Django form not rendering in HTML - 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')

Related

Input fields are makred always RED in Djano UserRegistrationForm

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)

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

How to extend my contact form to main page?

I'm trying to extend my contact.html which contains contact form to my 'home.html' which acts as base.html. But it's not working and I tried many ways yet not working. Basically, the form not appearing on home.html when it suppose to be. However, it appears as usual on localhost:8000/contact.
My code are as following.
Home.html
<section id="contact-us" class="section">
<div class="main-contact">
<div class="col-xs-6 col-lg-4">
<div class="contact">
<h2>LET US HELP YOU</h2>
<p> Push the boundaries of efficiency and excellence through game changing solutions.<br>
We provide innovative solutions that combine international best practices with cutting edge technology for finaciers, governments and property professionals.<br>
Speak to us or email us at info#resolutions.com.my today about how we can help your organisation get ahead.</p>
</div>
</div>
<div class="form">
<h3>FILL UP THE FORM BELOW FOR MORE INFORMATION ABOUT VALUATION MANAGEMENT SYSTEM</h3>
<div id="active">
<li><a href='{% url "contact.html" %}'></a></li>
{% block content %}
{% endblock %}
</div>
</a></li>
</div>
</div>
</section>
contact.html
{% extends "home.html" %}
{% load envelope_tags %}
{% block default-active %}active{% endblock %}
{% block content %}
<form action="{% url 'envelope-contact' %}" method="post">
{% csrf_token %}
{% antispam_fields %}
{{ form.as_p }}
<input type="submit" value="Send!" />
</form>
{% endblock %}
added my views.py
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from re_web.forms import ContactForm
# Create your views here.
from django.views.generic import (
TemplateView,
CreateView,
UpdateView,
DeleteView,
ListView,
DetailView,
)
from django.core.urlresolvers import reverse
from re_web.models import Article
class HomeView(TemplateView):
template_name = 'home.html'
def contact(request):
form_class = ContactForm
return render(request, 'contact.html', {
'form': form_class,
}
)

Django unable to render form in table format

I have a django formset and I am trying to render it row by row. Instead, the form is being render column by column (like a vertical form instead of horizontal). I am using django's form.as_table but it is still not rendering correctly. Any ideads?
form.html:
<form id="formset" class="original" action="{% url 'inventory:requests' inventory.id %}" method="post">{% csrf_token %}
<!-- Add New Row -->
{{formset.management_form}}
{% for form in formset.forms %}
{{ form.non_field_errors }}
{{ form.errors}}
<div class='item'>
<table>{{ form.as_table }}</table>
<p style=""><a class="delete" href="#">Delete</a></p>
</div>
{% endfor %}
<p><a id="add" href="#">Add another item</a></p>
<input type="submit" name="submit" value="Request Blocks" id="submitButton">
</form>
The form's as_table method just uses <tr></td> instead of <div> to render your form - but it will be rendered visually the same way.
To easily get control over your form, consider using django-crispy-forms. Here is is how you would make your form render horizontally:
In your forms.py, add this (in addition to your normal code):
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
class ExampleFormSetHelper(FormHelper):
def __init__(self, *args, **kwargs):
super(ExampleFormSetHelper, self).__init__(*args, **kwargs)
self.form_method = 'post'
self.render_required_fields = True
self.template = 'bootstrap/table_inline_formset.html'
self.add_input(Submit("submit", "Save"))
Next, in your views.py:
from .forms import ExampleFormsetHelper, YourFormSet
def formset_view(request):
formset = YourFormSet()
helper = ExampleFormSetHelper()
return render(request, 'template.html',
{'formset': formset, 'helper': helper})
Finally, in your template, all you need is:
{% load crispy_forms_tags %}
{% crispy formset helper %}
For more details, the documentation has the specifics.