Reputation: 45
Hello everybody!!! I have a problem with forms, below is the code, any help will be appreciated...
views.py
def my_registration_view(request):
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username=form.cleaned_data['username'],
first_name=form.cleaned_data['first_name'],
last_name=form.cleaned_data['last_name'],
email=form.cleaned_data['email'],
password=form.cleaned_data['password'],)
user.save()
return HttpResponseRedirect(reverse('profile', args=[user.id]))
else:
return render_to_response('register.html', {'form': form}, context_instance=RequestContext(request))
else:
form = MyForm()
context = {'form': form}
return render_to_response('register.html', context, context_instance=RequestContext(request))
my forms.py which works fine
class MyForm(forms.Form):
username = forms.CharField(max_length=25)
first_name = forms.CharField(max_length=25)
last_name = forms.CharField(max_length=25)
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput())
and here is my forms.py when it is replaced, stopped showing the fields.
class MyForm(forms.Form):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'password']
here is the register.html
<form action="{% url 'register' %}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type='submit' value='Submit' />
</form>
Upvotes: 1
Views: 1074
Reputation: 3399
Replace forms.Form with forms.ModelForm. This should work.
class MyForm(forms.ModelForm):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'password']
Upvotes: 3
Reputation: 23
Try like this;
form = MyForm(request.POST) if request.method == 'POST':
This is logical error your form should be top.
Upvotes: 0
Reputation: 1
Try like this..
return render_to_response('register.html', {'form':form}, context_instance=RequestContext(request))
form is not coming for sure... instead dict as object let's do one iteration like this...
Upvotes: 0
Reputation: 2646
In you example you have not mentioned forms.typeField
, Look in the below example:
For you Html page some thing like this:
<form action="/your-name/" method="post">
<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
In forms.py you should have fields
form.py
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
For more examples and references look into : Django working with forms
Upvotes: 0