Django Custom Password Reset Form widget not working - django

Stumped as to why my template isn't showing my custom password reset form.
Here is code:
forms.py
class CustomPasswordResetForm(PasswordResetForm):
def __init__(self, *args, **kwargs):
super(CustomPasswordResetForm, self).__init__(*args, **kwargs)
email = forms.EmailField(
label='', widget=forms.EmailInput(attrs={
'placeholder': 'placetest#test.com',
'class': 'form-field', }))
Views.py
class PasswordResetView(auth_views.PasswordResetView):
form_class = CustomPasswordResetForm
template_name = 'password_reset.html'
urls.py
urlpatterns = [
path('login/', LoginView.as_view(), name='login'),
path('password_reset', PasswordResetView.as_view(), name='password_reset'),
path('login_success/', login_success, name='login_success'),]
Template
{% load static %}
{% block title %}Home{% endblock %}
{% block content %}
<div class="form-container" id="pwrest">
<div class="form-title">
<h2>Enter your email address</h2>
</div>
<form method="POST">
{% csrf_token %}
<p>email</p>
<div>{{ form.email }}</div>
<input class="submit-button" type="submit" value="Send me instructions!">
</form>
</div>
</div>
{% endblock %}
CSS
.form-field{
width: 300px;
height:30px;
margin-bottom:5px;
margin-top:5px;
border:none;
border-radius: 5px;
background-color:whitesmoke;
}
Rendered HTML
<div class="form-title">
<h2>Enter your email address</h2>
</div>
<form method="POST">
<input type="hidden" name="csrfmiddlewaretoken" value="TOKEN">
<p>email</p>
<div><input type="email" name="email" autocomplete="email" maxlength="254" required id="id_email"></div>
<input class="submit-button" type="submit" value="Send me instructions!">
</form>
</div>
</div>
When I view the template in my browser, I am seeing the form field as the default, its almost like its just not recognizing the CSS class.
I'm not sure what I've missed.
.

Related

How do I use Django generic updateviews to update my model using individual form field values?

models.py:
from django.db import models
class Location(models.Model):
name = models.CharField(max_length=20)
is_source = models.BooleanField(default=False)
is_destination = models.BooleanField(default=False)
def __str__(self):
return self.name
views.py
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views import generic
from .models import Location
class LocationsListView(generic.ListView):
model = Location
template_name = 'locations/list.html'
context_object_name = 'locations'
class LocationUpdateView(generic.edit.UpdateView):
model = Location
fields = ['name', 'is_source', 'is_destination']
context_object_name = 'location'
template_name = 'locations/update.html'
success_url = reverse_lazy('locations:list')
class LocationDeleteView (generic.edit.DeleteView):
model = Location
template_name = 'locations/confirm_delete.html'
context_object_name = 'location'
success_url = reverse_lazy('locations:list')
locations/update.html
{% extends 'base.html' %}
{% block title %}Location Update{% endblock %}
{% block content %}
<section>
<div class="container">
<h1>Location Update</h1>
<div class="form-container">
<form method="post">
{% csrf_token %}
{% if form.errors %}
<div class="p-3 mb-3 border border-danger border-3 rounded">{{ form.errors }}</div>
{% endif %}
<div class="mb-3">
<label for="" class="form-label">Name</label>
<input type="text" class="form-control" value="{{ form.name.value }}">
</div>
<div class="mb-3">
<input type="checkbox" class="form-check-input" {% if form.is_source.value %} checked {% endif %}>
<label for="">Source</label>
</div>
<div class="mb-3">
<input type="checkbox" class="form-check-input" {% if form.is_destination.value %} checked {% endif %}>
<label for="">Destination</label>
</div>
<input type="submit" class="btn btn-success mb-3" value="Save">
</form>
</div>
</div>
</section>
{% endblock %}
locations.urls.py
from django.urls import path
from . import views
app_name = 'locations'
urlpatterns = [
path('', views.LocationsListView.as_view(), name='list'),
path('update/<int:pk>/', views.LocationUpdateView.as_view(), name='update'),
path('delete/<int:pk>/', views.LocationDeleteView.as_view(), name='delete'),
]
When I try to update my model, individually rendering the form fields using {{form.name.value}}, I get an error that my name field is required, and yet it is filled. I do not get the error if I render the form as a whole using {{form.as_p}} for example. What am I doing wrong?
I tried using {{form.as_p}} and it worked. But I need individual field rendering so I can style my form.
You need to provide the name attribute for each of your field <input> tags. The field's html_name attribute should be used if rendering manually
<input name="{{ form.name.html_name }}" type="text" class="form-control" value="{{ form.name.value }}">

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 %}

why are styles not getting applied to Django URLField

I have a model for the profile in it there are different fields like CharField and also URLField but on the page, the styles are getting applied to the input of other fields but are not getting applied to the input of URLField
here is my models.py:
and here is my forms.py:
class ProfileForm(ModelForm):
class Meta:
model = Profile
fields = [
"name",
"email",
"username",
"location",
"bio",
"short_intro",
"profile_image",
"social_github",
"social_twitter",
"social_linkedin",
"social_youtube",
"social_website",
]
def __init__(self, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs.update({"class": "input"})
and here is my HTML:
{% extends 'main.html' %}
{% block content %}
<!-- Main Section -->
<main class="formPage my-xl">
<div class="content-box">
<div class="formWrapper">
<a class="backButton" href="{% url 'account' %}"><i class="im im-angle-left"></i></a>
<br>
<form action="{% url 'edit-account' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
<div class="form__field">
<label for="formInput#text">{{ field.label }}</label>
{{ field }}
</div>
{% endfor %}
<input class="btn btn--sub btn--lg my-md" type="submit" value="Submit" />
</form>
</div>
</div>
</main>
{% endblock %}
and here is an example of gif of what's happening:
Please answer how can I apply the same styles on the input of URLField as well

Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P<pk>[^/]+)/$']

I'm getting this error when I use
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
but there is no such error when path is..
path('create_order', views.createOrder, name="create_order"),
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name='products'),
path('customer/<str:pk_test>/', views.customer, name="customer"),
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
path('update_order/<str:pk>/', views.updateOrder, name="update_order"),
path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"),
]
views.py
def createOrder(request, pk):
OrderFormSet = inlineformset_factory(Customer, Order , fields=('product','status'), extra=9)
customer = Customer.objects.get(id=pk)
formset = OrderFormSet(queryset=Order.objects.none(), instance=customer)
#form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
#print('printing post', request.POST)
formset = OrderFormSet(request.POST, instance=customer)
if formset.is_valid():
formset.save()
return redirect('/')
context = {'formset': formset}
#return redirect('accounts/order_form.html', context)
return render(request, 'accounts/order_form.html', context)
i also have tried redirect, that's not working the problem is with urls.py.
customer.html
{% extends 'accounts/main.html' %}
{% block content %}
<br>
<div class="row">
<div class="col-md">
<div class="card card-body">
<h5>Customer:</h5>
<hr>
<a class="btn btn-outline-info btn-sm btn-block" href="">Update Customer</a>
<a class="btn btn-outline-info btn-sm btn-block" href="{% url 'create_order' customer.id %}">Place Order</a>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Contact Information</h5>
<hr>
<p>Email: {{customer.email}}</p>
<p>Phone: {{customer.phone}}</p>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Total Order</h5>
<hr>
<h1 style="text-align: center;padding: 10px;">{{order_count}}</h1>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col">
<div class="card card-body">
<form method="POST">
<button class="btn btn-primary" type="submit">Search</button>
</form>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md">
<div class="card card-body">
<table class="table table-sm">
<tr>
<th>Product</th>
<th>Category</th>
<th>Date Ordered</th>
<th>Status</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for order in orders %}
<tr>
<td>{{order.product}}</td>
<td>{{order.product.category}}</td>
<td>{{order.date_created}}</td>
<td>{{order.status}}</td>
<td><a class="btn btn-outline-info btn-md " href="{% url 'update_order' order.id %}">Update</a></td>
<td><a class="btn btn-outline-danger btn-md " href="{% url 'delete_order' order.id %}">Delete</a></td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
models.py
class Customer(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
phone = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-md-6">
<div class="card card-body">
<form action="" method="POST">
{% csrf_token %}
{{formset.managment_form}} <!-- to remove the managmentForm data missing or has been tempered wiith , error -->
{% for form in formset %}
{{formset}} <!--in context of views.py -->
<hr>
{% endfor %}
<input class="btn btn-outline-success btn-md" type="submit" name="submit">
</form>
</div>
</div>
</div>
{% endblock %}
I have added the templates , and thanks to all but I think the only problem is with urls.py , because if I use
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
instead of
path('create_order', views.createOrder, name="create_order"),
then I get error, otherwise there is no such error for the above path.
I finally got the error.
So, error was here
the href which we have used id {% url 'create_order' customer.id %}
and this is in customer.html ,so the customer.id will get value provided by the views.customer
but if you see in your view.customer,
context = {'customers':customers,'orders': orders,'orders_count': orders_count}
because we followed a tutorial video, that guy did some changes which we didn't because it isn't shown in the video.
the changes he did was that
he changed 'customers' to 'customer' and now context of customer.html is good
because now it knows what the hell is customer.id
i know where the problem is
in the dashboard.html you should delete the line includes {% url 'create_order' %}
I don't know what is the problem but just replaced the file urls.py from GitHub with the same context and it's not showing that error.
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name='products'),
path('customer/<str:pk_test>/', views.customer, name="customer"),
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
path('update_order/<str:pk>/', views.updateOrder, name="update_order"),
path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"),
]
views.py
from django.forms import inlineformset_factory
def createOrder(request, pk):
OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status'), extra=10 )
customer = Customer.objects.get(id=pk)
formset = OrderFormSet(queryset=Order.objects.none(),instance=customer)
#form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
#print('Printing POST:', request.POST)
#form = OrderForm(request.POST)
formset = OrderFormSet(request.POST, instance=customer)
if formset.is_valid():
formset.save()
return redirect('/')
context = {'form':formset}
return render(request, 'accounts/order_form.html', context)
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-md-6">
<div class="card card-body">
<form action="" method="POST">
{% csrf_token %}
{{ form.management_form }}
{% for field in form %}
{{field}}
<hr>
{% endfor %}
<input type="submit" name="Submit">
</form>
</div>
</div>
</div>
{% endblock %}
Again I don't know why it was showing this error and where was the problem but just relapced it with the same code from GitHub and it worked.if someone know how it worked, that will be really helpful in near future.
in dashboard you should remove the line with create order
cause there is use of create_order url without id so there's an error

Using Django registration with a Flat UI template

I have created a template design for signup page using Flat UI. Now i want to use Django registration to register a user. I have goggled various resources but they are very complex and using Django inbuilt form to create a form.
I need simple steps that i can follow
signup.html(home/django/mysite/templates)
{% extends "base.html" %}
{% block title %}Signup page{% endblock %}
{% block content %}
<div class="container" style="width:500px">
<h3 style="margin-top:100px">Sign Up</h3>
<hr>
<div class="login-form">
<form action="" method="post">
<div class="control-group span3" style="width:400px" >
<input type="text" value="" placeholder="Enter your name" id="name" style="width:400px;padding-bottom:15px;margin-bottom:10px" >
<i class="input-icon fui-user" for="login-name"></i>
</div>
<div class="control-group span3" style="width:400px" >
<input type="text" value="" placeholder="Your E-mail" id="email" style="width:400px;padding-bottom:15px;margin-bottom:10px" >
<i class="input-icon fui-mail" for="login-name"></i>
</div>
<div class="control-group span3" style="width:400px">
<input type="password" value="" placeholder="Password" id="pass" style="width:400px;padding-bottom:15px;margin-bottom:10px">
<i class="input-icon fui-lock" for="login-pass"></i>
</div>
<div class="control-group span3" style="width:400px">
<input type="password" value="" placeholder="Confirm Password" id="login-pass" style="width:400px;padding-bottom:15px;margin-bottom:10px">
<i class="input-icon fui-lock" for="login-pass"></i>
</div>
<div style="text-align:center">
<a class="btn btn-hg btn-primary btn-wide" href="#">Sign Up</a>
<!--<a class="login-link" href="#">Lost your password ?</a> -->
</div>
</form>
</div><!-- /login-form -->
</div> <!-- /container -->
{% endblock content %}
views.py
def signup(request):
return render(request, 'signup.html')
urls.py
urlpatterns = patterns('',
url(r'^signup/$', views.signup),)
What i should write in views.py or models.py to register a user using django registration.
You can use django registration together with custom html/css through django forms. Here are the steps:
Provided you have included relevant imports, your urls.py looks fine so no changes needed.
Create a forms.py file in the same folder as your views.py and add the following code into forms.py:
from django import forms
class Signup_form(forms.Form):
# CSS styles should not be inline. i've moved your style contents under a 'form-control' class
name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'type':'text', 'placeholder':'Enter your name', 'id':'name', 'name':'name', 'class' : 'form-control'}))
email = forms.EmailField(label="Email address", widget=forms.TextInput(attrs={'type':'text', 'placeholder':'Your E-mail', 'id':'email', 'name':'email', 'class' : 'form-control'}))
pass1 = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'type':'password', 'placeholder':'Password', 'id':'pass1', 'name':'pass1', 'class' : 'form-control'}))
pass2 = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'type':'password', 'placeholder':'Confirm Password', 'id':'pass2', 'name':'pass2', 'class' : 'form-control'}))
3.In your views.py file, you have to link pass the Signup_form to your views layer. Change your views.py file to the following:
from forms import Signup_form
def signup(request):
form = Signup_form()
name = request.POST.get('name','')
email = request.POST.get('email', '')
pass1 = request.POST.get('pass1', '')
pass2 = request.POST.get('pass2', '')
# Do some validations here
user = User.objects.create_user(name, email, pass2)
if user:
user.save()
return render(request, 'signup.html', {'form': form})
4.Now that you have passed your Signup_form object in views layer, you can use django template tags to display them in your signup.html page. Here's how your signup.html could look like:
{% extends "base.html" %}
<link rel="stylesheet" href="{% static 'css/custom.css' %}">
{% block title %}Signup page{% endblock %}
{% block content %}
<div class="container" style="width:500px">
<h3 style="margin-top:100px">Sign Up</h3>
<hr>
<div class="login-form">
<form action="" method="post"> {% csrf_token %}
<div class="control-group span3" style="width:400px" >
{{ form.name.errors }}
{{ form.name }}
<i class="input-icon fui-user" for="login-name"></i>
</div>
<div class="control-group span3" style="width:400px" >
{{ form.email.errors }}
{{ form.email }}
<i class="input-icon fui-mail" for="login-name"></i>
</div>
<div class="control-group span3" style="width:400px">
{{ form.pass1.errors }}
{{ forms.pass2 }}
<i class="input-icon fui-lock" for="login-pass"></i>
</div>
<div class="control-group span3" style="width:400px">
{{ form.pass2.errors }}
{{ forms.pass2 }}
<i class="input-icon fui-lock" for="login-pass"></i>
</div>
<div style="text-align:center">
<input type="submit" class="btn btn-hg btn-primary btn-wide" value="Sign Up">
<!--<a class="login-link" href="#">Lost your password ?</a> -->
</div>
</form>
</div><!-- /login-form -->
</div> <!-- /container -->
{% endblock content %}
5.Since i have earlier moved your CSS styles(in point 2) into a 'form-control' class, now we will place it back by adding your styles in a external custom.css file. Create a custom.css file in the directory static/css/custom.css and add the following into it:
.form-control {
width:400px;
padding-bottom:15px;
margin-bottom:10px;
}
In your Views.py
from django.contrib.auth.models import User
def signup(request):
username = request.POST.get("name","")
password = request.POST.get("pass","")
login_pass = request.POST.get("login-pass","")
email = request.POST.get("email","")
if username != "" or password != "" or login_pass != "":
#do some validations
user = User.objects.create_user(username, email, password)
if user:
user.is_active = True
user.save()
return render(request, 'signup.html')
Above code will register a new user into system
If you would have use Django forms then all the validations will be done by Django.
Note: Please add name attribute to your HTML fields required for getting vaLues in request.POST. Also point your HTMl form action to "signup" view