Input fields are makred always RED in Djano UserRegistrationForm - html

I am creating a User authentication system in Django. The first page I set is to Register a new user. For that, my views.py is below:
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from .forms import UserRegisterForm
from django.contrib import messages # To give an alert when a valid data is received
# Create your views here.
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'Your account has been created!')
return redirect('login')
else:
form = UserRegisterForm(request.POST)
return render(request, 'Agent/register.html', {'form': form})
and the html file is given below:
register.html
{% extends "client_management_system/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="{% url 'login' %}">Sign In</a>
</small>
</div>
</div>
{% endblock content %}
and the URL pattern for register page is given below:
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from Agent import views as agent_views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('client_management_system.urls')),
path('register/', agent_views.register, name='register'),
]
But my Register fields are always RED as shown below:
Does anyone has an idea how to make them normal? and make the field RED when it is left empty and Sign Up button is pressed.

In the else: clause you should initialize a new form, not with request.POST data (which you don't have)
else:
form = UserRegisterForm()
(moreover the else is unnecessary there)

Related

Reverse for 'likes' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['datasecurity/likes/<int:pk>'] Like buttton error in django

registration and login page is working properly but mine like button is not working .. I don't know why...
Can somebody help me to solve this issue …
it will be great help
please help
Thank you!
views.py`
from django.shortcuts import render, get_object_or_404
from datasecurity.models import Post
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login required
# Create your views here.
def datasecurity(request):
allPosts= Post.objects.all()
context={'allPosts': allPosts}
return render(request, 'datasecurity/data.html',context=context)
def blogHome(request, slug):
post=Post.objects.filter(slug=slug).first()
context={"post":post}
return render(request, "datasecurity/blogHome.html", context)
#login_required
def likes(request, pk):
post=get_object_or_404(Post, id=request.POST.get('post_id'))
post.likes.add(request.user)
return HttpResponseRedirect(reverse('datasecurity:blogHome', args=str(pk)))
urls.py
from django.conf.urls import url
from . import views
app_name = 'datasecurity'
urlpatterns = [
url(r'^$', views.datasecurity, name="datasecurity"),
url(r'^datasecurity/(?P<slug>[^/]+)', views.blogHome, name='blogHome'),
url(r'^likes/<int:pk>', views.likes, name = "likes"),
]
data.html
{% extends 'careforallapp/navbar.html' %}
{% block body_block %}
{% load static %}
Welcome to Data Security
{% for post in allPosts %}
<div class="line-dec"></div>
<span
>This is a Bootstrap v4.2.1 CSS Template for you. Edit and use
this layout for your site. Updated on 21 May 2019 for repeated main menu HTML code.</span
>
</div>
<div class="left-image-post">
<div class="row">
<div class="col-md-6">
<div class="left-image">
{% if post.img %}
<img src="{{ post.img.url }}" alt="" />
{% endif %}
</div>
</div>
<div class="col-md-6">
<div class="right-text">
<h4>{{post.title}}</h4>
<h6>Article by {{post.author}}</h6>
<h2>{{post.datetime}}</h2>
<p>
{{post.content|safe | truncatechars:280}}
</p>
<from action = "{% url 'datasecurity:likes' pk=post.pk %}" method = "POST">
{% csrf_token %}
<button type="submit" name="post_id" value = "{{ post_id }}" class="btn"> Like
</button>
</form>
<div class="white-button">
Read More
</div><br>
</div>
{% endfor %}
error msg <from action = "{% url 'datasecurity:likes' pk=post.pk %}" method = "POST">
Reverse for 'likes' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['datasecurity/likes/int:pk']
this msg was highlighted when I debug the the code. So can someone tell me please what i missed in my code...
Thank You!
You are not taking the pk argument from view. Change your view to:
#login_required
def likes(request, pk):
post=get_object_or_404(Post, id=pk)
and the url to:
url(r'^likes/(?P<pk>\d+)/', views.likes, name = "likes"),
notice the used regular expression in the url.

Django from is not being past into html template

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

Django form not rendering in HTML

I have a form that isn't rendering and I can't figure out why. The only thing showing is submit button. I created the form having followed the methodology described here, here and here.
I looked at solutions for the problem (listed below amongst others) but they havent helped.
django-forms not rendering errors
django form not rendering in template. Input fields doesn't shows up
Django Form not rendering
Django Form not rendering - following documentation
The html is app_core/index.html which extends another- landing_page/base.html
The html:
{% extends 'landing_page/base.html' %}
{% load i18n %}
{% load staticfiles %}
{% load static %}
{% load bootstrap %}
{%block content %}
<div id="contactus" class="container-fluid">
<br>
<div class="container text-center">
<div class="row">
<div class="col-xs-12 col-sm-10 col-sm-offset-1 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2 text-left">
<center><h3>{% trans 'Contact Us' %}</h3>
<p>{% trans 'We are at your disposal 365 days 24 hours a day. When you think of languages think of Milingual.
Languages are not studied, they are lived!' %}</p></center>
</div>
</div>
<div class ="row">
<div class="col-xs-12 col-sm-10 col-sm-offset-1 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2 text-left">
<center><h1>Contact Us</h1><center>
<form id="contactus-form" action="{% url 'contact' %}"method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<br/>
<div class="form-actions">
<button type="submit" class="btn btn-primary pull-center">Send</button>
</div>
</form>
<div>
</div>
</div>
{%endblock content %}
The Views.py
from django.core.mail import BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import ContactForm
#ContactUs
def contact(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
whoareyou = form.cleaned_data['whoareyou']
name = form.cleaned_data['name']
phone_number = form.cleaned_data['phone_number']
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_email(subject, message, whoareyou, from_email, ['thiswaysouth#gmail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, "/index.html", {'form': form})
def success(request):
return HttpResponse('Success! Thank you for your message.')
The form.py
from django import forms
class ContactForm(forms.Form):
WHOAREYOU_CHOICES = (
('Teacher', 'Teacher'),
('Student', 'Student'),
('Venue', 'Venue'),
('Business', 'Business'),
('Other', 'Other')
)
whoareyou = forms.ChoiceField(choices=WHOAREYOU_CHOICES, required=True)
name = forms.CharField(required=True)
phone_number = forms.CharField(required=True)
from_email = forms.EmailField(required=True)
subject = forms.CharField(required=True)
message = forms.CharField(widget=forms.Textarea, required=True)
And the urls.py
from django.conf.urls import url, include
from .views import *
from app_core import views
urlpatterns = [
url(r'^$', IndexPage, name='index'),
# setting session city
url(r'^get-city-session$', GetCitySession, name='get-city-session'),
url(r'^set-city-session$', SetCitySession, name='set-city-session'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^success/$', views.success, name='success'),
]
You need to put your code inside blocks otherwise it doesn't know where to put it when you extend. In your base.html, you can do something like
{% block body %}
{% endblock %}
And then in your index.html page, you need to surround everything that you want to appear in that spot in your base.
{% block body %}
... Code goes here ...
{% endblock %}
This ended having a very simple solution that I failed to notice simply because of my naivete and newness to programming. The above code was and is perfectly correctly but I neglected to add crucial line of code in the ContactForm code in form.py. At the end of the form I was simply to add the following lines and it rendered perfectly:
class ContactForm(forms.Form):
WHOAREYOU_CHOICES ...
class Meta:
fields =('whoareyou','name','phone_number','from_email','subject','message')

Form not Rendered in Django

I am trying to display a form in Django HTML Template, but it is not being Rendered
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Description, Bill
from django.http import Http404
from .forms import DForm
from .forms import BForm
import pprint
# Create your views here.
def index(request):
context = {}
return render(request, 'front/index.html', context)
def commitbill(request):
if request.method == "POST":
form = BForm(request.POST,request.FILES)
if form.is_valid():
print form.errors
Bill = form.save()
return HttpResponse(str(Bill.bill_id()))
print form.errors
return HttpResponse("fail")
forms.py
from django import forms
from .models import Description, Bill
class BForm(forms.ModelForm):
class Meta:
db_table = 'inventory_bill'
model = Bill
fields = ('party', 'inovice', 'amount','image','image_caption')
the template, portion of which is not being Rendered!
{% load staticfiles %}
<html>
<head>
<title></title>
<link href="{%static "./styles/bootstrap.min.css" %}" rel="stylesheet" />
</head>
<body>
<h1 style="text-align: center;">Rahul's Shop</h1>
<h2 style="text-align: center;">Inventory</h2>
<form id="bill" action ="{% url 'front:commitbill' %}" method = "post" class="form-horizontal" enctype="multipart/form-data">
{% csrf token %}
{{ form.as_p }}
<div class="container">
<div class="row">
<input type="button" id="add_items" class="col-md-offset-5 col-md-2 btn btn-success" value="Add items" \>
</div>
</div>
</form>
The portion {{ form.as_p }} is not being Rendered, That's my main Issue!
your index should read like this, you need to pass the form to the template context.
def index(request):
form = BForm()
context = {
'form': form,
}
return render(request, 'front/index.html', context)

Contact Form Django Not Working

I am trying to create a contact form for my Django site but it's not working properly. There are three steps to the contact form. Step 1 has a box where you input the subject of the email. Step 2 has a box where you input the sender's email address. At this point, there are three buttons- "first step", "prev step", and "submit". If I click "submit", the site doesn't take me to step 3, which is supposed to be where you input the body of the email. Instead, it reroutes me back to the Step 1 page.
I did my research and I can't find anything online related to this particular problem.
Here is my views.py file, which is located in the django_test/django_test directory:
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
from forms import MyRegistrationForm
from django.contrib.formtools.wizard.views import SessionWizardView
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
#import logging
#logr = logging.getLogger(__name__)
def login(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return HttpResponseRedirect('/accounts/loggedin')
else:
return HttpResponseRedirect('/accounts/invalid')
def loggedin(request):
return render_to_response('loggedin.html',
{'full_name': request.user.username})
def invalid_login(request):
return render_to_response('invalid_login.html')
def logout(request):
auth.logout(request)
return render_to_response('logout.html')
def register_user(request):
if request.method == 'POST':
form = MyRegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
args = {}
args.update(csrf(request))
args['form'] = MyRegistrationForm()
return render_to_response('register.html', args)
def register_success(request):
return render_to_response('register_success.html')
class ContactWizard(SessionWizardView):
template_name = "contact_form.html"
def done(self, form_list, **kwargs):
form_data = process_form_data(form_list)
return render_to_response('done.html', {'form_data': form_data})
def process_form_data(form_list):
form_data = [form.cleaned_data for form in form_list]
logr.debug(form_data[0]['subject'])
logr.debug(form_data[1]['sender'])
logr.debug(form_data[2]['message'])
send_mail(form_data[0]['subject'],
form_data[2]['message'], form_data[1]['sender'],
[(my email address], fail_silently=False)
return form_data
This my forms.py file, also located in the django_test/django_test directory:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class MyRegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
class ContactForm1(forms.Form):
subject = forms.CharField(max_length=100)
class ContactForm2(forms.Form):
sender = forms.EmailField()
class ContactForm3(forms.Form):
message = forms.CharField(widget=forms.Textarea)
And my contact_form.html file, located in the django_test/templates directory:
{% extends "base.html" %}
{% block content %}
<h2>Contact Us</h2>
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
{% for field in form %}
{{field.error}}
{% endfor %}
<form action="/contact/" method="post">{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{ wizard.form }}
{% endif %}
</table>
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">"first step"</button>
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">"prev step"</buttom>
{% endif %}
<input type="submit" value="submit" />
</form>
{% endblock %}
And this is my urls.py file:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from django_test.api import ArticleResource
from django_test.forms import ContactForm1, ContactForm2, ContactForm3
from django_test.views import ContactWizard
article_resource = ArticleResource()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/login/$', 'django_test.views.login'),
url(r'^accounts/auth/$', 'django_test.views.auth_view'),
url(r'^accounts/loggedin/$', 'django_test.views.loggedin'),
url(r'^accounts/invalid/$', 'django_test.views.invalid_login'),
url(r'^accounts/logout/$', 'django_test.views.logout'),
url(r'^accounts/register/$', 'django_test.views.register_user'),
url(r'^accounts/register_success/$', 'django_test.views.register_success'),
url(r'^articles/all/$', 'article.views.articles'),
url(r'^articles/create/$', 'article.views.create'),
url(r'^articles/get/(?P<article_id>\d+)/$', 'article.views.article'),
url(r'^articles/like/(?P<article_id>\d+)/$', 'article.views.like_article'),
url(r'^articles/add_comment/(?P<article_id>\d+)/$', 'article.views.add_comment'),
url(r'^articles/search/', 'article.views.search_titles'),
url(r'^articles/api/', include(article_resource.urls)),
url(r'^contact/', ContactWizard.as_view([ContactForm1, ContactForm2, ContactForm3])),
)
I'm not getting any error messages either, which is frustrating, so I don't know what I'm doing wrong. Thank you.
All I had to do was view the page source on the site. It turned out
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">"prev step"</buttom>
in contact_form.html had a typo: </buttom>. I fixed the error and now I get the comment page.
The line should be:
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">"prev step"</button>