Form not Rendered in Django - html

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)

Related

How do I use the onsubmit function in Django to switch pages?

I'm trying to create a page that, once a form submit button is clicked, will redirect to the home page. I'm using the 'onsubmit' function for that, but it isn't working.
HTML code
{% extends 'base.html' %}{% load static %}
{% block head %}
<link rel="stylesheet" href="{% static 'login.css' %}" />
<script src="{% static 'login.js'}"></script>
{% endblock %}
<!-- page code -->
{% block pagename %}
<p>SIGN IN</p>
{% endblock %}
{% block content %}
<div class="contentContainer">
<p>Please enter your competition ID:</p>
<form class="form" onsubmit="pageSwitch()">
<input type="text" id="entry" placeholder="ID ENTRY HERE...">
<input type="submit" id="entrySubmit" value="SUBMIT">
</form>
</div>
{% endblock %}
JS Code
function pageSwitch(){
window.location.replace("{% url 'home' %}");
}
urls.py Code
from django.contrib import admin
from django.urls import path
from files import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('test/', views.test, name='test'),
path('', views.login, name='login'),
path('home/', views.home, name='home'),
path('leaderboard/', views.lboard, name='lboard'),
path('scorecard/', views.score, name='score'),
path('submit/', views.submit, name='submit'),
path('base/', views.base, name='base'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
'views.py' Code
from django.shortcuts import render
# Create your views here.
def test(request):
return render(request, 'test.html')
def base(request):
return render(request, 'base.html')
def login(request):
return render(request, 'login.html')
def home(request):
return render(request, 'home.html')
def lboard(request):
return render(request, 'leaderboard.html')
def score(request):
return render(request, 'score.html')
def submit(request):
return render(request, 'submit.html')
def base(request):
return render(request, 'base.html')
I'm not really sure what else to try, I've been messing around with either using anchors and 'onclick' instead, but that hasn't worked either, so I'm a bit stuck. This is my first time using Django, so all of the other explanations I've found have been a bit too complex for me to understand, including things that aren't in my code that have thrown me off a bit.
When using a form's onsubmit event to call a function and redirect to another page, it's important to prevent the default form submission behavior, which can interfere with the redirect. One solution is to add an event parameter to the function, and then use event.preventDefault() to stop the form submission. For example:
<form onsubmit="myFunction(event)">
...
</form>
<script>
function myFunction(event) {
event.preventDefault();
window.location.replace('https://example.com');
}
</script>
This way, the preventDefault() method will be called before the form is submitted, ensuring that the redirect will happen immediately.

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)

I can't add data to the database through form

I have been working on making a website in which people can post the evaluation of the restaurant they visited. I want users to post data through a form, but I can't make a form page work as I imagined. To speak the detail, the data put in the form isn't added to the database. Please tell me why the system doesn't work. I can't find the data I typed in the form on admin page and "Tabelog/list.html".
The function named "form" is the one trying to show the form on the page and save data to the database.
models.py
from django.db import models
stars = [
(1,"☆"),
(2,"☆☆"),
(3,"☆☆☆"),
(4,"☆☆☆☆"),
(5,"☆☆☆☆☆")
]
# Create your models here.
class Tabelog(models.Model):
store_name = models.CharField("店名",max_length = 124)
evaluation = models.IntegerField("評価",choices = stars)
comment = models.TextField("口コミ")
def outline(self):
return self.comment[:10]
def __str__(self):
return ("{},{},{}".format(self.store_name,self.evaluation,self.comment[:10]))
forms.py
from django import forms
from django.forms import ModelForm
from Tabelog.models import Tabelog
class CreateTabelogForm(forms.ModelForm):
class Meta:
model = Tabelog
fields = "__all__"
urls.py
from django.urls import path,include
from Tabelog import views
app_name = "Tabelog"
urlpatterns = [
path("lp/", views.lp,name="lp"),
path("list/",views.list,name="list"),
path("detail/<str:store_name>",views.detail,name="detail"),
path("form/",views.form,name="form")
]
views.py
from django.shortcuts import render
from Tabelog.models import Tabelog
from Tabelog.forms import CreateTabelogForm
# Create your views here.
def lp(request):
return render(request,"Tabelog/lp.html")
def list(request):
info = Tabelog.objects.all()
context = {
"info":info,
}
return render(request,"Tabelog/list.html",context)
def detail(request,store_name):
detail = Tabelog.objects.get(store_name = store_name)
context = {
"detail":detail,
}
return render(request,"Tabelog/detail.html",context)
def form(request):
if request.method == "GET":
form = CreateTabelogForm()
context = {
"form":form
}
return render(request,"Tabelog/form.html",context)
else:
form = CreateTabelogForm(request.POST or None)
if request.method == "post" and form.is_valid():
form.save()
return redirect("Tabelog:list")
else:
form = CreateTabelogForm()
context = {
"form":form
}
return render(request,"Tabelog/form.html",context)
base.html
<!DOCTYPE html>
<html lang="ja" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<title>Tabelog</title>
</head>
<body>
<div class="container">
<header>
Welcome to Tabelog!
</header>
<main>
{% block content%}
{% endblock %}
</main>
<footer>Thank you for providing information!</footer>
</div>
</body>
</html>
form.html
<!DOCTYPE html>
{% extends 'Tabelog/base.html' %}
{% block content %}
<form action="" method="post">
{{ form.as_p }}
{% csrf_token %}
<button type="submit">SUBMIT!</button>
</form>
{% endblock %}
list.html
<!DOCTYPE html>
{% extends 'Tabelog/base.html' %}
{% block content %}
{% for contents in info%}
<article class="store">
<h1> {{contents.store_name}}</h1>
<h2>{{contents.get_stars_display}}</h2>
<span>{{contents.outline}}</span>
</article>
{% endfor %}
{% endblock %}
I think there is a typo here. You have used request.method=="post", it should request.method == "POST". To be honest, that check is reduandent, so you should remove it.
def form(request):
if request.method == "GET":
form = CreateTabelogForm()
context = {
"form":form
}
return render(request,"Tabelog/form.html",context)
else:
form = CreateTabelogForm(request.POST or None)
if request.method == "post" and form.is_valid():
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# remove this code
A refactored version of that code:
def form(request):
form = CreateTabelogForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
form.save()
return redirect("Tabelog:list")
context = {
"form":form
}
return render(request,"Tabelog/form.html",context)

Django form not showing in template

Why is the form not showing in the browser?
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{ structure.name }} - Details</title>
</head>
<body>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<h3>Structure: {{ structure }}</h3>
<h3>Ajouter enregistrement</h3>
<form action="{% url 'Structure:addrecord' structure.id %}" method="post">
{% csrf_token %}
{% for structure in all_structures %}
<input type="radio" id="record{{ forloop.counter }}" name="record" value="record.id">
<label for="record{{ forloop.counter }}">
Nom de l'enregistrement: {{ record.record_name }}
</label>
{% endfor %}
</form>
</body>
</html>
When I test this in my browser, and inspect it, it gives me a form of this size: 1340px * 0 px.
I even explicitly gave a style="height: 500px", but it still gives me an empty form.
Here's a screenshot
Thanks for the help guys!
Edit:
Views.py:
from django.shortcuts import render, get_object_or_404
from .models import Structure, Record
def index(request):
all_structures = Structure.objects.all()
return render(request, 'Structures/index.html', {'all_structures': all_structures})
def detail(request, structure_id):
#structure = Structure.objects.get(pk=structure_id)
structure = get_object_or_404(Structure, pk=structure_id)
return render(request, 'Structures/details.html', {'structure': structure})
def addRecord(request, structure_id, record.name, record.type, record.pos, record.long):
r = Record(structure='structure_id', name='record.name', type='record.type', pos='str(record.pos)', long='str(record.long)')
r.save()
return render(request, 'Structures/details.html', {'structure': structure})
Also, I do not quite understand this yet because I am using a video tutorial series by thenewboston's channel, the variables I am using in addRecord are not known, and I want to use them from the model. Here are the models and urls files as well:
models.py:
from django.db import models
class Structure(models.Model):
name = models.CharField(max_length=120)
path = models.CharField(max_length=200)
def __str__(self):
return self.name
class Type(models.Model):
typename = models.CharField(max_length=50)
def __str__(self):
return self.typename
class Record(models.Model):
structure = models.ForeignKey(Structure, on_delete=models.CASCADE) #each structure has many records, each per line
name = models.CharField(max_length=200)
type = models.ForeignKey(Type)
pos = models.IntegerField()
long = models.IntegerField()
def __str__(self):
return self.name
urls.py:
from django.conf.urls import url
from . import views
app_name = 'Structure'
urlpatterns = [
# /structures/
url(r'^$', views.index, name='index'),
# /structures/id
url(r'^(?P<structure_id>[0-9]+)/$', views.detail, name='detail'),
# /structures/addrecord
url(r'^(?P<structure_id>[0-9]+)/addrecord/$', views.addRecord, name='addrecord'),
]
Look for the value of all_structures that you are passing in context from views.
If it is empty or not passed, form fields won't be displayed as per your template code.
Try to print its value either in the console or in template. That's how to Debug.
Hope this helps.

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>