Issue using the django usercreationform, not rendering form in HTML - python

im making a signup page in a django project using the UserCreationForm but when rendering my html i only see the submit button
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
def register(request):
form = UserCreationForm
return(render(request, 'register.html', {form: form}))
{% extends 'base.html' %}
{% block title %}Sign Up{% endblock %}
{% block body %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="button">
<button type="submit">Sign up</button>
</form>
{% endblock %}

You can not use the form as key of the context, you should use 'form'. Furthermore it is not a good idea to pass a reference to the class, you should create an instance of the form in the view, so:
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
def register(request):
form = UserCreationForm()
# use 'form' instead of form &downarrow; &downarrow;
return render(request, 'register.html', {'form': form})
If you had used a form object, instead of a reference to the class, it would have raised an error that a Form is not hashable. But since you used a reference to the form class, there was no error, and thus this remained undetected.

The problem is within the django views function..Use below code instead..
you should pass it as a string variable {'form' :form}
return render(request, 'register.html', {'form': form})

Related

Django register form

so, I made the registration page with django and it doesn't show the form
register.html
<form method="post">
{{ form.as_table }}
{% csrf_token %}
<input type='submit' value="Register">
</form>
and this is the views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = UserCreationForm()
return render(request, 'register.html', { 'form ' : form})
def login(request):
return render(request, 'login.html')
And all it shows is the register button
Could be one of two things:
Put the {% csrf_token %} before the form variable in your template.
Don't put any whitspace in the form key in your context dictionary (so instead of ' form ' it should be 'form')
I think you mistakenly wrote "form " instead of "form" and also put {% csrf_token %} in the form tag right before the rendering

'ManagementForm data is missing or has been tampered with' Issue

I am stuck with this error and I don't know what to do...
I followed the Django documentation here
I would like also to create a new Player object when I fill the empty extra form, but one requires field of the model must be based on request.user.team not seated directly by the user
Hope someone is familiar with ManagementForm
My files:
views.py
from django.shortcuts import render, redirect
from skeleton.models import Player
from django.contrib.auth.decorators import login_required
from .forms import PlayerForm
from django.forms import modelformset_factory
# Create your views here.
#login_required(login_url="/accounts/login/")
def team_area(request):
PlayerFormSet = modelformset_factory(Player, fields=('first_name', 'last_name'), extra=1)
if request.method == "POST":
player_formset = PlayerFormSet(
request.POST,
request.FILES,
queryset=Player.objects.all().filter(team=request.user.team),)
if player_formset.is_valid():
player_formset.save()
return redirect('team_area:home')
else:
player_formset = PlayerFormSet(queryset=Player.objects.all().filter(team=request.user.team))
return render(request, 'team_area/team_area.html', {'player_formset': player_formset})
team_area.html
{% extends 'base_layout.html' %}
{% block content %}
<h1>Area Squadra</h1>
<form method="post" action="">
{% csrf_token %}
{{ formset.management_form }}
{% for player_form in player_formset %}
{% for field in player_form %}
{{ field.label_tag }} {{ field }}
{% endfor %}
<br>
{% endfor %}
<input type="submit" value="Aggiorna">
</form>
{% endblock %}
A formset may contain more then a single form, so for saving the data from a formset in the view file, you have to loop through all the forms and save each form's data. Like in your views.py file you can write:
if player_formset.is_valid():
for form in player_formset:
form.save()
This will create as many new objects of Player as there are new forms in the formset (assuming you have not deleted any form or edited the pre-existing form).
One must also update the Management Form data in the .html file as soon as the user clicks on Add Player button
This is the solution I found and used using
.save(commit=False)
if request.method == "POST":
player_formset = PlayerFormSet(request.POST, request.FILES, queryset=Player.objects.all().filter(team=request.user.team),)
for player_form in player_formset:
if player_form.is_valid():
player = player_form.save(commit=False)
player.team = request.user.team
if player_formset.is_valid():
player_formset.save()

Forbidden (403) CSRF verification failed. Request aborted.in Django

Why does Django show this error: 'Forbidden (403)CSRF verification failed. Request aborted.' when I already have {% csrf_token %} in the form.
templates/core/signup.html
{% block content %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign up</button>
</form>
{% endblock %}
views.py
from django.contrib.auth.forms import UserCreationForm
from django.views.generic.edit import CreateView
class SignUpView(CreateView):
template_name = 'core/signup.html'
form_class = UserCreationForm
Since you are already passing on the csrf token from django.core.context_processors.csrf to the context manager. Check whether the form HTML has something like this or not:
<input type='hidden' name='csrfmiddlewaretoken' value="jqhdwjavwjagjzbefjwdjqlkkop2j3ofje" />
A couple of other things are required to make the csrf protection work (check out the docs):
Your browser has to accept cookies from your server
Make sure you have 'django.middleware.csrf.CsrfViewMiddleware' included as middleware in your settings.py (alternatively use the decorator csrf_protect() on particular views you want to protect)
In your views.py you need to pass the RequestContext in your render_to_response for the context processors to actually be run.
from django.template import RequestContext
context = {}
return render_to_response('my_template.html',
context,
context_instance=RequestContext(request))
the new render shortcut (django 1.3+) will do it for you:
from django.shortcuts import render
context = {}
return render(request, 'my_template.html', context)
For class-based view:
class MyFormView(View):
form_class = MyForm
initial = {'key': 'value'}
template_name = 'form_template.html'
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
# <process form cleaned data>
return HttpResponseRedirect('/success/')
return render(request, self.template_name, {'form': form})

Django Form not showing, only the button (NEW)

only my Submit button is popping up when i am trying to pass a form.
I even tried just copying the code from the Django website... Still does not work for me.
This is my forms.py
from django import forms
class contactForm(forms.Form):
name = forms.CharField(required=False, max_length=100, help_text='100 max.')
email = forms.EmailField(required=True)
comment = forms.CharField(required=True, widget=forms.Textarea)
This is my views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from .forms import contactForm
def contact(request):
form = contactForm(request.POST or None)
if form.is_valid():
print(request.POST)
context = locals()
return render(request, 'contact/contact.html', context)
def index(request):
return render(request, 'contact/contact.html')
This is my contact.html
{% extends "contact/base.html" %}
{% block content %}
<h1>Contact</h1>
<form method='POST' acion=''> {% csrf_token %}
{{ form.as_p }}
<input type='submit' value='submit form'/>
</form>
{% endblock %}
I really do not know what is wrong with this code...please help! Thanks
ps: I am new to python, maybe i need another version?
You have two views rendering the same template. One of them, contact, passes the form to the template. The other, index, does not, so there is nothing called form in the context and the result will be blank.

Django UserCreationForm neither gives error message nor registering user

I am beginner to python Django. And trying build an posting article website with the help of tutorials. I got stuck at UserCreationForm. I have created a form using UserCreationForm, but when I am submitting the form I am not able to neither submit the form nor getting any error message on the page.
My views.py code
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.template.context_processors import csrf
from django.contrib.auth.forms import UserCreationForm
def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
args = {}
args.update(csrf(request))
args['form'] = UserCreationForm()
print args
return render_to_response('register.html', args)
def register_success(request):
return render_to_response('register_success.html')
register.html
{% extends "base.html" %}
{% block content %}
<h2>Register</h2>
<form action="/accounts/register/" method="post"> {% csrf_token %}
{{form}}
<input type="submit" value="Register"/>
</form>
{% endblock %}
register_success.html
{% extends "base.hml" %}
{% block content %}
<h2>You have registered!</h2>
<p>Click Here to login again</p>
{% endblock %}
The problem is that you are always creating a blank form.
args['form'] = UserCreationForm()
This means that you do not see any errors for POST requests when the form is invalid.
Instead, you should only create the blank form for GET requests.
from django.shortcuts import render
def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
else:
form = UserCreationForm()
args = {'form': form}
return render(request, 'register.html', args)
Note that I have simplified the view by using render instead of the obsolete render_to_response. That means you don't need to handle csrf manually.
You can use Django Generic Views, specifically CreateView, it will make your life a lot easier. You can use it like so:
from django.views.generic import CreateView
class CreateUserView(CreateView):
template_name = 'register.html'
form_class = UserCreationForm
success_url = '/accounts/register_success'
Add this to your urls.py and you are good to go:
from mysite.views import CreateUserView
# add this url pattern
url(r'^sign_up/$', CreateUserView.as_view(), name='signup'),

Categories

Resources