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,
}
)
Related
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')
I am having an issue where I have categories for each product, so for my URLs, i have slugs referencing to each category. in the href on my frontpage (HTML pasted down below). I see that when I load the portion of the HTML that has the for loop applied makes it disappear. I have never run into this. Does anybody have any idea what's going on? I'll post the relevant div where this is occurring. I can post additional code if needed. Thanks
In this case, the Get covered now button is missing
Edsure\apps\core\templates\frontpage.html
{% extends 'base.html' %}
{% block content %}
{% load static %}
<div id="signup">
{% for category in menu_categories %}
<a class="btn btn-lg col-sm-12 slideanim" id="title" href="{% url 'category_detail' category.slug %}">
Get Covered Now!
</a>
{% endfor %}
<a class="btn btn-lg col-sm-12 slideanim" id="title" href="#">
Learn More!
</a>
</div>
Edsure\apps\core\views.py
from django.shortcuts import render
from apps.store.models import Product
def frontpage(request):
return render(request, 'frontpage.html')
Edsure\apps\store\views.py
from django.shortcuts import render, get_object_or_404
from .models import Product, Category
def product_detail(request,category_slug, slug):
product = get_object_or_404(Product, slug=slug)
context = {
'product': product
}
return render(request, 'product_detail.html', context)
def category_detail(request, slug):
category = get_object_or_404(category, slug=slug)
products = category.products.all()
context = {
'category': category,
'products': products
}
return render(request,'category_detail.html', context)
so, in your view you have no context named "menu_categories" but "category",try this instead:
{% for c in category %}
<a class="btn btn-lg col-sm-12 slideanim" id="title" href="{% url 'category_detail' c.slug %}">
Get Covered Now!
</a>
{% endfor %}
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.
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 %}
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')