I want the form to show
Username
Email
Password
Password(2)
At the moment, it is showing
Username
Password
Password (2)
Email
I am trying to follow this tutorial https://www.youtube.com/watch?v=q4jPR-M0TAQ.
I have looked at the creators notes on Github but that has not helped.
I have double checked my code and cannot see any daft typos.
Can anyone provide any insight?
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}!')
return redirect ('blog-home')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form':form})
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Join Today</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="#">Sign In</a>
</small>
</div>
</div>
{% endblock content %}
you can customize the look and order of the form by this method, create a new template in the account/ template directory, name it register.html, and make it look as follows:
{% extends "base.html" %}
{% block title %}Create an account{% endblock %}
{% block content %}
<h1>Create an account</h1>
<p>Please, sign up using the following form:</p>
<form action="." method="post">{% csrf_token %}
{{ form.username }}
{{ form.other_fields_as_you_like }}
<p><input type="submit" value="Create my account"></p>
</form>
{% endblock %}
Related
I am trying to display 2 forms in my contact.html page in a Django project. Each form needs to display a success message when being successfully submitted by users. The problem is that both forms in the page show the same success message when either of them being submitted.
How can I tie the success message to the submitted form on my HTML page?
forms.py
from dataclasses import field, fields
from logging import PlaceHolder
from socket import fromshare
from django import forms
from .models import ServiceRequest, Contact, Newsletter
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = ['name','email','phone','message']
class NewsletterForm(forms.ModelForm):
class Meta:
model = Newsletter
fields = ['name','email']
views.py
from http.client import HTTPResponse
from multiprocessing import context
from django.shortcuts import render
from django.views.generic import TemplateView
from .forms import ContactForm, NewsletterForm, ServiceRequest, ServiceRequestForm
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.urls import reverse
def Contact(request):
contact_form = ContactForm(request.POST or None)
newsletter_form = NewsletterForm(request.POST or None)
if request.method == 'POST' and contact_form.is_valid():
contact_form.save()
messages.success(request, "Thanks for contacting us!")
return HttpResponseRedirect(request.path_info)
elif request.method == 'POST' and newsletter_form.is_valid():
newsletter_form.save()
messages.success(request, "Thanks for joining our newsletter!")
return HttpResponseRedirect(request.path_info)
context = {
"contact_form":contact_form,
"newsletter_form":newsletter_form,
}
return render(request, "main/contact.html", context)
contact.html
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% load static %}
{% block content %}
<div>
<!-- Message from backend -->
{% for message in messages %}
{% if message.tags == 'success' %}
<div>{{message}}
</div>
{% endif %}
{% endfor %}
<form method="POST">
{% csrf_token %}
<div class="row">
{{ contact_form.name|as_crispy_field }}
{{ contact_form.email|as_crispy_field }}
{{ contact_form.phone|as_crispy_field }}
{{ contact_form.message|as_crispy_field }}
</div>
</div>
<button type="submit">Submit</button>
</form>
</div>
<div>
<!-- Message from backend -->
{% for message in messages %}
{% if message.tags == 'success' %}
<div>{{message}}
</div>
{% endif %}
{% endfor %}
<form method="POST">
{% csrf_token %}
<div class="row">
{{ newsletter_form.name|as_crispy_field }}
{{ newsletter_form.email|as_crispy_field }}
</div>
<button type="submit">Submit</button>
</form>
</div>
{% endblock %}
After submitting one form on this page, both forms show the success message:
You can use extra_tags of messages framework Django docs:
So in view:
messages.success(request, "Thanks for contacting us!", extra_tags='form1')
And in template:
{% for message in messages %}
{% if message.tags == 'success' and message.extra_tags == 'form1' %}
<div>{{message}}
</div>
{% endif %}
{% endfor %}
My forms.py:
class SignUpForm(forms.ModelForm):
name = forms.CharField(label="name", required=True, widget=forms.TextInput())
email = forms.CharField(label="email", required=True, widget=forms.TextInput())
password = forms.CharField(label="password", widget=forms.PasswordInput(), required=True)
confirm_password = forms.CharField(label="password", widget=forms.PasswordInput(), required=True)
def clean(self):
cleaned_data = super(SignUpForm, self).clean()
password = cleaned_data.get("password")
confirm_password = cleaned_data.get("confirm_password")
if password != confirm_password:
self.add_error('confirm_password', "Password and confirm password do not match")
return cleaned_data
class Meta:
model = get_user_model()
fields = ('name', 'email', 'password')
My html file:
{% block content %}
<form method="post">
<div class="sign-card">
<h3>Signup</h3>
{% csrf_token %}
<div class="input-div">
<label for="{{ form.name.id_for_label }}">Username:</label>
{{ form.name }}
</div>
<div class="input-div">
<label for="{{ form.email.id_for_label }}">Email:</label>
{{ form.email }}
</div>
<div class="input-div">
<label for="{{ form.password.id_for_label }}">Password:</label>
{{ form.password }}
</div>
<div class="input-div">
<label for="{{ form.password.id_for_label }}">Confirm Password:</label>
{{ form.confirm_password }}
</div>
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% endif %}
<button type="submit" class="btn">Sign up</button>
<p>Already have account? Log In</p>
</div>
</form>
{% endblock %}
My views.py:
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('name')
password = form.cleaned_data.get('password')
email = form.cleaned_data.get('email')
user = authenticate(username=username, password=password, email=email)
login(request, user)
return redirect('index')
else:
form = SignUpForm()
return render(request, 'registration/signup.html', {'form': form})
The problem I'm facing is that <div class="alert alert-danger"> doesn't work properly. It prints the text and makes it bold, but I have no CSS styling for it (like here, for example: https://www.csestack.org/display-messages-form-submit-django/). I don't want to use Django messages, neither change my code in views.py. How can I fix it? If there is no way to fix it without this changes, so, how can I fix the problem fixing my views.py?
Thanks a lot for your answers.
Actually, you are missing the css file to interpret the alert-danger class.
You can either manually write css for it or include some css library like bootstrap.
You can do something like below in your code: In <head> tag
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
</head>
It should work fine then.
As in the question title "{{form}}" from is not being loaded into html template I checked by previous projects I have almost the same code, differences are required fields, naming etc. mechanic is the same.
In those projects registration function works perfectly here it's not even throwing an error just don't display anything.
No wonder what might be wrong in here.
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class RegistrationForm(UserCreationForm):
email = forms.EmailField(max_length=60, help_text="Required field")
class Meta:
model = Profile
fields = ["email", "username", "password", "password2", "calories_plan", "diet_type"]
views.py
def registration_view(request):
context = {}
if request.POST:
form = RegistrationForm(request.POST)
if form.is_valid():
email = form.cleaned_data.get("email")
password = form.cleaned_data.get("password")
new_account = authenticate(email=email, password=password)
login(request, new_account)
else:
context["registration_form"] = form
else:
form = RegistrationForm()
context["registration_form"] = form
return render(request, "Account/registration.html", context)
html template
{% extends 'main.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="post">
{% csrf_token %}
<fieldset class="form-group">
<legend class=border-bottom mb-4>Join today
{{ form }}
</legend>
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already have an account?
<a href="#" class="ml-2">
Log In
</a>
</small>
</div>
</div>
{% endblock %}
And how it looks in browser.
You're passing 'registration_form' to the context, but in template you are calling {{ form }}.
Replace:
{{ form }}
with:
{{ registration_form }}
l am started to learn Django few days ago, and I get this error:
django.urls.exceptions.NoReverseMatch: Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P[^/]+)/$']*
urls.py
path('create_order/<str:pk>/', views.createOrder, name='create_order'),
views.py
def createOrder(request, pk):
customer = Customer.objects.get(id=pk)
form = OrderForm(initial={'customer': customer})
if request.method == 'POST':
# print('Printing:', request.POST)
form = OrderForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
context = {
'form': form
}
return render(request, 'accounts/order_form.html', context)
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<br>
<div class="row">
<div class="col-12 col-md-6">
<div class="card card-body">
<form action="" method="post">
{% csrf_token %}
{{form}}
<input class="btn btn-sm btn-danger" type="submit" value="Conform">
</form>
</div>
</div>
</div>
{% endblock %}
customer.html
<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>
As the error said, it tried with empty argument, means there was no customer value available in context. So you need to send the customer value through context, like this:
context = {
'customer' : customer,
'form': form
}
I was also following this tutorial from youtube(dennis ivy) and got the same error,
don't know what is the problem but just replace 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. thanks to all regards Haris Ahmad
What I'm trying to do is execute a function when the user clicks the "add to cart" button, the product displayed on the screen will be added to the cart model. So far i've figured out how to add objects to the cart from the shell. What i don't know is how to call a python function with html and how to pass the object to it. Thank you in advance.
my template.html:
{% extends 'templates/header.html' %}
<title>{% block head_title %}{{ object.name }} - {{ block.super }}{% endblock head_title %}</title>
{% block head %}
{{ block.super }}
{% load staticfiles %}
<link rel = "stylesheet" href = "{% static 'css/products_detail.style.css' %}" type = "text/css"/>
{% endblock head %}
{% block content %}
<div id='Product-Page'>
<p>{{ object.name }}</p>
<hr>
<div id='Product-Image'>
<img src='{{ object.image.url }}' alt='{{ object.image.name }}'/>
</div>
<div id='Product-Details'>
<p id='Product-Name'>{{ object.name }}</p>
<p id='Product-Description'><small>{{ object.description }}</small></p>
</div>
<div id='Product-Buy'>
<p id='Product-Price'>{{ object.price }} лв.</p>
<p id='Product-Quantity'>{{ object.quantity }} </p>
<form class='Product-Form' method='post' action='#'>
{% csrf_token %}
<input class='Product-Button' type='submit' value='Buy Now'>
</form>
<form class='Product-Form' method='get' action=''>
{% csrf_token %}
<input class='Product-Button' type='submit' value='Add to cart'>
</form>
</div>
<hr>
</div>
{% endblock content%}
my view:
class ProductDetailView(DetailView):
template_name = 'products/products_detail.html'
def get_object(self, *args, **kwargs):
slug = self.kwargs.get('slug')
return get_object_or_404(Product, slug=slug)
You can add hidden inputs to each form (both of which should be POST methods, not GET) then add a post method to your view. Something like:
<form class='Product-Form' method='post'>
{% csrf_token %}
<input name="buy-now" hidden>
<input name="pk" value="{{ object.pk }}" hidden>
<button type="submit" class="btn">Buy Now</button>
</form>
<form class='Product-Form' method='post'>
{% csrf_token %}
<input name="add-to-cart" hidden>
<input name="pk" value="{{ object.pk }}" hidden>
<button type="submit" class="btn">Add to cart</button>
</form>
Then in your view:
class ProductDetailView(DetailView):
template_name = 'products/products_detail.html'
def get_object(self, *args, **kwargs):
slug = self.kwargs.get('slug')
return get_object_or_404(Product, slug=slug)
def post(self, request, *args, **kwargs):
name = request.POST.get("pk")
product = Product.objects.get(pk=pk)
if "buy-now" in request.POST:
#Do something to buy.
print('buy now ' + product.name)
elif "add-to-cart" in request.POST:
#Add to cart.
print('add to cart ' + product.name)
return redirect('home')
Or you can do it via AJAX if you don't want to reload the page.