Django from is not being past into html template - html

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

Related

Django: div class alert alert-danger does not work properly

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.

Django, user can update email and username but not Image

As in title I have a problem with updating form because everything works as I want but not an image updating feature.It sends success message but it does not change the image for the profile.
views.py
def profileView(request):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user,)
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, 'Your account has been updated!')
return redirect('profile-page')
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form}
return render(request, 'shop/profile.html', context)
HTML:
<div>
{{ user.username }}
<img src="{{ user.profile.user_image.url }}">
Delete
<form method="POST"> {% csrf_token %}
{{ p_form.as_p}}
{{ u_form.username }}
{{ u_form.email }}
<button type="submit">Update</button>
</form>
</div>
signals.py
#receiver(post_save, sender=User)
def profile_creation(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
{{ u_form.email }}
<button type="submit">Update</button>
</form>
</div>
If you send files in a form, you specify the enctype="multipart/form-data" attribute to encode images in the POST request:
<form enctype="multipart/form-data" method="POST">
{% csrf_token %}
{{ p_form.as_p}}
{{ u_form.username }}
{{ u_form.email }}
<button type="submit">Update</button>
</form>

i get an error. django.urls.exceptions.NoReverseMatch

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

Why won't my UserCreationForm render in chronological order?

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

Django redirect to previous page not working

Hi I want to redirect to the previous after submitting the form in django. It is successfully redirecting to the previous page but the post action is not happening. I am able to successfully post the data if I remove the action attribute.
This is my form template.
{% extends 'musicapp/base.html' %} {% block content %}
<!-- <h1>New post</h1> -->
<form method="POST" action={{ request.META.HTTP_REFERER }} class="post-form">{% csrf_token %}
<div class="add_track_form" >
<div class="col-sm-6">
<section class="panel panel-default">
<header class="panel-heading font-bold">Add Genre</header>
<div class="panel-body">
<form action="{% url 'post_list' %}" role="form">
<div class="form-group">
<label>Title</label>
{{ form.name }}
</div>
<input type="hidden" name="next" value="{{ request.path }}">
<button type="submit" class="btn btn-sm btn-default">Submit</button>
</form>
</div>
</section>
</div>
</div>
</form>
{% endblock %}
This is the views.py file
from django.shortcuts import render, get_object_or_404, redirect, render_to_response
from django.http import HttpResponseRedirect
from .forms import AddTrackForm, AddGenreForm
from django.http import HttpResponse
from .models import Track, Genre
from . import getAlbumArt
# Create your views here.
def home(request):
tracks = Track.objects.all().order_by('created_date')
return render(request, 'musicapp/post_list.html', {'tracks': tracks})
def post_detail(request, pk):
track = get_object_or_404(Track, pk=pk)
# print post
return render(request, 'musicapp/post_detail.html', {'track': track})
# def post_new(request):
# form = AddTrackForm()
# return render(request, 'musicapp/post_edit.html', {'form': form})
def post_new(request):
if request.method == "POST":
form = AddTrackForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
artist = request.POST.get("artist", "")
album = request.POST.get("album", "")
# print artist, album
urlArt = getAlbumArt.getAlbumArtURL(album, artist)
print urlArt
if urlArt:
post.cover_image_url = urlArt
if post.album == '*':
post.album = 'Unknown'
post.save()
tracks = Track.objects.all().order_by('created_date')
return render(request, 'musicapp/post_list.html', {'tracks': tracks})
else:
form = AddTrackForm()
return render(request, 'musicapp/post_edit.html', {'form': form})
def post_edit(request, pk):
post = get_object_or_404(Track, pk=pk)
if request.method == "POST":
form = AddTrackForm(request.POST, instance=post)
if form.is_valid():
post = form.save(commit=False)
artist = request.POST.get("artist", "")
album = request.POST.get("album", "")
# print artist, album
urlArt = getAlbumArt.getAlbumArtURL(album, artist)
print urlArt
if urlArt:
post.cover_image_url = urlArt
if post.album == '*':
post.album = 'Unknown'
post.save()
tracks = Track.objects.all().order_by('created_date')
return redirect('post_detail', pk=post.pk)
else:
form = AddTrackForm(instance=post)
return render(request, 'musicapp/post_edit.html', {'form': form})
def genre(request):
tracks = Track.objects.all().order_by('created_date')
genres = Genre.objects.all()
return render(request, 'musicapp/genre.html', {'genres': genres, 'tracks': tracks})
def genre_songs(request, pk):
genres = Genre.objects.all()
genre_obj = get_object_or_404(Genre, pk=pk)
tracks = genre_obj.track_set.all()
# print post
return render(request, 'musicapp/genre_songs.html', {'genres': genres, 'genre' : genre_obj, 'tracks': tracks})
def genre_new(request):
if request.method == "POST":
form = AddGenreForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.save()
genres = Genre.objects.all()
print request.META.HTTP_REFERER
next = request.POST.get('next', '/')
# return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
# print next
# return HttpResponseRedirect(next)
# return HttpResponseRedirect('/')
return render_to_response('musicapp/post_edit.html', {'form': AddTrackForm()})
else:
form = AddGenreForm()
return render(request, 'musicapp/genre_edit.html', {'form': form})
And these are the URL routings.
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='post_list'),
url(r'^track/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
url(r'^track/new/$', views.post_new, name='post_new'),
url(r'^track/(?P<pk>\d+)/edit/$', views.post_edit, name='post_edit'),
url(r'^genre/$', views.genre, name='genre_list'),
url(r'^genre/(?P<pk>\d+)/$', views.genre_songs, name='genre_songs'),
url(r'^genre/new/$', views.genre_new, name='genre_new'),
]
Take a look at this:
<input type="hidden" name="next" value="{{ request.path }}" />
request.path provides the path for the current page, not the previous. As such, you are currently submitting a next value of the same page the form is submitted from.
{{ request.META.HTTP_REFERER }} provides the referring page. So why would you post the form to the previous page? It should be noted, though, that this may have a value of None (or the referring page may be from another domain).
I assume you have your form's action parameter and your 'next' hidden input's values switched. Otherwise, you probably have unnecessarily complex logic.
you have two forms and they are nested. Inner form uses GET (if nothing specified, then GET will be used per default) and outer one uses POST. this is purely chaos and you should not do so. if you fix this, I am sure the bug will also be fixed.
{{ request.META.HTTP_REFERER }} is not necessarily the previous page you think about. You should not use it this way. I would work with GET (e.g. with '?prev=/url/before/form/') to remember which page the user is coming from.
Replace in your urls.py
url(r'^$', views.home, name='post_list'),
with
url(r'^postlist/$',views.home, name='post_list'),
and in your form
<form action="{% url 'post_list' %}" role="form">
to be
<form action="/postlist" role="form" method="POST">
So I solved my problem by comparing the URL from which we are clicking the link and then setting a hidden field depending upon the previous
URL (request.META.HTTP_REFERER) and redirecting according to flag value I'm getting from the template.
This is my template
{% extends 'musicapp/base.html' %} {% block content %}
<!-- <h1>New post</h1> -->
<form method="POST" class="post-form">{% csrf_token %}
<div class="add_track_form" >
<div class="col-sm-6">
<section class="panel panel-default">
<header class="panel-heading font-bold">Add Genre</header>
<div class="panel-body">
<div class="form-group">
<label>Title</label>
{{ form.name }}
</div>
{% if 'track/new/' in request.META.HTTP_REFERER %}
<input class="form-control" type="hidden" value = 0 id="flag" maxlength="50" name="flag" type="text">
{% else %}
<input class="form-control" type="hidden" value = 1 id="flag" maxlength="50" name="flag" type="text">
{% endif %}
<button type="submit" class="btn btn-sm btn-default">Submit</button>
</div>
</section>
</div>
</div>
</form>
{% endblock %}
This is the views function:
def genre_new(request):
if request.method == "POST":
form = AddGenreForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
redirect_flag = request.POST.get("flag", "") # redirect to different places depending upon where it was clicked
post.save()
genres = Genre.objects.all()
print redirect_flag
if redirect_flag == '0':
return HttpResponseRedirect(reverse('post_new'))
elif redirect_flag == '1':
return HttpResponseRedirect(reverse('genre_list'))
else:
return HttpResponseRedirect('/')
else:
form = AddGenreForm()
return render(request, 'musicapp/genre_edit.html', {'form': form})
Is there an easier way to do this?
I think that I have an easier way.
Template:
<div hidden>
<input name="url_get" value={{ url_ref }}>
</div>
View:
url_get = request.POST.get('url_get')
if url_get:
url_ref = url_get
else:
url_ref = request.META.get('HTTP_REFERER')
args['url_ref'] = url_ref
So, we always have the first url
This might look like a long time coming but applying the reasoning from Ian Prince. Please pay attention to some changes that have been made.
{% extends 'musicapp/base.html' %} {% block content %}
<!-- <h1>New post</h1> -->
<form method="POST" class="post-form">{% csrf_token %}
<div class="add_track_form" >
<div class="col-sm-6">
<section class="panel panel-default">
<header class="panel-heading font-bold">Add Genre</header>
<div class="panel-body">
<form action="{% url 'post_list' %}" role="form">
<div class="form-group">
<label>Title</label>
{{ form.name }}
</div>
<input type="hidden" name="next" value="{{ request.META.HTTP_REFERER }}">
<button type="submit" class="btn btn-sm btn-default">Submit</button>
</form>
</div>
</section>
</div>
</div>
</form>
{% endblock %}
These changes include:
action='{{ request.META.HTTP_REFERER }}'
<!-- although this was posted as: action={{ request.META.HTTP_REFERER }} -->
and the change of:
value="{{ request.path }}"
to:
value="{{ request.META.HTTP_REFERER }}"
That solved my problem. I hope it solves yours