I'm using the app django-likes and have managed to get it working. But I'm running into a very weird problem. The model "Story" is associated with the likes. Now the Story posts are repeated the number of votes they have -- for example, if they have 4 votes, they're actually repeated 4 times. Not sure what's going on. Any help much appreciated.
views.py
def home(request):
posts = Story.objects.all().order_by('votes')
form = StoryForm(request.POST or None)
if form.is_valid():
save_it = form.save(commit=False)
save_it.save()
messages.success(request, 'Thanks for adding your mix!')
return render_to_response('home.html',
locals(),
context_instance=RequestContext(request))
models.py
from django.db import models
import secretballot, likes
class Story(models.Model):
text = models.CharField(max_length=2000)
def __unicode__(self):
return self.text
secretballot.enable_voting_on(Story)
home.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load likes_inclusion_tags %}
{% block content %}
{% if user.is_authenticated %}
<h1 align=center>Add Your Mix!</h1>
<div class='col-sm-6 col-sm-offset-3'>
<h1>{{ form_title }}</h1>
<form method="POST" action="" >{% csrf_token %}
{{ form|crispy }}
<input type='submit' class='btn' value='Add{{ button_submit }}' />
</form>
</div>
{% else %}
<h1 align=center>Login and add a story!</h1>
<p align=center><a class="btn btn-primary btn-lg" href="/accounts/login/" role="button">Login!</a></p>
{% endif %}
{% for post in posts %}
<p>{{ post.text }} {% likes post %}</p>
{% endfor %}
{% endblock %}
It is possible that the {% likes post %}returns a number and Multiplies the string {{ post.text }} five times like python would. Try separating it or converting it to string.
Related
One of functionality in my training project:
subscribe to the news by check-box and e-mail.
Send newsletter daily.
The user can unsubscribe from the mailing list in his profile by unchecking the checkbox.
It so happened that first I set up a daily newsletter for users who have booleanfield = true.
For it I marked the checkboxes in the admin panel. It works.
Now it is necessary to add the checkbox and the mail field to the news page.
I'm stuck on the simplest. Tired and confused.
Please help me place a checkbox and a mail box with a send button on the news page
models.py
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
hr = models.BooleanField(default=False)
subscribed_for_mailings = models.BooleanField(default=False)
subscription_email = models.EmailField(default="")
def __str__(self):
return str(self.user)
Forms.py
class MailingForm(forms.ModelForm):
class Meta:
model = models.Profile
fields = ('subscription_email', 'subscribed_for_mailings', )
widgets = {
'subscription_email': forms.EmailInput(attrs={"placeholder": "Your Email..."}),
'subscribed_for_mailings': forms.CheckboxInput,
}
views.py
def all_news(request):
today = date.today()
today_news = models.TopNews.objects.filter(created__gte=today)
return render(request, "news.html",
{'today_news': today_news})
def mailing_news(request):
if request.method == 'POST':
mailing_form = forms.MailingForm(request.POST)
if mailing_form.is_valid():
mailing_form.save()
return HttpResponse('You will receive news by mail')
else:
mailing_form = forms.MailingForm()
return render(request, "news.html", {'mailing_form': mailing_form})
urls.py
...
path('news/', views.all_news, name='all_news'),
...
news.html
{% extends 'base.html' %}
{% block title %}
News
{% endblock %}
{% block body %}
<h1>Last news</h1>
{% for news in today_news%}
<h3>{{ news.title }}</h3>
Read this news
<p>
{{ news.created }}
</p>
<hr>
{% endfor %}
<h4>I want to receive news by mail</h4>
<form action="." method="post">
{{ mailing_form.as_p }}
{% csrf_token %}
<label>
<input type="submit" value="Subscribe">
</label>
</form>
{% endblock %}
The page displays a list of news and only the "send" button. There is no check-box and a field for mail
enter image description here
Finally I realized this functionality in a different way:
forms.py
class MailingForm(forms.ModelForm):
class Meta:
model = models.Profile
fields = ('subscribed_for_mailings', 'subscription_email', )
views.py
#login_required
def mailing_news(request):
if request.method == "POST":
mailing_form = forms.MailingForm(request.POST,
instance=request.user.profile,
)
if mailing_form.is_valid():
mailing_news = mailing_form.save(commit=False)
mailing_news.subscribed_for_mailings = mailing_news.subscribed_for_mailings
mailing_news.subscription_email = mailing_news.subscription_email
mailing_news.save()
return render(request, "subscribe_complete.html",
{"mailing_news": mailing_news})
else:
mailing_form = forms.MailingForm()
return render(request, 'subscribe.html', {"mailing_form": mailing_form})
news.html
{% extends 'base.html' %}
{% block title %}
News
{% endblock %}
{% block body %}
<h1>Last news</h1> {{ news.created }}
{% for news in today_news%}
<h3>{{ news.title }}</h3>
Read this news
<hr>
{% endfor %}
I want to receive news by mail
{% endblock %}
urls.py
...
path('subscribe/', views.mailing_news, name='subscribe')
...
news.html
{% extends 'base.html' %}
{% block title %}
News
{% endblock %}
{% block body %}
<h1>Last news</h1> {{ news.created }}
{% for news in today_news%}
<h3>{{ news.title }}</h3>
Read this news
<hr>
{% endfor %}
I want to receive news by mail
{% endblock %}
subscribe.html
{% extends 'base.html' %}
{% block title %}
Subscribe
{% endblock %}
{% block body %}
<form action="." method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ mailing_news.as_p }}
{% if user.profile.subscribed_for_mailings is True %}
<input type="checkbox" name="subscribed_for_mailings" id="id_subscribed_for_mailings" checked="">
If you don't want to receive emails anymore, uncheck
<br>
Subscription email: <input type="email" name="subscription_email" value={{ user.profile.subscription_email }} class="vTextField" maxlength="254" id="id_subscription_email">
{% else %}
<label>
<input type="checkbox" name="subscribed_for_mailings" id="id_subscribed_for_mailings">
I want to subscribe for mailing news
</label>
<p><label>
Send news on my email:
<input type="email" name="subscription_email" class="vTextField" maxlength="254" id="id_subscription_email">
</label></p>
{% endif %}
<p><input type="submit" value="Update"></p>
</form>
{% endblock %}
subscribe_complete.html
{% extends 'base.html' %}
{% block title %}
Subscribing complete
{% endblock %}
{% block body %}
<h3>Hi {{ user.username }}</h3>
Thanks for subscribing.
You will receive daily news by email: {{ user.profile.subscription_email }}
{% endblock %}
you need to change subscribed_for_mailings in mailing news, like this
def mailing_news(request):
if request.method == 'POST':
mailing_form = forms.MailingForm(request.POST)
if mailing_form.is_valid():
profile = mailing_form.save(commit=False) ####
profile.subscribed_for_mailings = mailing_form.cleaned_data.get('subscribed_for_mailings') ####
profile.subscription_email = mailing_form.cleaned_data.get('subscription_email') ####
profile.save() #### new_line
return HttpResponse('You will receive news by mail')
else:
mailing_form = forms.MailingForm()
return render(request, "news.html", {'mailing_form': mailing_form})
you can change in cleaned_data.get('....')
** for some reason my form is not showing in the template can someone tell me why ,
think you.
**
views.py
i think the problem is here but i cant find it i followed the documentation and got nothing also
def contact(request):
print(request.POST)
forms=contactform(request.POST or None)
if forms.is_valid():
print(forms.cleaned_data())
context= {
"title":"contact",
"form": forms
}
return render(request,"form.html",context)
```
> forms.py
```
from django import forms
class contactform(forms.ModelForm):
full_name=forms.CharField()
email=forms.EmailField()
text=forms.CharField(widget=forms.Textarea)
```
> form.html
```
{% extends "gta.html" %}
{% block ferr%}
{% if title %}
<h1>{{title}}</h1>
{% endif %}
<form method="POST" action="."> {% csrf_token %}
{{forms.as_p}}
<button type="submit">submitt</button>
</form>
{% endblock %}
This should sort you.
{% extends "gta.html" %}
{% block ferr%}
{% if title %}
<h1>{{title}}</h1>
{% endif %}
<form method="POST" action="."> {% csrf_token %}
{{form.as_p}}
<button type="submit">submitt</button>
</form>
{% endblock %}
I am using this exact code in another project, the only difference is that I have changed the model names, urls patterns, and template names since it is a different project. However, I am getting this error and I have no idea why. I am trying to bring the user to a detail page that has both the post and any comments on the post, as well as a link that takes to a page that allows the user to add a comment to the post.
app Views.py:
#login_required
def add_comment_to_post(request,pk):
post = get_object_or_404(UserPost,pk=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('feed:post_detail', pk=userpost.pk)
else:
form = CommentForm()
return render(request,'feed/comment_form.html',{'form':form})
userpost_detail.html (post_detail in urls)
{% extends 'base.html' %}
{% block content %}
<h1 class="posttitle">{{ userpost.title }}</h1>
<p class="postcontent">{{ userpost.post_body }}</p>
{% if request.user.is_authenticated and request.user == post.author %}
<a class="link" href="{% url 'feed:edit_post' post.id %}">Edit Post</a>
{% endif %}
<hr>
Add Comment
<div class="container">
{% for comment in post.comments.all %}
<br>
{% if user.is_authenticated or comment.approved_comment %}
{{ comment.create_date }}
<a class="btn btn-warning" href="{% url 'comment_remove' pk=comment.pk %}">
<span class="glyphicon glyphicon-remove"></span>
</a>
<p>{{ comment.comment_body }}</p>
<p>Posted By: {{ comment.author }}</p>
{% endif %}
{% empty %}
<p>No Comments</p>
{% endfor %}
</div>
{% endblock %}
comment_form.html:
{% extends 'base.html' %}
{% block content %}
<h1>New Comment</h1>
<form class="post-form" method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Add Comment</button>
</form>
{% endblock %}
Traceback and error:
Traceback (most recent call last):
File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/handlers/base.py", line 198, in _get_response
"returned None instead." % (callback.__module__, view_name)
ValueError: The view feed.views.add_comment_to_post didn't return an HttpResponse object. It returned None instead.
Your view does not return anything if the request is not a POST.
The problem is one of indentation. The last three lines - from else onwards - need to be moved back one level.
I am having a form which takes some value as input, and I am processing the input and returning the required output. Now when I tried to display the output it not displaying on the webpage.
The following is my forms.py:
class CompForm(forms.ModelForm):
class Meta:
model = Comp
fields = ('inp',)
The following is my views.py:
def index(request):
form = CompForm(request.POST or None)
context = {
'form': form,
}
print context
if form.is_valid():
...
...
outData = "The values you gave is correct"
errData = "The values you gave is incorrect"
print context
context['outData'] = outData
context['errData'] = errData
print context
return render(request, 'comp/index.html', context)
The following is my index.html:
{% extends "comp/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="row">
<div class="col-md-8 col-md-offset-2">
<form method="post" action="">
{% csrf_token %}
{{ form|crispy }}
<input class="btn btn-primary" type="submit" name="Submit" />
</form>
</div>
</div>
{% if outData %}
{{ outData.as_p }}
{% endif %}
{% if errData %}
{{ errData.as_p }}
{% endif %}
{% endblock %}
In the terminal I am able to get the outData and errData in the dictionary, but its not getting displayed in the webpage. What might be the mistake? Kindly help.
You are trying to called the method as_p on strings which doesn't make sense.
as_p() is a helper method on form instances to make it easier to render them in the template so you need:
{{ form.as_p }}
you can also use as_table and as_ul
You can read more in the documentation
I have set of questions and its answers stored in db.I have a form to get answer for each question.I need to display only one question at a time in template and validate that answer against the original answer stored in db.
For now am able to display one value.But what i need is to display a question in a page and validate if the answer is correct,move on to display next question from db and so on. How do I achieve this?
form.py
from django import forms
class details_form(forms.Form):
answer = forms.CharField(widget=forms.TextInput())
views.py
def display_question(request):
context = RequestContext(request)
if request.method == 'GET':
print "GET"
form_class = details_form()
que_data = details.objects.get(que_id=1)
else:
##POST request
return render_to_response('sample/display_question.html',{'form':form_class,'que_data':que_data},context)
template:
{% extends 'sample/base.html' %}
{% block title %} Question {% endblock %}
{% block body_block %}
<p><strong>Your question : </strong></p>
"{{ que_data.que }}"
<p><strong>Type your answer here :<strong></p>
<form id='details_form' method = 'post' action='/next'>
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<br></br>
<input type ="submit" name="submit" value="Submit"/>
</form>
{% endblock %}
Update:
views.py
def display_question(request,question_id):
context = RequestContext(request)
form_class = details_form()
try:
quesno_id = {'id':question_id}
que_data = details.objects.get(que_id=question_id)
except details.DoesNotExist:
pass
if request.method == 'POST':
form = details_form(request.POST)
if form.is_valid():
user_answer = form.cleaned_data['answer']
if que_data.original_answer == user_answer:
return HttpResponseRedirect("question/%s/" %question_id+1)
else:
print form.errors
else:
pass
return render_to_response('sample/display_question.html',{'form':form_class,'que_data':que_data,'quesno_id':quesno_id},context)
template
{% extends 'sample/base.html' %}
{% block title %} Question {% endblock %}
{% block body_block %}
<p><strong>Your question {{ quesno_id.id}} : </strong></p>
"{{ que_data.que }}"
<p><strong>Type your answer here :<strong></p>
<form id='details_form' method = 'post' action="/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<br></br>
<input type ="submit" name="submit" value="Submit"/>
</form>
{% endblock %}
urls.py
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^question/(?P<question_id>\w+)/$',views.display_question,name='display_question'),
)
models.py
from django.db import models
class Songdata(models.Model):
que_id = models.AutoField(primary_key=True)
que = models.CharField(max_length=256)
original_answer = models.TextField()
def __unicode__(self):
return self.song_name
form.py
from django import forms
class details_form(forms.Form):
user_answer = forms.CharField(widget=forms.TextInput())
You need to use an absolute URL path like HttpResponseRedirect("/question/%s/" % (question_id+1)) (notice the leading slash)