I Want To Create A User Like Signup or register when i hit submit button i got this error:
UnboundLocalError at /signup/
i want to signup user:
local variable 'usercustom' referenced before assignment
here is my Views.py
def signup(request):
registered = False
if request.method == "POST":
user_form = UserForm(request.POST or None)
custom_form = UserCustom(request.POST or None)
if user_form.is_valid() and custom_form.is_valid():
user = user_form.save(commit=False)
user.save()
custom = custom_form.save(commit=False)
custom.user = user
custom.save()
registered = True
else:
print(user_form.errors,custom_form.errors)
else:
user_form = UserForm()
usercustom = UserCustom()
return render(request,'form.html',{'user_form':user_form,'usercustom':usercustom,'registered':registered})
here is my Form.html
{% extends "base.html" %}
{% block body_block %}
<div class="content-section">
{% if registerd %}
<h1>Thank Your For registering!</h1>
{% else %}
<h1>Register Here</h1>
<h3>Fill out the form</h3>
<form enctype="multipart/form-data" method="POST">
{% csrf_token %}
{{ user_form.as_p }}
{{ usercustom.as_p }}
<input type="submit" value="Register!" class="btn btn-danger">
</form>
{% endif %}
</div>
{% endblock %}
It is because usercustom is not declared when you tried to send POST request. You need to rename custom_form variable to usercustom. I have simplified your code for you.
def signup(request):
registered = False
if request.method == "POST":
user_form = UserForm(request.POST or None)
usercustom = UserCustom(request.POST or None)
if user_form.is_valid() and usercustom.is_valid():
user = user_form.save(commit=False)
user.save()
custom = usercustom.save(commit=False)
custom.user = user
custom.save()
registered = True
else:
print(user_form.errors, usercustom.errors)
else:
user_form = UserForm()
usercustom = UserCustom()
return render(request,'form.html',{'user_form':user_form,'usercustom':usercustom,'registered':registered})
Related
I'm trying to make a view containing one form and one formset but something does not work.
both form and formset after checking if .is_valid returns false. I do not really undersand why it is like that
def ProductCreateView(request):
context = {}
created_product = None
form = ProductForm()
if request.method == 'POST':
form = ProductForm(request.POST)
if form.is_valid():
created_product = form.save()
print("Successfully created new product: {}".format(created_product))
else:
print("form is not valid")
#print(request.POST) returns csrfmiddlewaretoken ...
#print(request.FILES) returns file : inmemoryuploadedfile ...
#print(list(request.POST.items()))
context['form'] = form
formset = ProductPhotoInlineFormset()
if request.method=='POST':
formset = ProductPhotoInlineFormset(request.POST or None, request.FILES or None, instance=created_product)
if formset.is_valid():
created_images = formset.save()
print("Successfully created new imagest: {}".format(created_images))
else:
print("formset is not valid")
context['formset'] = formset
return render(request, "Ecommerce/create_product_test.html", context)
my template - create_product_test.html
{% extends 'base.html' %}
{% block content %}
<div id="alert-box">
</div>
<div id="image-box" class="mb-3">
</div>
<div id="image-box"></div>
<div class="form-container">
<button class="btn btn-primary mt-3 not-visible" id="confirm-btn">confirm</button>
<form method="POST" enctype="multipart/form-data" action="" id="image-form">
{% csrf_token %}
<div>
{{form}}
{{formset.management_form}}
{{formset.as_p}}
</div>
</form>
</div>
{% endblock content %}
forms.py file
ProductPhotoInlineFormset = inlineformset_factory(
Product,
Photo,
fields=('file',),
form=PhotoForm,
extra=1,
)
where is the problem ?
You can find out what's wrong with the form with:
print(form.errors)
print(form.non_field_errors())
and for a formset:
print(formset.errors)
print(formset.non_form_errors())
This way, you can easily find out why the form is not valid.
So I'm making a to-do list and I made a booleanfield modelform which has attribute "complete". I want that user to check it when it's complete and I tried wriring if task.complete == True cross out the item and it didn't work(it only worked when I checked it from the admin panel). Then I tried form.complete instead of task.complete and it doesn't do anything.
models:
class Task(models.Model):
title = models.CharField(max_length=200)
complete = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
forms:
from .models import *
class TaskForm(forms.ModelForm):
title = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Add new task...'}))
class Meta:
model = Task
fields = '__all__'
html:
<div class="main-container">
<form method="POST" action="/">
{% csrf_token %}
<input type="submit"/>
{{ form.title }}
</form>
{% for task in tasks %}
{{ form.complete }}
{% if form.complete == True %}
<h1><strike>{{task.title}}</strike></h1>
{% else %}
<h1>{{task.title}}</h1>
{% endif %}
{% endfor %}
</div>
views:
def index(request):
tasks = Task.objects.order_by('-created')
form = TaskForm()
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
context = {
'tasks': tasks,
'form': form,
}
return render(request, 'to-do.html', context)
There are some problems with your code I don't know how to explain. Try this. It should work.
<div class="main-container">
<form method="POST" action="/"> # create new task
{% csrf_token %}
{{ form.title }}
<input type="submit" name="new-task"/>
</form>
<form method="post"> # update task status
{% csrf_token %}
{% for task in tasks %}
{% if task.complete %}
<input type="checkbox" name="if_completed" checked value="{{ task.pk }}">
<h1><strike>{{task.title}}</strike></h1>
{% else %}
<input type="checkbox" name="if_completed" value="{{ task.pk }}">
<h1>{{task.title}}</h1>
{% endif %}
{% endfor %}
<input type="submit" name="update-task"/>
</form>
</div>
view.py (Only for form, add your other code with it)
from django.http import HttpResponseRedirect
from django.urls import reverse
def index(request):
tasks = Task.objects.order_by('-created')
form = TaskForm()
if request.method == 'POST':
if 'new-task' in request.POST:
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('home')) # replace home with url name where you want to redirect
elif 'update-task' in request.POST:
task_pk = request.POST.getlist("if_completed")
for i in task_pk:
Task.objects.filter(pk=i).update(complete=True) # I have replace pk with i here
return HttpResponseRedirect(reverse('home')) # replace home with url name where you want to redirect
context = {
'tasks': tasks,
'form': form,
}
return render(request, 'to-do.html', context)
in forms.py
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = ('title',)
widgets = {
'title': forms.TextInput(attrs={'placeholder':'Add new task...'})
}
This should work. There may be be some error because of typos or indentation. Let me know if you get any issue
def index(request):
tasks = Task.objects.order_by('-created')
form = TaskForm()
context = {
'tasks': tasks,
'form': form,
}
if request.method == 'POST':
if 'new-task' in request.POST:
form = TaskForm(request.POST)
if form.is_valid():
form.save()
elif 'update-task' in request.POST:
task_pk = request.POST.getlist("if_completed")
for i in task_pk:
Task.objects.filter(pk=pk).update(complete=True)
return render(request, 'to-do.html', context)
hi i have a problem with login function in django ,when i loggin succes see when user is logged but main.html didnot .
wiews
def user_login(request):
context = {}
if request.method == "POST":
username = request.POST['username']
password = request.POST["password"]
user = authenticate(request,username=username,password=password)
if user.is_authenticated:
print("1")
login(request, user)
if request.GET.get('next',None):
print("2")
return HttpResponseRedirect(request.GET['next'])
return HttpResponseRedirect(reverse('success'))
else:
print("3")
context["error"] = "nieprawidlowe dane"
return render(request,'auth/login.html',context)
else:
print("4")
return render(request,'auth/login.html',context)
#login_required(login_url="/login/")
def success(request):
c = {}
c['user'] = request.user
return render(request,'auth/success.html',c)
and in here is succes and on this page django can see when user is logged
{% extends 'main.html' %}
{% block article %}
<p>User <b>{{ user.username }}</b> jestes zalogowony</p>
<form method="post" action="/logout/">
{% csrf_token %}
<input type="submit" value="Logout">
</form>
{% endblock %}
but main.html didnot see user
I've built a "firewall" login form that I want to put in front of my
actual production website while I develop the site. The idea is to try
and keep the "bad guys" out of the site and at the same time see what
usernames and passwords they're using. The problem I'm having is that
if I enter an invalid username/password pair, my form's error message
doesn't get displayed. I realize that for my purposes, it it might be
better to not display any error message at all but I'd still like to
understand what the problem is. Can anyone see what I'm doing wrong?
Thanks.
# views.py
import logging
logger = logging.getLogger(__name__)
from django.contrib.auth import authenticate
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.views import login
from django.http import HttpResponseRedirect
def firewall_login(request, *args, **kwargs):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
username = request.POST['username']
password = request.POST['password']
if form.is_valid():
fw_username = form.cleaned_data['username']
fw_password = form.cleaned_data['password']
user = authenticate(username=fw_username, password=fw_password)
if user is not None:
if user.is_active:
login(request, user)
logger.info("User '%s' logged in." % fw_username)
return HttpResponseRedirect("/accounts/profile/")
else:
logger.info("User '%s' tried to log in to disabled account." % fw_username)
return HttpResponseRedirect("/accounts/disabled/")
else:
logger.info("User '%s' tried to log in with password '%s'." % (username, password))
form = AuthenticationForm(request) # Display bound form
else:
form = AuthenticationForm() # Display unbound form
return render(request, "registration/login.html", {"form": form,})
# login.html
{% extends "base.html" %}
{% block content %}
{% if form.errors %}
<p class="alert alert-error">Sorry, that's not a valid username or password</p>
{% endif %}
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-error">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for field in form.non_field_errors %}
<div class="alert alert-error">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
<form action="" method="post">
{% csrf_token %}
<p><label for="username">Username:</label>{{ form.username }}</p>
<p><label for="password">Password:</label>{{ form.password }}</p>
<input type="hidden" name="next" value="{{ next|escape }}" />
<input class="btn btn-primary" type="submit" value="login" />
</form>
{% endblock %}
It's because you pass new form instance. Validation occurs on is_valid call.
So, just remove form = AuthenticationForm(request) in else block:
def firewall_login(request, *args, **kwargs):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
username = request.POST['username']
password = request.POST['password']
if form.is_valid():
fw_username = form.cleaned_data['username']
fw_password = form.cleaned_data['password']
user = authenticate(username=fw_username, password=fw_password)
if user is not None:
if user.is_active:
login(request, user)
logger.info("User '%s' logged in." % fw_username)
return HttpResponseRedirect("/accounts/profile/")
else:
logger.info("User '%s' tried to log in to disabled account." % fw_username)
return HttpResponseRedirect("/accounts/disabled/")
else:
logger.info("User '%s' tried to log in with password '%s'." % (username, password))
else:
form = AuthenticationForm() # Display unbound form
return render(request, "registration/login.html", {"form": form,})
When I submit this form, neither are saved in the database but the HttpResponseRedirect works successfully. Any ideas why?
views.py
#login_required
def entry(request):
fantasyTeamForm = FantasySeasonForm() #Form to store each player in the fantasy team
seasonUserTournForm = PartialSeasonEntryForm()
season_tournament_id = 1
tournament_classic = Tournament(pk=season_tournament_id)
user_instance = request.user
if request.method == 'POST':
fantasyTeamForm = FantasySeasonForm(request.POST or None)
fantasyTeamForm.fields
if fantasyTeamForm.is_valid():
fantasyTeamForm.save(commit=False)
seasonUserTourn = ClassicSeasonUserList(
tournament=tournament_classic,
fantasy_team=fantasyTeamForm['FANTASY_TEAM_ID'],
user=user_instance.id,
)
seasonUserTournForm = PartialSeasonEntryForm(request.POST or None, instance=seasonUserTourn)
seasonUserTournForm.fields
if seasonUserTournForm.is_valid():
seasonUserTournForm.save()
fantasyTeamForm.save()
return HttpResponseRedirect('/season/entrysuccess') #page on success
args = {}
args.update(csrf(request))
args['form'] = fantasyTeamForm
args['form2'] = seasonUserTournForm
return render_to_response('entry.html', args, context_instance=RequestContext(request))
entry.html
<h2><b>Choose your team:</b></h2><br>
{% for field in form %}
{{field.error}}
{% endfor %}
{% for field in form2 %}
{{field.error}}
{% endfor %}
<form action="/season/entrysuccess" method="post"> {% csrf_token %}
{{form2}}
<br><br>
{{form.as_ul}}
<br>
<input type="submit" value="Submit Team" />
</form>
form action in html should have been:
<form action="/season/entry" method="post">
instead of
<form action="/season/entrysuccess" method="post">