How to Add a comment section in Django using model form - html

I m New in Django I started a project of blog I wanted to add A comment section feature in my Project I Am Having a error Mode form is not defined in class
view.py
from Blog.models import Comment
from Blog.forms import CommentForm
def post_detail_view(request,year,month,day,post):
post=get_object_or_404(Post,slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
comments=Comment.objects.filter(active=True)
csubmit=False
if request.method=='POST':
form=CommentForm(data=request.POST)
if form.is_valid():
new_comment=form.save(commit=False)
new_comment.post=post
new_comment.save()
csubmit=True
else:
form=CommentForm()
return render(request,'blog/detail.html',{'post':post,'comments':comments,'csubmit':csubmit,'form':form})
if I tried to run this function I want to display a form in detail page and if end user submit the form then display same page
detail.html
<!doctype html> {% extends "blog/base.html" %} {% block title_block %} detail Page {% endblock%} {% block body_block %}
<h1>This Is Your Content</h1>
<div>
<h2>{{post.title|title}}</h2>
</div>
<div>
{{post.body|title|linebreaks}}
<p>Publised of {{post.publish|title}} Published By {{post.author|title}}</p>
<div>
{% with comments.count as comments_count %}
<h2>{{comments_count}} Comment{{comments_count|pluralize}}</h2>
{% endwith%}
<div>
{%if comments %} {%for comment in comments %}
<p> comment {{forloop.counter}} by {{comment.name}} on {{comment.created}}
</p>
<div class="cb">{{comment.body|linebreaks}}</div>
<hr> {%endfor%} {%else%}
<p>There are NO Comments Yet !!!</p>
{%endif%} {%if csubmit %}
<h2>Your Comment Added Succefully</h2>
{%else%}
<form method="post">
{{form.as_p}} {%csrf_token%}
<input type="submit" name="" value="Submit Comment">
</form>
{%endif%}
</div>
{%endblock%}
here I defined my form
forms.py
from Blog.models import Comment
class CommentForm(ModelForm):
class meta:
model=Comment
fields=('name','email','body')
related model I m mentioning in below
models.py
class Comment(models.Model):
post=models.ForeignKey(Post, related_name=('comments'), on_delete=models.CASCADE)
name=models.CharField( max_length=32)
email=models.EmailField()
body=models.TextField()
created=models.DateTimeField( auto_now_add=True)
updated=models.DateTimeField (auto_now=True)
active=models.BooleanField(default=True)
class meta:
ordering=('-created',)
def __str__(self):
return 'Cammnted by{} on {}'.format(self.name,self.post)

Update your forms.py to this and it would work
from django.db.models import fields
from django import forms
from Blog.models import Comment
class CommentForm(forms.ModelForm):
class meta:
model=Comment
fields=('name','email','body')

Related

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

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

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

Language choice affects text overflow in html(bootstrap) (Django)

I'm using bootstrap to implement my post detail page.
It works well and fit perfectly into tho format when using Korean.
But, if I wrote english contents, it overflow the format.
What's wrong with it?
Here is the code :
models.py
from django.db import models
from django.core.urlresolvers import reverse
from django.conf import settings
def upload_location(instance, file_name):
return "{}/{}".format(instance.author.username, file_name)
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = models.TextField()
image = models.ImageField(upload_to=upload_location, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-created_at',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse(
"posts:detail",
kwargs={
"pk": self.id,
}
)
def get_image_url(self):
if self.image:
return self.image.url
return "http://placehold.it/300x200"
post_detail.html
{% extends 'chacha_dabang/skeleton/base.html' %}
{% load pipeline %}
{% block content %}
<div class="container">
<section class="post-content-section">
<h2> {{ post.title }} </h2>
<h5 style="text-align: right;"> {{ post.created_at }} </h5>
<hr class="thin">
<img src="{{ post.get_image_url }}" alt="image">
<p> {{ post.content }} </p>
</section>
</br>
<hr class="thin">
</br>
<section id="comment-section" data-post-id={{ post.pk }}>
<h3> 댓 글 (<span id="comment-count"></span>)</h3>
<ul>
</ul>
<form method="POST" action="">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
</section>
</div>
{% endblock %}
{% block custom_js %}
{% javascript "comments" %}
{% javascript "message" %}
{% endblock %}

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.