Django form won't show up on template - python

I'm making a sign in system in Django Python, i've been preparing the forms.py, views.py and the template itself, but so far the form fail to load on the template, can anyone help?
Forms.py
class Email_Only_SignUp_Form(forms.Form):
email = forms.EmailField(initial='Your Email...')
Views.py
def email_only_signup_form(request, template_name):
if request.method == 'POST':
signup_form = Email_Only_SignUp_Form(request.POST)
if signup_form.is_valid():
email = signup_form.cleaned_data['email']
username = email
try:
#check for duplicate username
User.objects.get(username=username)
email_error = 'email already exist'
except:
#initial creation of user object
try:
import os, random, string
length = 13
chars = string.ascii_letters + string.digits + '!#$()'
random.seed = (os.urandom(1024))
password = ''.join(random.choice(chars) for i in range(length))
User.objects.create_user(username,
username,
password,
)
user = User.objects.get(username=username)
user_profile=UserProfile(user=user)
user_profile.save()
#send email to user
try:
admin_email = settings.EMAIL_ORIGIN_MEMBERS
email_txt = loader.get_template('account/emails/createaccount.html')
email_html = loader.get_template('account/emails/createaccounthtml.html')
email_context = Context({'u_name': username,
'username': username,
'password': password,
})
new_user_mail = EmailMultiAlternatives('Welcome!',
email_txt.render(email_context),
admin_email,
[user.email, ],
headers={'Reply-To': 'admin#admin.com'}
)
new_user_mail.attach_alternative(email_html.render(email_context), 'text/html')
new_user_mail.send()
except:
pass
return redirect('/account/thankyou/?next=%s'%next)
except:
pass
else:
print('user form in not valid')
else:
signup_form = Email_Only_SignUp_Form()
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
email_only_signup_form.html
{% extends "index.html" %}
{% block heroslider %}
<div class="page_title2" style="padding:150px 0px 50px 0px;">
<div class="container">
<h1>User Registration</h1>
</div>
</div><!-- end page title -->
{% endblock %}
{% block main_body %}
<style type="text/css">
input[type='radio'], input[type='checkbox'] {
width:20px;
vertical-align: middle;
}
div.reg_error {
position:relative;
top:-10px;
margin-top:0px;
padding-top:0px;
color:red;
}
</style>
<div class="container">
<form class="pagesignup logiform" action="" method="POST">{% csrf_token %}
<div class="row">
<div class="large-12 columns" style="margin-bottom: 30px;">
<div class="reg_form">
<div class="sky-form">
<header>REGISTER</header>
</div>
<div class="row">
<div class="large-12 columns">
<p>Email<br/>
{{signup_form.email}}
<div class="reg_error">{{ signup_form.email.errors.as_text }}{{email_error}}</div></p>
</div>
</div>
<div class="row">
<div class="large-12 large-centered columns" style="text-align:center;padding:20px;">
<input class="but_medium1" style="border:none;" type = "submit" value="REGISTER" /><br>
<br>By clicking on register, you have read and agreed to our terms of use
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<!-- Google Code for Sign Up Page (landed) Conversion Page -->
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 969557266;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "5zU4CJby_FoQkoqpzgM";
var google_remarketing_only = false;
/* ]]> */
</script>
<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/conversion/969557266/?label=5zU4CJby_FoQkoqpzgM&guid=ON&script=0"/>
</div>
</noscript>
{% endblock %}

You have not passed the signup_form to the template.
return render_to_response(template_name, {'signup_form': signup_form}, context_instance=RequestContext(request))
I have no idea what locals() does.
Edit: I just saw locals which is a built in python function. It will be better if you explicitly pass the variables you need in the template.
Edit 2: Check if it is the correct template_name. In the template simply print and see the form {{ signup_form }}. See if it is available.

You are not returning the form.
Try changing the last line of the view to
return render_to_response(template_name, locals(), context_instance=RequestContext(request, {'signup_form' : signup_form ))

Related

How can I use GET and POST on the same form in Django

I have a project wiki using Django and python from CS50W and stuck at a point where i have to check for the title is it exist or not and if it exists i will give message and option to change the title or edit it, now this part is using GET method and if the topic does not exist it will set focus to textarea and user can ad information about the title and save it to new file now this uses methot=POST. If I write the following code my check works
createNewPage.html
<div class="form-group" style="margin-right: 20%">
<form id="newTitle" action="{% url 'save' %}" method="GET">
{% csrf_token %}
{% block newTitle %}
<label>{{ newTitle_form.title.label }}</label>
{{ newTitle_form.title }}
{% endblock %}
</form>
{% if messages %}
<div id="messageDiv" class="alert alert-info" role="alert">
{% for message in messages %}
{{ message }}
{% endfor %}
</div>
{% endif %}
{% if messages %}
<div class="h1 flex-container btn-save-placement" style="height: 0px; padding-top: 0px; margin-right: 0%">
<div>
<a role="button" id="changeTopic" class="btn btn-outline-dark" href="{% url 'new_topic' %}">Change</a>
<a role="button" class="btn btn-outline-dark" href="{% url 'edit' pagetitle %}">Edit</a>
</div>
</div>
{% endif %}
</div>
<div class="form-group" style="margin-right: 20%; margin-top: 25px">
{% block textArea %}
<label>{{ newText_form.text.label }}</label>
{{ newText_form.text }}
{% endblock %}
</div>
<div class="btn-save-placement flex-container" style="height: 48px; padding-top: 0px;">
<button class="btn btn-outline-dark" href="{% url 'save' %}" type="submit" formmethod="POST">Save New Page</a>
</div>
<script>
function blurFunction() {
var newTitleText = document.getElementById("titleCheck");
if (newTitleText.value !== null && newTitleText.value !== "") {
document.getElementById("newTitle").requestSubmit();
}
}
</script>
and if I change from the 8th line to 35th line just above the then check does not work but it saves new file. what can i change to get both working.
views.py
def save(request):
if request.method == "GET":
searchPage = request.GET.get('title','')
if(util.get_entry(searchPage) is not None):
messages.info(request, 'The Page ' + searchPage + ' Already Exists, Do You Want To Change It Or Edit It!')
return HttpResponseRedirect(reverse("new_topic_t", kwargs={'entry': searchPage}))
else:
return HttpResponseRedirect(reverse("new_topic_t", kwargs={'entry': searchPage}))
else:
title = request.POST["title"]
content = request.POST["text"]
util.save_entry(title, content)
return HttpResponseRedirect(reverse("generate_page", kwargs={'entry': title}))
forms.py
class newTitle(forms.Form):
title = forms.CharField(label='New Page Title', max_length=100, widget=forms.TextInput(
attrs={
'id': 'titleCheck',
'class': 'search',
'type': 'text',
'placeholder': 'Type Topic Title Here...',
'onblur': 'blurFunction()',
'value': ''
}))
text = forms.CharField(label='Enter Page Text', widget=forms.Textarea(
attrs={
'id': 'NewTopicText',
'class': 'form-control',
'rows': '14'
}))
You can use like this:
def save(request):
if request.method == "GET":
searchPage = request.GET.get('title','') # consider using snake_case
if(util.get_entry(searchPage) is not None):
messages.info(request, 'The Page ' + searchPage + ' Already Exists, Do You Want To Change It Or Edit It!')
return HttpResponseRedirect(reverse("new_topic_t", kwargs={'entry': searchPage}))
else:
form = newTitle() # consider using PascalCase
return render('createNewPage.html', context={'newText_form': form})
else:
form = newTitle(request.POST)
if form.is_valid():
title = form.cleaned_data["title"]
content = form.cleaned_data["text"]
util.save_entry(title, content)
return HttpResponseRedirect(reverse("generate_page", kwargs={'entry': title}))
else:
return render('createNewPage.html', context={'newText_form': form}) # will render errors in the html page
FYI, as per PEP-8 guideline, you should name variables and method names snake_case and Class names PascalCase.

Django Dependent/Chained Dropdown List - Select A Valid Choice Error

I have implemented a Dependent dropdown list within Django but when I try to submit the form I get the following error 'Select a valid choice. That choice is not one of the available choices.'
I have spent a while looking on the web for the answer and have tried a few with little avail.
From my understanding and reading, this is an error because I render the form with a queryset of none. Then I use ajax to fill in the options. Even though I have updated the dropdown list, the form validation is checking my submitted answer against a queryset of none - thus the error.
So i'm hoping someone can help me to update the choices the form will accepted on form submission.
views.py
# stage6 is where I render my view and check validation
def stage6(request):
form_deal = DealForm(request.POST or None, prefix='inst')
if form_deal.is_valid():
form_deal.save()
messages.success(request, 'Deal added successfully.')
form_deal = DealForm()
context = {
'dform': form_deal,
}
return render(request, 'stages/stage6/stage6.html', context)
# This is used for my ajax request
def load_offers(request):
property_process_id = request.GET.get('propertyprocess_link')
offers = Offer.objects.filter(propertyprocess_link=property_process_id).order_by('id')
return render(request, 'stages/stage6/offers_dropdown_list.html', {'offers': offers})
forms.py
class DealForm(forms.ModelForm):
deal_date = forms.CharField(
label='',
widget=forms.TextInput(attrs={'type': 'date'})
)
target_move_date = forms.CharField(
label='',
widget=forms.TextInput(attrs={'type': 'date'})
)
def __init__(self, *args, **kwargs):
super(DealForm, self).__init__(*args, **kwargs)
# filter the foreign keys shown
self.fields['propertyprocess_link'].queryset = PropertyProcess.objects.filter(sector="Sales")
# filter used for ajax request
self.fields['offer_accepted'].queryset = Offer.objects.none()
# add a "form-control" class to each form input
# for enabling bootstrap
for name in self.fields.keys():
self.fields[name].widget.attrs.update({
'class': 'form-control',
})
class Meta:
model = Deal
fields = ('propertyprocess_link',
'deal_date',
'price_agreed',
'target_move_date',
'offer_accepted'
)
models.py
class Deal(models.Model):
propertyprocess_link = models.ForeignKey(PropertyProcess,
on_delete=models.CASCADE)
deal_date = models.DateField()
price_agreed = models.IntegerField()
target_move_date = models.DateField()
offer_accepted = models.ForeignKey(Offer,
on_delete=models.CASCADE)
class Meta:
verbose_name_plural = "deals"
def __str__(self):
return '%s, %s' % (
self.propertyprocess_link.property_link.address_line_1,
self.propertyprocess_link.property_link.postcode
)
html
{% block content %}
<div class="container-fluid header-container">
<div class="row">
<div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
<div class="card-au card-signin my-5">
<div class="card-body">
<form id="offers-form" data-offers-url="{% url 'ajax_load_offers' %}" class=" text-center text-white" method="post" novalidate>
{% csrf_token %}
{{ dform.non_field_errors }}
<div class="form-colour mt-2">
{{ dform.propertyprocess_link.errors }}
<label class="mb-0 mt-1">Property Being Offered On:</label>
{{ dform.propertyprocess_link }}
</div><div class="form-colour mt-2">
{{ dform.offer_accepted.errors }}
<label class="mb-0 mt-1">Offer Being Accepted:</label>
{{ dform.offer_accepted }}
</div>
<div class="form-colour mt-2">
{{ dform.price_agreed.errors }}
<label class="mb-0 mt-1">Price Agreed:</label>
{{ dform.price_agreed }}
</div>
<div class="form-colour mt-2">
{{ dform.deal_date.errors }}
<label class="mb-0 mt-1">Deal Date:</label>
{{ dform.deal_date }}
</div>
<div class="form-colour mt-2">
{{ dform.target_move_date.errors }}
<label class="mb-0 mt-1">Target Move Date:</label>
{{ dform.target_move_date }}
</div>
<div class="mb-3"></div>
{# hidden submit button to enable [enter] key #}
<div class="hidden-btn" style="margin-left: -9999px"><input class="hidden-btn" type="submit" value=""/></div>
<div class="text-center mt-2">
<input type="submit" class="login-btn btn-green btn btn-lg border-green text-uppercase py-3" value="Add Deal" />
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock content %}
{% block postloadjs %}
{{ block.super }}
<script>
$("#id_inst-propertyprocess_link").change(function () {
var url = $("#offers-form").attr("data-offers-url"); // get the url of the `load_offers` view
var propertyID = $(this).val(); // get the selected Property Process ID from the HTML input
$.ajax({ // initialize an AJAX request
url: url, // set the url of the request (= localhost:8000/ajax/load-offers/)
data: {
'propertyprocess_link': propertyID // add the Property Process id to the GET parameters
},
success: function (data) { // `data` is the return of the `load-offers` view function
$("#id_inst-offer_accepted").html(data); // replace the contents of the offers input with the data that came from the server
}
});
});
</script>
{% endblock postloadjs %}
Thanks very much for any help anyone can give.

iterate users in friends list over same modal and access database content

I am making a chat box for my website. As per current implementation,i i am iterating over the current friends list and and anchor tag triggers a modal for that particular user. The modal is common for all users as it only changes the data inside.
Now, i have used jquery to fetch the message history ( from model object ) and display is modal body.
I can click on different users and view the messages in their respective models correctly. However, when i try to submit the form to send another message it gets added to the message box of first user. This is happening for all users in the friend list.
How can i trigger the form to post in the model of the correct user.
Template
{% for friend in friends_list %}
<li style="padding:10px">{{friend.to_user.usercreation.fname}} {{friend.to_user.usercreation.lname}} <i style ="color:green;font-size:0.65rem;text-align:justify;float:right;margin-top:8.5px;" class="fa fa-circle" aria-hidden="true"></i></li>
<form action="{% url 'usercreation:addmessage' friend.to_user.usercreation.pk %}" method="post">
{% csrf_token %}
<div class="modal fade" id="chatbox" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header text-center">
<h6 class="modal-title w-100">BlogChat</h6>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<pre><div class="modal-body"></div></pre>
<div class="modal-footer">
<input style="width:330px;height:40px" type="text" name="addmessage" value="" placeholder="Type..">
<button style="float:right;" type="submit" class="btn btn-primary">Send message</button>
</div>
</div>
</div>
</div>
</form>
{% endfor %}
JQUERY:
<script type="text/javascript">
$('#chatbox').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var recipient = button.data('whatever')
attributes
$.ajax({
url: "{% url 'fetcher' %}",
data: {
'search': recipient
},
dataType: 'json',
success: function (data) {
list = data.list;
$('#chatbox').find('.modal-body').text(list)
}
});
var modal = $(this)
modal.find('.modal-title').text('Chat with ' + recipient)
})
</script>
VIEWS:
def fetcher(request):
if request.is_ajax():
name = User.objects.get(username=request.GET.get('search', None))
b = ChatMessage.objects.get(user1 = request.user,user2 = name)
print(b.message)
data = {
'list': b.message,
}
print(data)
return JsonResponse(data)
def addmessage(request,pk):
if request.method=='POST':
print(request.user)
print(User.objects.get(username=UserCreation.objects.get(pk=pk)))
obj = ChatMessage.objects.get(user1 = request.user , user2 = User.objects.get(username=UserCreation.objects.get(pk=pk)) )
obj2 = ChatMessage.objects.get(user2 = request.user , user1 = User.objects.get(username=UserCreation.objects.get(pk=pk)) )
name = request.POST.get('addmessage')
obj.message += ('\n'+str(request.user)+': '+name)
obj2.message += ('\n'+str(request.user)+': '+name)
obj.save()
obj2.save()
return HttpResponseRedirect(reverse('usercreation:profile',args=[request.user.usercreation.pk]))
Models:
class ChatMessage(models.Model):
user1 = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="participant1")
user2 = models.ForeignKey(User, on_delete=models.CASCADE , related_name="participant2")
message = models.TextField(default="")
date = models.DateTimeField(auto_now=True, db_index=True)

How to update form element data value after construction using multidict

I have a website post creator / editor im writing. I have successfully been able to create post (saves to json) , get a pull down menu list of the made post from same db (and a second, all posts.json, which is where the list of posts comes from. ), and have the element forms populated with said information. I can then save it, and it is indeed writing to the file. Problem is , the data in the text fields is not updating in saved post. It saves the original data passed with the multidict. I CAN manually update it as : Ex. form.title.data = "New Title" , and it saves as such, so i know its handling everything correctly on the save end. If anyone has an idea how to get the updated information from the form fields, id be grateful. Thank you.
Constructors at line 103
Code:
https://hastebin.com/lafavifike.py
from flask import Flask, render_template, request, flash, redirect, url_for
from QFlask import QFlask
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired
from wtforms.fields import Field, TextAreaField, TextField, SelectField
from wtforms.widgets import TextArea
import os, json
from werkzeug.datastructures import MultiDict
app = Flask(__name__)
app.config['SECRET_KEY'] = "test"
class editPostForm(FlaskForm):
id_pos = ['blog_posts', 'security_posts', 'game_posts','music_posts','project_posts']
file_path_all = str(os.getcwd()) + "\\static\\allposts.json"
with open(file_path_all, 'r') as post_edit:
all_posts = json.load(post_edit)
posts = [('default', 'Choose Post To Edit')]
for key in all_posts.keys():
if key not in id_pos:
posts.append((all_posts[key]['id'], all_posts[key]['title']))
loadform = SelectField('Choose Post', choices=posts)
loadposts = SubmitField('Load')
class PostForm(FlaskForm):
#Actual form fields
categories = [('blog_posts','Blog Post'), ('security_posts','Security Post'),('game_posts','Games Post'),('music_posts','Music Post'),('project_posts','Projects Post')]
category = SelectField('Category', choices = categories, validators = [DataRequired()])
title = StringField('Title', validators=[DataRequired()])
date = StringField('Date', validators=[DataRequired()])
content = TextAreaField('Content', validators=[DataRequired()], widget=TextArea())
submit = SubmitField('Submit')
#app.route('/', methods=['POST', 'GET'])
def index():
file_path = str(os.getcwd()) + "\\static\\posts.json"
with open(file_path, 'r+') as post_edit:
data = json.load(post_edit)
positions = {}
for key in data['id_pos'].keys():
positions[key] = data['id_pos'][key]
#Create Post Form
prefixs = {'1':'blog_posts','2':'security_posts',"3":"game_posts","4":"music_posts","5":"project_posts"}
form = PostForm()
edit_form = editPostForm()
if request.method == 'POST':
print(edit_form.loadform.data)
if edit_form.loadform.data != 'None':
return redirect('/edit_post/'+ edit_form.loadform.data)
else:
form.validate()
category = form.category.data
title = form.title.data
date = form.date.data
content = form.content.data
post_id = str(int(positions[category]) +1)
post = {
"id": post_id,
"title": title,
"date": date,
"content": content
}
#Update data structure, and save back to the file
data['id_pos'][category] = post_id
data[category][post_id] = post
#SAVE POST
data['index_posts'][post_id] = post
with open(file_path, 'w') as post_edit:
json.dump(data, post_edit)
print('Post Saved')
flash('Post Saved')
file_path_all = str(os.getcwd()) + "\\static\\allposts.json"
with open(file_path_all, 'r+') as file:
data = json.load(file)
with open(file_path_all, 'w') as file:
data[post_id] = post
json.dump(data, file)
return redirect(url_for('index'))
return render_template('post_editor.html', title="Post Creator", form=form, edit_form = edit_form)
#app.route('/edit_post/<id>', methods=['GET','POST'])
def edit_post(id):
#Load data from JSON Files. posts= categorized posts, allposts is all posts key'd by id.
file_path_all = str(os.getcwd()) + "\\static\\allposts.json"
file_path = str(os.getcwd()) + "\\static\\posts.json"
with open(file_path, 'r+') as post_edit:
data = json.load(post_edit)
with open(file_path_all, 'r') as post_edit:
all_posts = json.load(post_edit)
posts = [('default', 'Choose Post To Edit')]
for key in all_posts.keys():
posts.append((all_posts[key]['id'], all_posts[key]['title']))
#Auto filling category and data for fields
prefixs = {'1':'blog_posts','2':'security_posts',"3":"game_posts","4":"music_posts","5":"project_posts"}
category = prefixs[id[0]]
form = PostForm(MultiDict([("id", id),("title", data[category][str(id)]['title']) ,("date", data[category][str(id)]['date']),("content" , data[category][str(id)]['content'])]))
if request.method == "POST":
form.validate()
data[category][str(id)] = {
'id': str(id),
'title': form.title.data,
'date': form.date.data,
'content': str(form.content.data)
}
all_posts[str(id)] = {
'id': str(id),
'title': form.title.data,
'date': form.date.data,
'content': str(form.content.data)
}
#Write to file.
print('Saving the edited post..')
with open(file_path_all, 'w') as file:
json.dump(all_posts,file)
print('File Saved ')
with open(file_path, 'w') as file:
json.dump(data,file)
flash('File Saved')
return redirect('/')
return render_template('edited_post.html', title="Post Editor", form = form)
if __name__ == '__main__':
QFlask(app).run(title="Web Post Editor", zoom=0, width=600, height= 600)
posteditor.html
<html>
<head><title> Post Editor</title>
<style src="{{url_for('static', filename='css/bootstrap.min.css')}}"></style>
<style>
pre{
content-align: left;
}
body{
color: grey;
background-image: url({{url_for('static', filename='img/editor-bg.jpg')}});
}
</style>
<script src="{{url_for('static', filename='js/jquery.min.js')}}"></script>
<script src="{{url_for('static', filename='js/popper.js')}}"></script>
<script src="{{url_for('static', filename='js/bootstrap.min.js')}}"></script>
</head>
<body>
<div class="container">
{% with message = get_flashed_messages()%}
<ul class="flashes">
{{message}}
</ul>
{% endwith%}
{{ form.csrf_token }}
<form method="POST" action="" id="selection">
<fieldset class="form-group">
<div class="form-group">
{{edit_form.loadform.label(class="form-control-label")}}
{{ edit_form.loadform(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ edit_form.loadposts(class="btn btn-outline-info")}}
</div>
</fieldset>
</form>
<form method="POST" action="">
<fieldset class="form-group">
<div class="form-group">
{{ form.category.label(class="form-control-label")}}
{{ form.category(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.title.label(class="form-control-label")}}
{{ form.title(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.date.label(class="form-control-label")}}
{{ form.date(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.content.label(class="form-control-label")}}
{{ form.content(cols="50", rows="20",class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</fieldset>
</form>
</div>
</body>
</html>
editedpost.html:
<html>
<head><title> Post Editor</title>
<style src="{{url_for('static', filename='css/bootstrap.min.css')}}"></style>
<style>
pre{
content-align: left;
}
body{
color: grey;
background-image: url({{url_for('static', filename='img/editor-bg.jpg')}});
}
</style>
<script src="{{url_for('static', filename='js/jquery.min.js')}}"></script>
<script src="{{url_for('static', filename='js/popper.js')}}"></script>
<script src="{{url_for('static', filename='js/bootstrap.min.js')}}"></script>
</head>
<body>
<div class="container">
{% with message = get_flashed_messages()%}
<ul class="flashes">
{{message}}
</ul>
{% endwith%}
<form method="POST" action="">
{{ form.csrf_token }}
<fieldset class="form-group">
<div class="form-group">
{{ form.category.label(class="form-control-label")}}
{{ form.category(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.title.label(class="form-control-label")}}
{{ form.title(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.date.label(class="form-control-label")}}
{{ form.date(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.content.label(class="form-control-label")}}
{{ form.content(cols="50", rows="20",class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</fieldset>
</form>
</div>
</body>
</html>
I found the answer(with the help of some IRC folk ).The problem was the form data was always pulling from the initialized version. It never requested the update from the page. in data[category][str(id)] = , the values should be updated via request.form.get('title')

Django error : Matching query does not exist

I am working on a blog project and I am getting the "Matching query does not exist "error. I have tried using try block thinking that the model class might not be returning any value. Hence, modified my views.py as below:-
from django.shortcuts import render, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
from django.db.models import Q
from .forms import *
# Create your views here.
def home(request):
print("I am home")
try:
blog_data = BlogPost.objects.all()
print("blog_data", blog_data)
except BlogPost.DoesNotExist:
blog_data = None
print("blog_data", blog_data)
try:
last_element = BlogPost.objects.filter(id = len(blog_data))[0]
print("last_element", last_element)
except BlogPost.DoesNotExist:
last_element = None
print("last_element", last_element)
tags_list = BlogPost.objects.values_list("tags", flat = True).distinct()
#tags_list = BlogPost.objects.all().distinct()
context = {'blog_data':blog_data, "last_element":last_element, "tags_list":tags_list}
#last_element = list(BlogPost.objects.all().reverse()[0])
print("last_element",last_element, "blog_data",blog_data,"context",context)
return render(request, 'blog/home.html', context)
# def home(request):
# blog_data = BlogPost.objects.all()
# context = {'blog_data':blog_data}
# print('context', context)
# last_element = BlogPost.objects.all().reverse()[0]
# #last_element = BlogPost.objects.all().reverse()[0]
# return render(request, 'blog/home.html', context)
def new_post(request):
if request.method == 'POST':
form = BlogForm(data = request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('home')
else:
form = BlogForm()
return render(request, 'blog/blogform.html', {'form':form })
def login_user(request):
username = password = ''
state = "Please log in"
if request.POST:
username = request.POST.get('Username')
password = request.POST.get('Password')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
state = "You're successfully logged in!"
return HttpResponseRedirect('/blog/home')
else:
state = "Your account is not active, please contact the site admin."
else:
state = "Your username and/or password were incorrect."
#return render_to_response('main/login.html',{'state':state, 'username': username})
return render(request, "blog/login.html", {'state':state, 'username': username, 'next_page':"home.html"})
#return HttpResponseRedirect("home.html")
def logout_user(request):
logout(request)
return render(request,'blog/home.html')
def register_user(request):
username = password = password_again = email = ''
state = ''
if request.method == 'POST':
username = request.POST.get('Username')
password = request.POST.get('Password')
password_again = request.POST.get('Password_again')
email = request.POST.get('Email')
print('email', email)
if password == password_again:
password = make_password(password, salt = None, hasher = 'default')
else:
state = "Password and password re-entered do not match, please try again..."
return HttpResponseRedirect('login')
print("at 63")
try:
user = User.objects.get(username = username)
print('user at 67', user)
except Exception as e:
print("Error is :", e)
user = None
print("user", user)
try:
emailID = User.objects.get(email = email)
print("emailID", emailID)
except Exception as e:
print("Error is :", e)
emailID = None
print("emailID exception", emailID)
if user is not None:
state = 'Username already exists, please try another one...'
else:
if emailID is None:
new_user = User(username = username, password = password, email = email)
##Adding new logic for securityQAs vvv
#new_SQA = SecurityQA(user_email = email, security_question = security_question, security_answer = security_answer)
##Adding new logic for securityQAs ^^^
new_user.save()
#new_SQA.save()
state = 'You are successfully registered.. Thanks'
return HttpResponseRedirect('login')
else:
state = "Email ID already registered, try a new one.."
print('state at else', state)
#return HttpResponseRedirect('login')
return render(request, "blog/register.html", {'state':state, 'username':username, 'next_page':'home.html'})
def forgot_password(request):
pass
def comment_posted(request):
return render(request, "blog/comment_posted.html")
def blog_search(request):
qset = Q()
keyword = ''
keyword = request.POST.get('keyword')
print("keyword", keyword)
for word in keyword.split():
qset |= (Q(title__contains = word)|Q(description__contains = word))
print('qset', qset)
result = BlogPost.objects.filter(qset)
context = {'result':result}
return render(request, 'blog/blog_search.html', context)
Also, find my models.py below
from django.db import models
from django.contrib.auth.models import User
#from django.core.files.storage import FileSystemStorage
#fs = FileSystemStorage(location='E:\django\myblog\\blog\uploaded images')
# Create your models here.
class BlogPost(models.Model):
title = models.CharField(max_length = 30)
posted_by = models.CharField(max_length = 30)
posted_on = models.DateTimeField(auto_now_add = True)
description = models.CharField(max_length = 200)
comment = models.CharField(max_length = 150)
tags = models.CharField(max_length=50, default = "notag")
image = models.ImageField(upload_to = 'uploaded_images', default = None, null = True, blank = True)
def __str__(self):
#return "{0} : {1}".format(self.title, self.description)
return self.title
template code as below (home.html). Here I am getting the error at line "{% get_comment_list for blog.blogpost last_element.id as comment_list %}"
{% load staticfiles %}
{%load comments%}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Sourav's blog</title>
<!-- Bootstrap Core CSS -->
{%block styling%}
<link href="{%static 'css/bootstrap.min.css'%}" rel="stylesheet">
<!-- Custom CSS -->
<link href="{%static 'css/blog-post.css'%}" rel="stylesheet">
{%endblock styling%}
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Ideate</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
New idea
</li>
<!-- <li>Login</li> -->
{{user.is_authenticated}}
{% if user.is_authenticated %}
<li>
Logout
</li>
{% else %}
<li>
Login
</li>
{% endif %}
<li>
Help
</li>
{% if user.is_authenticated %}
<li>
Hi {{user.username}}
</li>
{%else%}
{% endif %}
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<!-- Page Content -->
<div class="container">
<div class="row">
<!-- Blog Post Content Column -->
<div class="col-lg-8">
<!-- Blog Post -->
<!-- Title -->
<h1>Idea Blog</h1>
<!-- Author -->
<p class="lead">
by Sourav
</p>
<hr>
<!-- Date/Time -->
<p><span class="glyphicon glyphicon-time"></span>
Posted on
<!-- {%for i in blog_data%}
{{i.posted_on}}
{%endfor%}</p> -->
{{last_element.posted_on}}
<hr>
<!-- Preview Image -->
<img class="img-responsive" src="http://placehold.it/900x300" alt="">
<hr>
<!-- Post Content -->
<!-- <p>Below is the result</p> -->
<!-- <p>{{blog_data}}</p> -->
<p>
<!-- {%for i in blog_data%}
<h1>{{i.title}}</h1>
<p>{{i.description}}</p>
{%empty%}
<span>No data</span>
{%endfor%} -->
<!-- {{last_element}} -->
<h1>{{last_element.title}}</h1><span> posted by {{last_element.posted_by}}</span>
<p>Description : {{last_element.description}}</p>
{{last_element.image}}
<p>Tags : {{last_element.tags}}</p>
{% get_comment_count for blog.blogpost last_element.id as comment_count %}
<p>{{ comment_count }} comments have been posted.</p>
{% get_comment_list for blog.blogpost 1 as comment_list %}
{% for comment in comment_list %}
<p>Posted by: {{ comment.user_name }} on {{ comment.submit_date }}</p>
<p>Comment: {{ comment.comment }}</p>
{% endfor %}
{% get_comment_form for blog.blogpost last_element.id as form %}
<!-- A context variable called form is created with the necessary hidden
fields, timestamps and security hashes -->
<table>
<form action="{% comment_form_target %}" method="post">
{% csrf_token %}
{{ form }}
<tr>
<td colspan="1">
<input type="submit" name="submit" value="Post">
<input type="submit" name="preview" value="Preview">
<input type="hidden" name="next" value="{% url 'comment_posted' %}" />
</td>
</tr>
</form>
</table>
{% get_comment_list for blog.blogpost last_element.id as comment_list %}
{%for comment in comment_list%}
<li><b>{{comment.name}}</b> has posted comment on {{comment.submit_date}} </li>
<ul><li>{{comment.comment}}</li></ul>
<a name="c{{ comment.id }}"></a>
<a href="{% get_comment_permalink comment %}">
see comment details
</a>
{%endfor%}
</p>
</div>
<div class="col-md-4">
<!-- Blog Search Well -->
<form action = "{%url 'blog_search'%}" method = "POST">
<div class="well">
<h4>Blog Search</h4>
<div class="input-group">
{%csrf_token%}
<input type="text" class="form-control" name = "keyword", placeholder = "Enter search keyword">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
<!-- /.input-group -->
</div>
</form>
<!-- Blog Categories Well -->
<div class="well">
<h4>Tags</h4>
<div class="row">
<div class="col-lg-6">
<ul class="list-unstyled">
<!-- {%for a in tags_list%}
{{a}}
{%endfor%} -->
<!-- {%for a in tags_list%}
{{a}}
{%endfor%} -->
{%for a in tags_list%}
{{a}},
{%endfor%}
<!-- <li>Category Name
</li>
<li>Category Name
</li>
<li>Category Name
</li>
<li>Category Name
</li> -->
</ul>
</div>
<div class="col-lg-6">
<ul class="list-unstyled">
<li>Category Name
</li>
<li>Category Name
</li>
<li>Category Name
</li>
<li>Category Name
</li>
</ul>
</div>
</div>
<!-- /.row -->
</div>
<!-- Side Widget Well -->
<div class="well">
<h4>Side Widget Well</h4>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore, perspiciatis adipisci accusamus laudantium odit aliquam repellat tempore quos aspernatur vero.</p>
</div>
</div>
</div>
</div>
</div>
<!-- Blog Sidebar Widgets Column -->
<!-- /.row -->
<hr>
<!-- Footer -->
<footer>
<div class="row">
<div class="col-lg-12">
<p>Copyright © Your Website 2014</p>
</div>
</div>
<!-- /.row -->
</footer>
</div>
<!-- /.container -->
<!-- jQuery -->
{%block javascript%}
<script src="{%static 'js/jquery.js'%}"></script>
<!-- Bootstrap Core JavaScript -->
<script src="{%static 'js/bootstrap.min.js'%}"></script>
{%endblock javascript%}
</body>
</html>
When I am loading my homepage (home.html) I am not facing any issue, however, when I am trying to logout after logging in i am facing the error . My logout view is rendering home.html also. However, in this case it doesn't work. Please help me out of this. I am stuck.
My quick answer is that the logout view function is not providing the context variables that the home.html template needs. Try redirecting to the home view instead.

Categories

Resources