Form isn't displayed in template - django

I'm new to django and I've been following a tutorial to help me create my project. My problem is that the form and its fields don't show up on my html page.
line of code from my html file
<form action="admin/signup/" method="post">
<div class="form-horizontal form-label-left">
{% csrf_token %}
{% for field in signupForm %}
<p>
{{ field.label_tag }}<br>
{{ field }}
{% if field.help_text %}
<small style="color: grey">{{ field.help_text }}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
</p>
{% endfor %}
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-4">
<button class="btn btn-primary">Cancel</button>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</div>
</form>
my signup form class
class SignUpForm(UserCreationForm):
usertype = forms.CharField(max_length=10)
userID = forms.CharField(label="User ID")
class Meta:
model = User
fields = (
'username', 'first_name', 'last_name', 'email',
'password1', 'password2', 'userID', 'usertype')
and my signup page view
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db()
user.profile.usertype = form.clean_data.get('usertype')
user.profile.userID = form.clean_data.get('userID')
user.save()
else:
form = SignUpForm()
context = {
'signupForm' :form
}
return render(request, 'admin.html', context)
any possible solutions and suggestions are appreciated, thanks!

May be indentation require in SignUpForm. Is it!!

Related

Django: User Login only working with terminal created users

I'm only new to django & this is my first time posting on stack overflow so appologies if I havent done this right.
My problem is that when I use my login function, it only seems to work with those created with the createsuperuser command in the terminal. Those created within the website just dont work.
The users show within the admin panel and have a password within them.
models.py
class Trickster_User(AbstractBaseUser, PermissionsMixin):
UserID = models.AutoField(primary_key=True)
Email = models.EmailField(('Email Address'), unique=True)
Username = models.CharField(('Username'),max_length=25, unique=True)
FirstName = models.CharField(('First Name'),max_length=25)
LastName = models.CharField(('Last Name'),max_length=25)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
objects = CustomUserManager()
USERNAME_FIELD = 'Email'
REQUIRED_FIELDS = ['Username', 'FirstName', 'LastName']
def __str__(self):
return self.FirstName + ' ' + self.LastName
views.py
def user_login(request):
context = {}
user = request.user
if user.is_authenticated:
return redirect('home')
if request.method == "POST":
form = UserAuthenticationForm(request.POST)
if form.is_valid():
Email = request.POST['Email']
password = request.POST['password']
user = authenticate(Email=Email, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
form = UserAuthenticationForm()
context['user_login'] = form
return render(request, 'authentication/login.html', context)
forms.py
class UserAuthenticationForm(forms.ModelForm):
Email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}))
password = forms.CharField(label='password', widget=forms.PasswordInput(attrs={'class':'form-control'}))
class Meta:
model = Trickster_User
fields = ('Email', 'password')
def clean(self):
Email = self.cleaned_data['Email']
password = self.cleaned_data['password']
if not authenticate(Email=Email, password=password):
raise forms.ValidationError("Invalid Login")
login.html
{% block content %}
<div class="shadow p-4 mb-5 bg-body rounded">
<h1> Login </h1>
<br/><br/>
<form action="" method=POST enctype="multipart/form-data">
{% csrf_token %}
{% for feild in user_login %}
<p>
{{ feild.label_tag }}
{{ feild}}
{% if feild.help_text %}
<small style="color: grey">{{ feild.help_text }}</small>
{% endif %}
{% for errors in field.errors %}
<p style="color: red">{{ feild.errors }}</p>
{% endfor %}
{% if user_login.non_feild_errors %}
<div style="color:red";>
<p>{{ user_login.non_feild_errors }}</p>
</div>
{% endif %}
</p>
{% endfor %}
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
{% endblock %}
Code to register users:
views.py
def register_user(request):
context = {}
if request.method == "POST":
form = UserRegistrationForm(request.POST)
if form.is_valid():
form.save()
Email = form.cleaned_data.get('Email')
raw_password = form.cleaned_data.get('password1')
user = authenticate(Email=Email, password=raw_password)
login(request, user)
messages.success(request, ("Registration Successful! Password"))
return redirect('home')
else:
context['UserRegistrationForm'] = form
else:
form = UserRegistrationForm()
context['UserRegistrationForm'] = form
return render(request, 'authentication/register_user.html', context)
register_user.html
{% block content %}
{% if form.errors %}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
There was an error with your form!
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endif %}
<div class="shadow p-4 mb-5 bg-body rounded">
<h1> Register </h1>
<br/><br/>
<form action="{% url 'register_user' %}" method=POST enctype="multipart/form-data">
{% csrf_token %}
{% for feild in UserRegistrationForm %}
<p>
{{ feild.label_tag }}
{{ feild}}
{% if feild.help_text %}
<small style="color: grey">{{ feild.help_text }}</small>
{% endif %}
{% for errors in field.errors %}
<p style="color: red">{{ feild.errors }}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
{% endblock %}
Ive seen one other post on something simmilar to this but the only solution posted was to change the 'is_active' status to True by default.
I tried this and am still running into same issue.

django form errors not showing on template

I'm using the basic django registration form and I'm not getting any errors displayed. I've seen a bunch of answers and nothing is working for me. I'm not sure if it's because I have custom css for the page or bootstrap or something else. Basically how do I display the errors in this particular case.
Here's my form:
<div class="form-content">
<h1>Sign Up</h1>
{% if user.is_authenticated == False %}
<form method="POST">
{% csrf_token %} {{form.as_p}}
<button class="btn form-btn">Sign Up</button>
<h4><span>or</span></h4>
<a
class="btn google-btn"
href="{% provider_login_url 'google' %}"
role="button"
style="text-transform: none; width: 100%"
>
<img
width="20px"
style="margin-bottom: 3px; margin-right: 5px"
alt="Google sign-in"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Google_%22G%22_Logo.svg/512px-Google_%22G%22_Logo.svg.png"
/>
Sign up with Google
</a>
</form>
{% else %}
<p>You're already registered...</p>
{% endif %}
</div>
Here's my view:
class UserRegistration(generic.CreateView):
form_class = RegisterForm
template_name = 'registration/registration.html'
def form_valid(self, form):
user = form.save()
form.registration_notification()
login(self.request, user, backend='django.contrib.auth.backends.ModelBackend')
return redirect(self.request.GET.get('next'))
and form:
class RegisterForm(UserCreationForm):
email = forms.EmailField()
first_name = forms.CharField(max_length=100)
last_name = forms.CharField(max_length=100)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')
def registration_notification(self):
email = self.cleaned_data['email']
username = self.cleaned_data['username']
if self.is_valid():
registration_notification_task.delay(email, username)
I'm not sure where to return the errors or where to validate the form and no answers for other questions have helped my situation. Now when I submit an invalid form there are no errors the page just doesn't submit. There's not even an error in the network tab so it's probably happening on the html side.
Updating my post following comments below:
**forms.py** (dont forget the import bit)
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
class RegisterForm(UserCreationForm):
class Meta:
model = User
fields = ["username", "email", "password1", "password2",]
views.py
def register_user(request):
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
new_user = form.save()
new_user = authenticate(username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],)
login(request, new_user)
messages.success(request,("Registration succesful!"))
return HttpResponseRedirect("/home")
else:
form = RegisterForm()
return render(request,'main/registration/register_user.html',{'form':form})
registration template
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-md-5 mx-auto">
<div id="second">
<div class="myform form ">
<div class="logo mb-3">
<div class="col-md-12 text-center">
<h1 >Signup</h1>
</div>
</div>
<form method="POST" action = "{% url 'register_user' %}" class="form-group">
{% csrf_token %}
{{ form| crispy }}
<div class="col-md-12 text-center mb-3">
<button type="submit" class=" btn btn-block mybtn btn-primary tx-tfm">Let's do it!</button>
</div>
<div class="col-md-12 ">
<div class="form-group">
<p class="text-center">Already have an account?</p>
</div>
</div>
</div>
</form>
</div>
</div>
{% endblock %}

Django custom registration form html

New to Django and I am attempting to create a customer registration form and was successful. However the tutorial I followed showed me how to iterate through a loop, the contents of my registration_form which doesn't really give me much flexibility from a UI perspective, or so it seems. Can someone tell me how to customize this form based on the code I've got?
HTML:
<h1>This is the register.html</h1>
<div class="col-md-4 offset-md-4">
<form method="post">
{% csrf_token %}
{% for field in registration_form %}
<p>
{{field.label_tag}}
{{field}}
{% if field.help_text %}
<small style="color: grey;">{{field.help_text}}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: grey;">{{error}}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit">Register</button>
</form>
</div>
views.py
def registration_view(request):
context = {}
if request.POST:
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email')
raw_password = form.cleaned_data.get('password1')
account = authenticate(email=email, password=raw_password)
login(request, account)
return redirect('home')
else:
context['registration_form'] = form
else:
form = RegistrationForm()
context['registration_form'] = form
print(context)
return render(request, 'accounts/register.html', context)
forms.py
class RegistrationForm(UserCreationForm):
email = forms.EmailField(max_length=100, help_text='Required. Add a valid email address')
class Meta:
model = Account
fields = ('email', 'username', 'password1', 'password2', 'first_name', 'last_name')
the form renders and works fine with registration, just looks kinda crappy. thanks!
You could render each field individually and take advantage of bootstrap styling as well. For example for the email field, you could have something like below
<div class="form-group">
{{ registration_form.email.label_tag }}
{{ registration_form.email }}
</div>
You can also have a div below it to display its errors on post
<div class="errors">
{% if registration_form.email.errors %}
{% for error in registration_form.email.errors %}
<strong>{{ error|escape }}</strong>
{% endfor %}
{% endif %}
</div>

Django contact form doesnt submit

I am trying to set up a contact form. I have implemented the Django-crispy-forms and now my form is not submitted (I don't have any errors).
I've added action="" to my form in my template without any success.
forms.py
class ContactForm(forms.Form):
name = forms.CharField(max_length=100, help_text='Enter your name or username')
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea(attrs={'rows': 3, 'cols': 40}), help_text='Example: I forgot my password!')
views.py
def contact_us(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
sender_name = form.cleaned_data['name']
sender_email = form.cleaned_data['email']
message = "From {0}:\n\n{1}".format(sender_name, form.cleaned_data['message'])
send_mail('PLM_Tool contact', message, sender_email, ['myadress#gmail.com'])
return redirect('home:index')
else:
form = ContactForm()
return render(request, 'accounts/contact.html', {'form': form})
urls.py
app_name = 'accounts'
urlpatterns = [path('contact/', views.contact_us, name='contact'),]
contact.html
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block main %}
<form method="post" action="">
{% csrf_token %}
<div class="row">
<div class="col-6">
{{ form.name|as_crispy_field }}
</div>
<div class="col-6">
{{ form.email|as_crispy_field }}
</div>
<div class="col-6">
{{ form.message|as_crispy_field }}
</div>
</div>
</form>
<button type="submit" class="btn btn-success">Send</button>
Cancel
<br><br>
{% endblock %}
Here is the problem, and do not give action to form
crispy forms create the field not the button.
<form method="post">
{% csrf_token %}
<div class="row">
<div class="col-6">
{{ form.name|as_crispy_field }}
</div>
<div class="col-6">
{{ form.email|as_crispy_field }}
</div>
<div class="col-6">
{{ form.message|as_crispy_field }}
</div>
</div>
<button type="submit" class="btn btn-success">Send</button>
</form>
just add the button inside the form

django: form.is_valid always giving error

i am working on login page but my form always gives me error, please find my code below, please see view.py it response always go to else statment of "if form.is_valid():" condition. please help
here you can see form.py
from django.contrib.auth.models import User
from django import forms
class LoginForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'password']
this is my view.py
def login_view(request):
template_name = 'user/login.html'
form_class = LoginForm
if request.method == "POST":
form = form_class(data=request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
try:
login(request, user)
return redirect('user:profile')
except:
form = form_class(None)
return render(request, template_name, {'form': form, 'custom_error': 'Error'})
else:
return HttpResponse("<h1>Data is invalid</h1>")
else:
if request.user.is_authenticated():
return redirect('user:profile')
else:
form = form_class(None)
return render(request, template_name, {'form': form,})
user/login.html
{% block body %}
<div class="section">
<div class="container">
<div class="row">
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="col-md-5">
<img src="{% static 'user/images/favicon.png' %}" class="img-responsive">
</div>
<div class="col-md-6">
{% include 'user/form-template.html' %}
<div class="col-sm-offset-2 col-sm-10" align="right">
<button type="submit" class="btn btn-default" autofocus>Sign In</button>
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
and finally this is my form-template.html file
{% for field in form %}
<div class="col-md-8">
<div class="col-md-4">
<label>{{ field.label_tag }} </label>
</div>
<div class="col-md-4">
{{ field }}
<div>
<span>{{ field.errors }}</span>
</div>
<div>
<span class="text-danger small">{{ custom_error }}</span>
</div>
</div>
</div>
{% endfor %}
If you are using ModelForm, you are going to operate on django model objects, creating, updating, etc. If you are only trying to login, use Form instead.
Thanks its solved, I just Changed My Form no it looks like this.
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
now i am not using built-in form and i also changed ModelForm to Form.