Reputation: 9123
I'm trying to make register possible on the homepage (register box appears onclick), so I don't have a seperate URL to handle registration. I'm trying to send the form through get_context_data
, however it's not working. Here's my code:
forms.py
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
confirm_password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = [
'username',
'password',
'confirm_password',
]
views.py
class BoxesView(ListView):
template_name = 'polls.html'
def get_context_data(self):
context = super(BoxesView, self).get_context_data()
# login
form = UserRegistrationForm(self.request.POST or None)
context['form'] = form
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = User.objects.create_user(username, password)
user.save()
return redirect('/')
return context
return context
def get_queryset(self):
pass
base.html
<form action="" enctype="multipart/form-data" method="post">{% csrf_token %}
<div class="registerBox">
{{ form.username }}
{{ form.password }}
<input type="submit" value="register"/>
</div>
</form>
The fields show up but after submitting the form it doesn't create a User because my form.is_valid is False. Any idea?
Upvotes: 0
Views: 253
Reputation: 10689
You shouldn't return a response from get_context_data()
. Instead, do that in the post()
method like this:
class BoxesView(ListView):
template_name = 'polls.html'
def post(self, request, *args, **kwargs):
form = UserRegistrationForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = User.objects.create_user(username, password=password)
return redirect('/')
else:
return self.get(request, *args, **kwargs)
def get_context_data(self):
context = super(BoxesView, self).get_context_data()
context['form'] = UserRegistrationForm()
return context
Upvotes: 1
Reputation: 588
Looks like your Form expects to have confirm_password
submitted, but that's not part of your html form.
Upvotes: 0