This is my first time to use SetPasswordForm. The form is not valid but does not shows error message. So I'm having hard time to figure out which part went wrong.
urls.py
url(r'^password_change/(?P<username>[-\w.]+)/$', views.password_change, name='password_change'),
url(r'^password_change_done/$', views.password_change_done, name='password_change_done'),
When user input their new password and if the action succeeded, the page will redirect to password_change_done.
views.py
#login_required
def password_change(request, username):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
oldpassword = form.cleaned_data.get('oldpassword')
password1 = form.cleaned_data.get('password1')
password2 = form.cleaned_data.get('password2')
if password1 == password2:
update_session_auth_hash(request, form.username)
form.save()
return HttpResponseRedirect('/blog/password_change_done/')
else:
return render(request, 'blog/profile.html', {'error_message': 'password mismatch'})
else:
return render(request, 'blog/profile.html', {'error_messages': form.errors })
else:
return redirect(reverse('blog:profile', args=[form.user.get_username()]))
#login_required
def password_change_done(request):
return render(request, 'blog/password_change_done.html')
forms.py
class PasswordChangeForm(SetPasswordForm):
error_messages = dict(SetPasswordForm.error_messages, **{
'password_incorrect': ("Your old password was entered incorrectly. Please enter it again."),
})
oldpassword = forms.CharField(
label=("Old password"),
strip=False,
widget=forms.PasswordInput(attrs={'autofocus': True}),
)
field_order = ['oldpassword', 'password1', 'password2']
def __init__(self, user, data, **kwargs):
self.user = user
super(PasswordChangeForm, self).__init__(data, **kwargs)
def clean_oldpassword(self):
oldpassword = self.cleaned_data["oldpassword"]
if not self.user.check_password(oldpassword):
raise forms.ValidationError(
self.error_messages['password_incorrect'],
code='password_incorrect',
)
return oldpassword
templates.py
{{ form.errors }}
{{ form.non_field_errors }}
{% if error_message %}
<h2><strong>{{ error_message }}</strong></h2>
{% else %}<br>
{% endif %}
<form class="form-horizontal" role="form" action="{% url 'blog:password_change' user.username %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="button-primary">submit</button></div>
</form>
I put {{ form.errors }} and {{ form.non_field_errors }} so if error happens than it can display error message on website. However till now no message displayed and seems like nothing happens whenever user click submit button.
You have quite a few issues here, but the main problem - as I have told you before - is how you are passing things to the template. You need to follow the pattern as shown in the documentation, and you need to be consistent about your variable naming.
Firstly, move your password check to the form itself:
class PasswordChangeForm(SetPasswordForm):
...
def clean(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 1= password2:
raise forms.ValidationError('password mismatch')
Now, fix your view:
def password_change(request, username):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
update_session_auth_hash(request, form.username)
form.save()
return HttpResponseRedirect('/blog/password_change_done/')
else:
return render(request, 'blog/profile.html', {'form': form })
else:
return redirect(reverse('blog:profile', args=[username]))
And finally, remove {{ error_messages }} from your template.
Related
I'm making Django app and I have an issue, I've never had problem with before. As always in form view, I'm checking if request.method == 'POST' but somehow it returns False,
My code looks like that:
def recipe_create_view(request):
context = {}
form = RecipeForm(request.POST or None)
IngredientFormset = formset_factory(IngredientForm)
formset = IngredientFormset(request.POST or None)
context['form'] = form
context['formset'] = formset
if request.method == 'POST':
if form.is_valid():
if formset.is_valid():
form.save()
print("made a recipe")
for form in formset:
child = form.save(commit=False)
child.recipe = parent
child.save()
print("made a Ingredient")
else:
print("formset is not valid")
else:
print("form is not valid")
else:
print("request method is not correct")
return render(request, 'recipes/create_recipe.html', context)
create_recipe.html file:
<form method="POST">
{% csrf_token %}
<label>recipe</label>
<p>{{form}}</p>
<label>ingredients</label>
{% for form in formset %}
<ul>
<label>name</label>
<li>{{ form.name }}</li>
<label>quantity</label>
<li>{{ form.quantity }}</li>
</ul>
{% endfor %}
<div>
<input type="submit" value="submit" class="button-33" role="button">
</div>
</form>
Where is the problem?
It is necessary to return HttpResponseRedirect after dealing with POST data, the tip is not specific to Django, it's a good web practice in general.
Also, try to maintain both GET and POST request separately, so try below view:
def recipe_create_view(request):
context = {}
form="" # for the error of variable refrenced before assignment.
IngredientFormset=""
formset=""
if request.method == 'POST':
form = RecipeForm(request.POST)
IngredientFormset = formset_factory(IngredientForm)
formset = IngredientFormset(request.POST)
if form.is_valid():
if formset.is_valid():
form.save()
print("made a recipe")
for form in formset:
child = form.save(commit=False)
child.recipe = parent
child.save()
print("made a Ingredient")
return redirect('some_success_path_name')
else:
print("formset is not valid")
else:
print("form is not valid")
else: # GET method
print("request method is GET")
form = RecipeForm()
IngredientFormset = formset_factory(IngredientForm)
formset = IngredientFormset()
context['form'] = form
context['formset'] = formset
return render(request, 'recipes/create_recipe.html', context)
add action in your HTML form and POST in small case.
<form action="/your_backend_url_to_view/" method="post">
{% csrf_token %}
<label>recipe</label>
<p>{{form}}</p>
<label>ingredients</label>
{% for form in formset %}
<ul>
<label>name</label>
<li>{{ form.name }}</li>
<label>quantity</label>
<li>{{ form.quantity }}</li>
</ul>
{% endfor %}
<div>
<input type="submit" value="submit" class="button-33" role="button">
</div>
</form>
I'm doing my first question on StackOverFlow about something ig going me crazy.
My project is an Auction site, and is based on django and Web3 to interact with a smart contract deployed on my Ganache.
Now I have got this error on my view :
ValueError at /getGiftFromFaucet/ The view contract.views.getGiftFromFaucet didn't return an HttpResponse object. It returned None instead.
The problem is:
If I register a customer and an address,
then I try to receive tokens from the Faucet,
If I put customer address I don't receive anything.
But if i select another address, I receive token in the first address.
I really don't understand why...
my Model:
class Customer(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
address = models.CharField(max_length=256,
blank=False,
null=False,
unique=True,
error_messages={'unique': 'This address is already registered'})
tokenBalance = models.FloatField(default=0)
dollarBalance = models.FloatField(default=0)
my Registration to the site
def registrationForm(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
address = form.cleaned_data['address']
user = User.objects.create_user(
username=username,
password=password,
)
newCustomer = Customer(
user=user,
dollarBalance=random.randrange(500, 1500),
address=address,
tokenBalance=0
)
user.save()
newCustomer.save()
user = authenticate(username=username, password=password)
login(request, user)
messages.success(request, f'''Welcome in DNote {request.user}''')
return redirect('homepage')
else:
form = RegistrationForm()
context = {'form': form}
return render(request, 'registration.html', context)
my Form:
class ReceiveTokenFromFaucet(forms.ModelForm):
class Meta:
model = Customer
fields = ['address']
My view:
def getGiftFromFaucet(request):
customer = Customer.objects.get(user=request.user)
customerAddress = customer.address
if request.method == 'POST':
form = ReceiveTokenFromFaucet(request.POST)
if form.is_valid():
form.save(commit=False)
customerAddress = form.cleaned_data['address']
if customerAddress not in alreadyRecompensed:
contract.functions.transfer(
customerAddress, 100000000000000000000
).transact({'from': faucet})
alreadyRecompensed.append(customerAddress)
customer.tokenBalance += 100000000000000000000
customer.save()
messages.success(request, 'Your Tokens Are accreditate on your Account')
return redirect('/homepage/')
if customerAddress in alreadyRecompensed:
messages.error(request, 'Already Recompensed')
return redirect('/homepage/')
else:
form = ReceiveTokenFromFaucet()
context = {'form': form, 'alreadyRecompensed': alreadyRecompensed}
return render(request, 'requireFromFaucet.html', context)
My Html:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block head_title %}{{ block.super }} ReceiveFreeTokens {% endblock head_title %}
{% block content %}
<div class="row justify-content-center mt-4">
<div class="col-4">
<h2>DNote</h2>
<h3>Receive Free Tokens</h3>
<p>Available only one time</p>
<br>
<form method="POST" enctype="multipart/form-data" style="max-width:100%">
{% csrf_token %}
{{ form|crispy }}
<br>
<input type="submit" class="btn btn-info" value="Create">
</form>
</div>
</div>
{% endblock content %}
Good day!
I'm trying to create a form with four fields, like in the screenshot. I'm not getting anywhere yet.
Now I use this form in template:
<form>
<form id="FirstForm" action="{% url one.views.FirstForm %}" method="POST">
{% csrf_token %}
{{ form1 }}
</form>
<form id="SecondForm" action="{% url one.views.SecondForm %}" method="POST">
{% csrf_token %}
{{ form2 }}
</form>
<div>
<input type="submit" name="subform1" value="Отправить" class="form_button">
</div>
</form>
And here is the code in views.py:
def FirstForm(request):
if request.method == 'GET':
form = FirstForm()
return render(request, 'home.html', {'form':form})
else:
form = FirstForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
try:
send_mail(name, email, settings.EMAIL_HOST_USER, ['daribian#list.ru'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, 'home.html', {'form': form})
def SecondForm(request):
if request.method == 'GET':
form = SecondForm()
else:
form = SecondForm(request.POST)
if form.is_valid():
date = form.cleaned_data['date']
number = form.cleaned_data['number']
try:
send_mail(date, number, settings.EMAIL_HOST_USER, ['daribian#list.ru'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, 'home.html', {'form': form})
def successView(request):
return HttpResponse('Success!')
As well as the forms themselves:
class FirstForm(forms.Form):
name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'name_class'}), max_length=100, required=True)
email = forms.EmailField(widget=forms.TextInput(attrs={'class' : 'email_class'}), required=True)
class SecondForm(forms.Form):
date = forms.CharField(widget=forms.TextInput(attrs={'class' : 'my_name_class'}), max_length=100, required=True)
number = forms.EmailField(widget=forms.TextInput(attrs={'class' : 'my_email_class'}), required=True)
I keep getting various errors and I think I'm doing something wrong. Can someone tell me what my mistake is?
enter image description here
Am trying to create a chat forum in django . but to do this i needed to extend the User Model, But after extending it the profile image does not save
This is my model
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email = models.EmailField()
img = models.FileField(upload_to='media/', blank=True, null=True)
def __str__(self):
return self.user.username
#receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
My View:
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db() # load the profile instance created by the signal
user.profile.email = form.cleaned_data.get('email')
user.profile.img = form.cleaned_data.get('img')
user.save()
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=user.username, password=raw_password)
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'tforum/signup.html', {'form': form})
My Forms.py
class SignUpForm(UserCreationForm):
email = forms.EmailField(help_text='Required.')
img = forms.FileField(help_text='Upload Image')
class Meta:
model = User
fields = ('username', 'email', 'img', 'password1', 'password2', )
Signup.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
<p>
{{ field.label_tag }}<br>
{{ field }}
{% if field.help_text %}
<small style="color: grey">{{ field.help_text }}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit">Sign up</button>
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
The problem is that the user is not created.
If i remove the img from the code the user saves.
I have stripped away most of the styling
you should create a profileForm
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('email', 'img')
and update your signup.py
def update_signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
profile_form = ProfileForm(request.POST, instance=request.user.profile)
if form.is_valid() and profile_form.is_valid():
user = form.save()
user.refresh_from_db() # load the profile instance created by the signal
user.profile.email = form.cleaned_data.get('email')
user.profile.img = form.cleaned_data.get('img')
profile_form.save()
user.save()
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=user.username, password=raw_password)
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'tforum/signup.html', {'form': form})
I have done my best to store value in the model User, but i can't please guide me what is the error and why it does not work.
relevant code is:
urls.py
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='registration'),
url(r'^customer/add/$', views.UserFormView.as_view(), name='customer-add'),
]
i think post method is not working because when i click on the submit button the traceback was
'[26/Jul/2017 23:50:37] "GET /customer/add/?csrfmiddlewaretoken=nLX4YAZ1Tk6Zt5DJUJNM9fiYtw91pZwsrDdZwb5tpr80qKBos36eV9SZdR23c9BT&username=dq&email=admin%40c.com&password=password123 HTTP
/1.1" 200 2796
'
views.py
class UserFormView(View):
form_class = UserForm
template_name = 'registration/registration_form.html'
# display blank form
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
# process form data
def post(self,request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
# return username if credentials are correct
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('registration:index')
return render(request, self.template_name, {'form': form})
forms.py
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
labels = {
"email": "Your Email"
}
fields = [
'first_name',
'last_name',
'username',
'email',
'password',
]
registration_form.html
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form class="form-horizontal" action="" method="post">
{% csrf_token%}
{% include 'registration/form-template.html' %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>