python - How to change this regular html form into django form? -
i want change following html form:
@transaction.atomic def register(request): if request.method == "post": fname = request.post['first_name'] lname = request.post['last_name'] mobile = request.post['mobile'] """this section replaces multiple characters blank value mobile number has nothing except numeric values """ rep = ['+', '-', ' ', '.'] in rep: mobile = mobile.replace(i, '') company = request.post['company'] email = request.post['email'] u = user.objects.create_user(mobile, email, '1234', first_name=fname, last_name=lname) u.save() p = userprofile.objects.create(user=u, company=company, mobile=mobile) p.save() return httpresponse("registration complete! please head on <a href='/login/'>login page</a> start using sms panel.") return render(request, "message/register.html", {})
into django form because need learn how use them, need fields filled before registration completes, don't want optional fields. following i've come documentation.
views.py
@transaction.atomic def register(request): if request.method == "post": form = registerform(request.post) if form.is_valid(): # guess need help. thanks. else: form = registerform() return render(request, "message/register.html", {'form': form})
register.html
<form method="post" action=""> {% csrf_token %} {{ form }} <input type="submit" value="register"/> </form>
you can create form registerform
, add process of cleaning of mobile clean_mobile
function in forms.py
. in views.py
, can access form data using form.cleaned_data
dictionary.
you can below:
forms.py
from django import forms class registerform(forms.form): first_name = forms.charfield(max_length=100) last_name = forms.charfield(max_length=100) mobile = forms.charfield() company = forms.charfield(max_length=100) email = forms.emailfield() def clean_mobile(self): mobile = self.cleaned_data['mobile'] rep = ['+', '-', ' ', '.'] in rep: mobile = mobile.replace(i, '') return mobile
views.py
@transaction.atomic def register(request): if request.method == "post": form = registerform(request.post) if form.is_valid(): u = user.objects.create_user(form.cleaned_data['mobile'], form.cleaned_data['email'], '1234', first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name']) u.save() p = userprofile.objects.create(user=u, company=form.cleaned_data['company'], mobile=form.cleaned_data['mobile']) p.save() return httpresponse("registration complete! please head on <a href='/login/'>login page</a> start using sms panel.") else: form = registerform() return render(request, "message/register.html", {'form': form})
Comments
Post a Comment