Django edit comment - python

So i want to do a edit existing comment, but it gives me this error
ValueError at /episode/Dragon-Ball-Super/edit/11
The view home.views.edit_comment didn't return an HttpResponse object. It returned None instead.
edit_comment
def edit_comment(request, slug, id):
anime = get_object_or_404(Anime, slug=slug)
comment = get_object_or_404(Comment, id=id)
form = CommentForm(request.POST, instance=comment.user)
if request.method == 'POST' or 'NONE':
if form.is_valid():
form.save()
return redirect('anime_title', slug=slug)
else:
form = CommentForm()
context = {'form': form}
return render(request, 'home/edit-comment.html', context)
urls.py
urlpatterns = [
path('', views.index, name='index'),
re_path(r'^episode/(?P<slug>[\w-]+)/$', views.anime_title, name='anime_title'),
re_path(r'^episode/(?P<slug>[\w-]+)/comment/$', views.add_comment, name='add_comment'),
re_path(r'^episode/(?P<slug>[\w-]+)/edit/(?P<id>\d+)/?', views.edit_comment, name='edit_comment'),
]
link under existing comment
{% if comment.user == request.user.userprofile %}
<h6 class="small comment-meta">
Edit
Delete</h6>
{% endif %}
models.py
class Comment(models.Model):
anime = models.ForeignKey(Anime, on_delete=models.CASCADE)
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
edit-comment.html
{% extends 'base/base.html' %}
{% block head %}
<title>Edit Comment</title>
{% endblock %}
{% block content %}
<h2>Edit Comment</h2>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}

You are handling only the POST request. GET request will be placed the first time when you load the form.
def edit_comment(request, slug, id):
anime = get_object_or_404(Anime, slug=slug)
comment = get_object_or_404(Comment, id=id)
form = CommentForm()
if request.method == 'POST':
form = CommentForm(request.POST, instance=comment.user)
if form.is_valid():
form.save()
return redirect('anime_title', slug=slug)
return render(request, 'home/edit-comment.html', {'form':form})

Related

How to add comments on django

I am trying to add a comment system to my project, all the code looks fine but I am getting this error "ValueError at /
The QuerySet value for an exact lookup must be limited to one result using slicing". I dont know what is wrong but the error might be on the views.py file.
views.py
def imagelist(request):
images = Post.objects.all()
post = get_object_or_404(Post)
comments = Comment.objects.filter(post=images)
if request.method == 'POST':
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid():
contentt = request.POST.get('content')
comment = Comment.objects.create(post=images, user=request.user, content=content)
comment.save()
return HttpResponseRedirect(post.get_absolute_url())
else:
comment_form = CommentForm()
context2 = {
"images": images,
"comments": comments,
"comment_form": comment_form,
}
return render(request, 'imagelist.html', context2)
models.py
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField(max_length=160)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '{}-{}'.format(self.post.title.str(self.user.username))
class Post(models.Model):
text = models.CharField(max_length=200)
posti = models.ImageField(upload_to='media/images', null=True, blank="True")
video = models.FileField(upload_to='media/images', null=True, blank="True")
user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username')
liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked')
updated = models.DateTimeField(auto_now=True)
created =models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.tittle)
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('content',)
You need to pass to the create mathod of the comments a single Post since the corresponding fields is a ForeignKey and you're passing an entire queryset (Post.objects.all())
You need get just the post where the comment should live.
single_post = Post.objects.get(pk=the_post_pk)
comment = Comment.objects.create(post=single_post, user=request.user, content=content)
The problem is that you write:
images = Post.objects.all()
comments = Comment.objects.filter(post=images)
Here images is a set of Post objects, not a single Post object, hence you can not filter on that. But you actually do not need to do this anyway.
Furthermore there is also a small mistake in the __str__ of your Comment model:
class Comment(models.Model):
# …
def __str__(self):
return '{}-{}'.format(self.post.text, self.user.username)
But the view itself looks "odd", since you here write a list of Posts, but if you make a POST request, you will somehow need to know to what post you want to submit the Comment, therefore at least the view that accepts the POST request, will need to know the primary key of the Post to comment on. You can for example encode that in the urls.py:
# appname/urls.py
from django.urls import path
from app import views
urlpatterns = [
path('post/<int:pk>/', views.post_detail, name='post_detail'),
path('post/', views.post_list, name='post_detail')
]
In that view, we can then fetch the item, for example with get_object_or_404, and in case of a POST set the post and user objects in the view:
from django.shortcuts import redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
#login_required
def post_detail(request, pk):
image = get_object_or_404(Post, pk=pk)
if request.method == 'POST':
comment_form = CommentForm(request.POST, request.FILES)
if comment_form.is_valid():
comment_form.instance.user = request.user
comment_form.instance.post = image
comment_form.save()
return redirect(post)
else:
comment_form = CommentForm()
context = {
'post': image,
'comment_form': comment_form,
}
return render(request, 'imagedetail.html', context)
In your template, you can render the comments of the post with:
{{ post }}
{% for comment in post.comment_set.all %}
{{ comment }}
{% endfor %}
<form method="post" action="{% url 'post_detail' pk=post.pk %}">
{% csrf_token %}
{{ comment_form }}
</form>
you can also make a view that renders a list:
#login_required
def post_list(request, pk):
images = Post.objects.prefetch_related('comment_set')
comment_form = CommentForm()
context = {
'image': images,
'comment_form': comment_form,
}
return render(request, 'imagelist.html', context)
in the template for the list, you can render it with:
{% for post in images %}
{{ post }}
{% for comment in post.comment_set.all %}
{{ comment }}
{% endfor %}
<form method="post" action="{% url 'post-detail' pk=post.pk %}">
{% csrf_token %}
{{ comment_form }}
</form>
{% endfor %}
here we thus make a POST request to the post-detail view.
After 4 hours of searching for answers, this is how I achieve it. All I did was add this new view, method, url and html. Hope this helps!
views.py
def imagedetail(request, pk):
post = get_object_or_404(Post, pk=pk)
comments = Comment.objects.filter(post=post)
if request.method == 'POST':
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid():
content = request.POST.get('content')
comment = Comment.objects.create(post=post, user=request.user, content=content)
comment.save()
return HttpResponseRedirect(post.get_absolute_url())
else:
comment_form = CommentForm()
context2 = {
"comments": comments,
"comment_form": comment_form,
}
return render(request, 'imagedetail.html', context2)
models.py (on Post model)
def get_absolute_url(self):
return reverse('imagedetail', args=[self.id])
urls.py (for new view which is imagedetail)
path('imagedetail/<int:pk>/', views.imagedetail, name='imagedetail'),
imagelist.html (to redirect to imagedetail, btw it is a bootstrap button)
<a role="button" class="btn btn-primary" href="{% url 'imagedetail' pk=image.pk %}"></a>
imagedetail.html (it only shows comments)
<form method="post">
{% csrf_token %}
{{comment_form.as_p}}
{% if request.user.is_authenticated %}
<input type="submit" value="Submit" class="btn btn-outline-succes">
{% else %}
<input type="submit" value="Submit" class="btn btn-outline-succes" disabled>
{% endif %}
</form>
<div class="main-comment-section">
{{ comments.count }}
{% for comment in comments %}
<blockquote class="blockquote">
<p class="mb-0">{{ comment.content }}</p>
<footer class="blockquote-footer">by <cite title="Source Title">{{ comment.user }}</cite></footer>
</blockquote>
{% endfor %}
</div>
2 - forms.py icine elave ele:
from django import forms
from .models import Comment
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('name', 'body')
# overriding default form setting and adding bootstrap class
def __init__(self, *args, **kwargs):
super(CommentForm, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs = {'placeholder': 'Enter name', 'class': 'form-control'}
self.fields['body'].widget.attrs = {'placeholder': 'Comment here...', 'class': 'form-control', 'rows': '5'}
3 - models.py elave ele :
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments")
name = models.CharField(max_length=50)
parent = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE)
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 self.name
def get_comments(self):
return Comment.objects.filter(parent=self).filter(active=True)
4 - views.py post bele gorunmelidi :
def post (request,slug):
post = Post.objects.get(slug = slug)
latest = Post.objects.order_by('-timestamp')[:3]
comments = post.comments.filter(active=True)
new_comment = None
comment_form = CommentForm()
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.save()
comment_form = CommentForm()
context = {
'post': post,
'latest': latest,
'comments': comments,
'comment_form': comment_form
}
return render(request, 'post.html', context)
5 - post.html de author altina divider den sonra elave ele :
<hr/>
<h3>Add Comment</h3>
<form method="post" action="">
{% csrf_token %}
{{ comment_form.as_p }}
<button type="submit" class="btn btn-primary">Comment</button>
</form>
{% with comments.count as total_comments %}
<h3 class="mt-5">
{{ total_comments }} comment{{ total_comments|pluralize }}
</h3>
{% endwith %}
{% if not post.comments.all %}
No comments yet
{% else %}
{% for comment in post.get_comments %}
{% include 'comment.html' with comment=comment %}
{% endfor %}
{% endif %}
</div>
6 - admin.py elave ele :
#admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display=('name', 'post', 'created', 'active')
list_filter = ('active', 'created', 'updated')
search_fields = ('name', 'body')
7 - templates de comment.html yarat ve icine elave et :
<div class="border-0 border-start border-2 ps-2" id="{{comment.id}}">
<div class="mt-3">
<strong>{{comment.name}}</strong>
{% if comment.parent.name%} to <strong>{{comment.parent.name}}</strong>{% endif %}
<small class="text-muted">On {{ comment.created.date }}</small>
</div>
<div class="border p-2 rounded">
<p>{{comment.body}}</p>
<button class="btn btn-primary btn-sm" onclick="handleReply({{comment.id}})">Reply</button>
<div id="reply-form-container-{{comment.id}}" style="display:none">
</div>
</div>
{% for comment in comment.get_comments %}
{% include 'comment.html' with comment=comment %}
{% endfor %}
8 - models de post un altina elave ele
def get_comments(self):
return self.comments.filter(parent=None).filter(active=True)

How to add a comment liking system in Django

I'm attempting to allow a user to like comments of a particular post. However when I attempt to solve this, the expected result doesn't occur.
urls.py:
path('likecomment/<int:pk>/', post_views.likecomment,
name='likecomment'),
views.py:
def likecomment(request, pk):
if request.method == 'POST':
comment = get_object_or_404(Comment, pk=pk)
comment.likes += 1
comment.save()
return redirect('home')
comments.html:
{% for com in comments %}
<br>
<br>
<br>
<b>{{ com.user.username }}</b> &nbsp {{ com.body }}
<br>
<p class="text-muted">{{ com.pub_date_pretty }} &nbsp &nbsp
&nbsp &nbsp &nbsp {{ com.likes }} Likes</p>
<a href="javascript:
{document.getElementById('likecomment').submit()}"> Like </a>
<form id="likecomment" method="post" action="{% url 'likecomment'
com.id %}">
{% csrf_token%}
<input type="hidden">
</form>
<br>
{% endfor %}
Home view:
#login_required(login_url='/login')
def home(request):
posts = Post.objects.all()
return render(request, 'posts/home.html', {'posts': posts})
Render comments:
def comment(request, pk):
form = CommentForm()
comments = Comment.objects.filter(post__pk=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = Comment()
comment.body = form.cleaned_data['body']
comment.user = request.user
comment.post = Post.objects.get(pk=pk)
comment.save()
return redirect('home')
else:
return render(request, 'posts/comments.html', {'error': 'Please submit valid data'})
else:
return render(request, 'posts/comments.html', {'form': form, 'comments': comments})
Like comments view:
def likecomment(request, pk):
if request.method == 'POST':
comment = get_object_or_404(Comment, pk=pk)
comment.likes += 1
comment.save()
return redirect('home')
The like occurs sometimes, however not for the right comment. The functionality isn't working correctly.
Image 1:
Image 2:
You have multiple HTML form elements with the same id (likecomment). Javascript has no way of knowing which one you meant to submit. Try appending a unique identifier, such as {{ forloop.counter }} to the id value, such as:
<form id="likecomment-{{ forloop.counter }}" ...
and
document.getElementById('likecomment-{{ forloop.counter }}').submit()

Editing view for combined form and inline_formset

I have been trying to create an editing view that allows me manage both parent and child models using an inline formset based in the documentation here
From what I can appreciate the formset doesn't validate. I did try and change it so that instead of validating the entire formset it iterated through each individual form in the formset and validated them individually. This did allow me to add items to the formset but not delete them.
At the moment the code results in "didn't return an HttpResponse object. It returned None instead" value error as the redirect is in the If valid statement and so if that does not result in true there is no other redirect to fall back on.
Models
class Shoppinglist(models.Model):
name = models.CharField(max_length=50)
description = models.TextField(max_length=2000)
created = models.DateField(auto_now_add=True)
created_by = models.ForeignKey(User, related_name='lists', on_delete=models.CASCADE)
last_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Item(models.Model):
name = models.CharField(max_length=80, unique=True)
amount = models.IntegerField(default=1)
shoppinglist = models.ForeignKey(Shoppinglist, on_delete=models.CASCADE)
def __str__(self):
return self.name
URL
urlpatterns = [
url(r'^shoppinglists/(?P<pk>\d+)/edit/$', views.shoppinglist_edit, name='shoppinglist_edit'),
]
View
def shoppinglist_edit(request, pk):
try:
shoppinglist = Shoppinglist.objects.get(pk=pk)
except ShoppingList.DoesNotExist:
raise Http404
ItemInlineFormset = inlineformset_factory(Shoppinglist, Item, extra=1, fields=('name', 'amount'))
if request.method == "POST":
form = ShoppinglistForm(request.POST, instance=shoppinglist)
formset = ItemInlineFormset(request.POST, instance=shoppinglist)
if formset.is_valid() and form.is_valid():
form.save()
formset.save()
return redirect('packlist_list', pk=pk)
else:
form = ShoppinglistForm(instance=shoppinglist)
formset = ItemInlineFormset(instance=shoppinglist)
context = {
'shoppinglist' : shoppinglist,
'listform': form,
'formset': formset,
}
return render(request, 'edit_list_with_items.html', context)
Template
{% block content %}
<form method="post">
{% csrf_token %}
<label>List Name</label>
{{ listform.name }}
{% if listform.first_name.errors %}
{% for error in listform.first_name.errors %}
{{ error|escape }}
{% endfor %}
{% endif %}
<label>Description</label>
{{ listform.description }}
{% if listform.description.errors %}
{% for error in listform.description.errors %}
{{ error|escape }}
{% endfor %}
{% endif %}
{{ formset.management_form }}
{% for form in formset %}
<div class="item-formset">
{{ form.amount }}
{% if form.amount.errors %}
{% for error in form.amount.errors %}
{{ error|escape }}
{% endfor %}
{% endif %}
{{ form.name }}
{% if form.name.errors %}
{% for error in form.name.errors %}
{{ error|escape }}
{% endfor %}
{% endif %}
</div>
{% endfor %}
{% if formset.non_form_errors %}
{% for error in formset.non_form_errors %}
{{ error|escape }}
{% endfor %}
{% endif %}
<div class="row spacer">
<button type="submit" class="btn btn-block btn-primary">Create</button>
</div>
</form>
{% endblock %}
{% block extra_js %}
<script>
$('.item-formset').formset({
addText: 'add item',
deleteText: 'remove'
});
</script>
{% endblock %}
Please note I am using this jquery plugin in the template.
https://github.com/elo80ka/django-dynamic-formset
it is probably either your form or formset is invalid, and you dont use else statement to handle that.
so in your views.py:
if request.method == "POST":
form = ShoppinglistForm(request.POST, instance=shoppinglist)
formset = ItemInlineFormset(request.POST, instance=shoppinglist)
if formset.is_valid() and form.is_valid():
form.save()
formset.save()
return redirect('packlist_list', pk=pk)
else:
# either your form or formset is invalid, so this code will render it again.
context = {
'shoppinglist' : shoppinglist,
'listform': form,
'formset': formset,
}
return render(request, 'edit_list_with_items.html', context)
else:
form = ShoppinglistForm(instance=shoppinglist)
formset = ItemInlineFormset(instance=shoppinglist)
context = {
'shoppinglist' : shoppinglist,
'listform': form,
'formset': formset,
}
return render(request, 'edit_list_with_items.html', context)
or you can simplify it with this:
if request.method == "POST":
form = ShoppinglistForm(request.POST, instance=shoppinglist)
formset = ItemInlineFormset(request.POST, instance=shoppinglist)
if formset.is_valid() and form.is_valid():
form.save()
formset.save()
return redirect('packlist_list', pk=pk)
else:
form = ShoppinglistForm(instance=shoppinglist)
formset = ItemInlineFormset(instance=shoppinglist)
# notice the indentation
context = {
'shoppinglist' : shoppinglist,
'listform': form,
'formset': formset,
}
return render(request, 'edit_list_with_items.html', context)
Mentioned error coming because you write this return render(request, 'edit_list_with_items.html', context) inside else block.
instead of this:
else:
form = ShoppinglistForm(instance=shoppinglist)
formset = ItemInlineFormset(instance=shoppinglist)
context = {
'
}
return render(request, 'edit_list_with_items.html', context)
Do this:
else:
form = ShoppinglistForm(instance=shoppinglist)
formset = ItemInlineFormset(instance=shoppinglist)
context = {
}
return render(request, 'edit_list_with_items.html', context)

can not upload the images

why I can not upload the images??
The urls.py:
see the
url(r'^things,,,
from django.conf.urls import include, url
from django.contrib import admin
from collection import views
from django.views.generic import TemplateView
from django.views.generic import (TemplateView,RedirectView,)
from collection.backends import MyRegistrationView
from django.contrib.sitemaps.views import sitemap
from collection.sitemap import (
ThingSitemap,
StaticSitemap,
HomepageSitemap,
)
sitemaps = {
'things': ThingSitemap,
'static': StaticSitemap,
'homepage': HomepageSitemap,
}
from django.contrib.auth.views import (
password_reset,
password_reset_done,
password_reset_confirm,
password_reset_complete,
)
urlpatterns = [
url(r'^$', views.index, name='home'),
url(r'^about/$',TemplateView.as_view(template_name='about.html'),name='about'),
url(r'^contact/$',views.contact, name='contact'),
url(r'^things/$', RedirectView.as_view(pattern_name='browse', permanent=True)),
url(r'^things/(?P<slug>[-\w]+)/$', views.thing_detail,name='thing_detail'),
url(r'^things/(?P<slug>[-\w]+)/edit/$', views.edit_thing,name='edit_thing'),
url(r'^things/(?P<slug>[-\w]+)/edit/images/$', views.edit_thing_uploads,name='edit_thing_uploads'),
url(r'^browse/$', RedirectView.as_view(pattern_name='browse', permanent=True)),
url(r'^browse/name/$',views.browse_by_name, name='browse'),
url(r'^browse/name/(?P<initial>[-\w]+)/$',views.browse_by_name, name='browse_by_name'),
url(r'^accounts/password/reset/$', password_reset,{'template_name':'registration/password_reset_form.html'},name="password_reset"),
url(r'^accounts/password/reset/done/$', password_reset_done,{'template_name':'registration/password_reset_done.html'},name="password_reset_done"),
url(r'^accounts/password/reset/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', password_reset_confirm,{'template_name':'registration/password_reset_confirm.html'},name="password_reset_confirm"),
url(r'^accounts/password/done/$', password_reset_complete,{'template_name':'registration/password_reset_complete.html'},name="password_reset_complete"),
url(r'^accounts/register/$',MyRegistrationView.as_view(),name='registration_register'),
url(r'^accounts/create_thing/$',views.create_thing,name='registration_register'),
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^sitemap\.xml$', sitemap, {'sitemaps':sitemaps},name='django.contrib.sitemaps.views.sitemap'),
url(r'^admin/', include(admin.site.urls)),
]
from django.conf import settings
if settings.DEBUG:
urlpatterns += [
url(r'^media/(?P<path>.*)$','django.views.static.serve',{'document_root': settings.MEDIA_ROOT,}),
]
the views.py:
See the def edit_thing_uploads
from django.shortcuts import render,redirect
from django.contrib.auth.decorators import login_required
from django.http import Http404
from collection.forms import ThingForm,ContactForm,ThingUploadForm
from collection.models import Thing,Upload
from django.template.loader import get_template
from django.core.mail import EmailMessage
from django.template import Context
def index(request):
things = Thing.objects.all()
return render(request, 'index.html', {
'things':things,
})
def thing_detail(request, slug):
thing = Thing.objects.get(slug=slug)
social_accounts = thing.social_accounts.all()
uploads = thing.uploads.all()
return render(request, 'things/thing_detail.html',{
'thing':thing,
'social_accounts': social_accounts,
'uploads': uploads,
})
#login_required
def edit_thing(request, slug):
thing = Thing.objects.get(slug=slug)
if thing.user != request.user:
raise Http404
form_class = ThingForm
if request.method == 'POST':
form = form_class(data=request.POST, instance=thing)
if form.is_valid():
form.save()
return redirect('thing_detail', slug=thing.slug)
else:
form = form_class(instance=thing)
return render(request, 'things/edit_thing.html',{'thing':thing,'form':form,})
#login_required
def edit_thing_uploads(request, slug):
thing = Thing.objects.get(slug=slug)
if thing.user != request.user:
raise Http404
form_class = ThingUploadForm
if request.method == 'POST':
form = form_class(data=request.POST,files=request.FILES, instance=thing)
if form.is_valid():
Upload.objects.create(
image=form.cleaned_data['image'],
thing=thing,
)
return redirect('edit_thing_uploads', slug=thing.slug)
else:
form = form_class(instance=thing)
uploads = thing.uploads.all()
return render(request, 'things/edit_thing_uploads.html', {
'thing': thing,
'form': form,
'uploads': uploads,
})
def create_thing(request):
form_class = ThingForm
if request.method == 'POST':
form = form_class(request.POST)
if form.is_valid():
thing = form.save(commit=False)
thing.user = request.user
thing.slug = slugify(thing.name)
thing.save()
return redirect('thing_detail', slug=thing.slug)
else:
form = form_class()
return render(request, 'things/create_thing.html', {'form':form,})
def browse_by_name(request, initial=None):
if initial:
things = Thing.objects.filter(name__istartswith=initial)
things = things.order_by('name')
else:
things = Thing.objects.all().order_by('name')
return render(request, 'search/search.html', {'things':things,'initial':initial,})
def contact(request):
form_class = ContactForm
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
contact_name = form.cleaned_data['contact_name']
contact_email = form.cleaned_data['contact_email']
form_content = form.cleaned_data['content']
template = get_template('contact_template.txt')
context = Context({
'contact_name':contact_name,
'contact_email':contact_email,
'form_content':form_content,
})
content = template.render(context)
email = EmailMessage(
'New contact form submission',content,
'Your website <hi#weddinglovely.com>',['fnt437#gmail.com'],
headers = {'Reply-To':contact_email }
)
email.send()
return redirect('contact')
return render(request, 'contact.html', {'form': form_class, })
The forms.py:
from django import forms
class ThingForm(ModelForm):
class Meta:
model = Thing
fields = ('name','description',)
class ContactForm(forms.Form):
contact_name = forms.CharField(required=True)
contact_email = forms.EmailField(required=True)
content = forms.CharField(
required=True,
widget=forms.Textarea
)
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.fields['contact_name'].label = "Your name:"
self.fields['contact_email'].label = "Your email:"
self.fields['content'].label = "What do you want to say?"
class ThingUploadForm(ModelForm):
class Meta:
model = Upload
fields = ('image',)
the edit_thing.html:
{% extends 'layouts/base.html' %}
{% block title %}
Edit {{ thing.name }} - {{ block.super }}
{% endblock %}
{% block content %}
<h1>Edit "{{ thing.name }}"</h1>
Edit images
<form role="form" action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
the edit_thing_uploads.html:
{% extends 'layouts/base.html' %}
{% block title %}
Edit {{ thing.name }}'s Images - {{ block.super }}
{% endblock %}
{% block content %}
<h1>Edit {{ thing.name }}'s Images</h1>
<h2>Uploaded images</h2>
{% for upload in uploads %}
<img src="{{ uploads.image.url }}" alt="" />
{% endfor %}
<h2>Uploads a new image</h2>
<form role="form" action="" method="post" enctype="multipart/form\-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="submit" />
</form>
{% endblock %}
the diirectory tree:
when I click in http://127.0.0.1:8000/things/another-things/edit/ is ok
however when I click the Edit images link to submit upload images it said no file has been choice?? I can not upload the images
You have to check the file permissions of
edit_thing_uploads.html
, make sure the file is accessible. because the path has been correct. and Django can't see it.
I got to know why ,,because I typos <form role="form" action="" method="post" enctype="multipart/form-data"> ---> <form role="form" action="" method="post" enctype="multipart/form\-data"> in edit_thing_uploads.html

Take In Input from User and Display the same input on the same page

Hi i am trying to create a post form in django where the user creates a post and the post is displayed back to them on the same page so far i have been unsuccessful. My articles display on the page but the form to post articles doesnt only the submit button shows.
views.py
def articles(request):
args = {}
args.update(csrf(request))
args ['posts'] = post.objects.filter(user = request.user)
args ['full_name'] = User.objects.get(username = request.user.username)
return render_to_response('articles.html', args)
def article(request, post_id=1):
return render(request, 'article.html',
{'post': post.objects.get(id=post_id) })
def create(request):
if request.POST:
form = PostForm(request.POST, request.FILES)
if form.is_valid():
a = form.save(commit=False)
a.user = User.objects.get(username = request.user.username)
a.save()
messages.add_message(request, messages.SUCCESS, "You Article was added")
return HttpResponseRedirect('/posts/all')
else:
form = PostForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('articles.html', args)
articles.html
<form action="/posts/create/" method="post" enctype="multipart/form-data">{% csrf_token %}
<ul>
{{form.as_ul}}
</ul>
<input type="submit" name="submit" value="Create Article">
</form>
{% if posts.count > 0 %}
{% for post in posts %}
<div>
<h2>{{full_name}}</h2>
<p>{{ post.body|lower|truncatewords:50 }}</p>
<p>{{post.likes}} people liked this article</a></p>
</div>
{% endfor %}
{% else %}
<p>None to show!</p>
{% endif %}
{% endblock %}
urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^create/$', 'posts.views.articles'),
url(r'^get/(?P<post_id>\d+)/$', 'posts.views.article'),
url(r'^create/$', 'posts.views.create'),
url(r'^like/(?P<post_id>\d+)/$', 'posts.views.like_article'),
url(r'^article/(?P<post_id>\d+)/$', 'posts.views.add_comment'),
)
First off you aren't passing the form to the template in articles(). You need to have something along the lines of:
args['form'] = YourForm()
In your first view function. Also, in your create view you do this:
a.user = User.objects.get(username = request.user.username)
Which does an unnecessary database lookup of the user again, you can just do this to be clearer and faster:
a.user = request.user

Categories

Resources