Can't upload pictures in django forms - python

From the admin level in Django, photos can be uploaded, but from the form on the website it is impossible.
The only picture that can be uploaded is the default picture I set in the models file.
If I delete the default picture from models and upload the photo from the form, an error pops up.
Here are some of my files:
models.py
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
publish_date = models.DateTimeField(blank=True, null=True)
image = models.ImageField(upload_to='images/', blank=True, null=True, default='images/user.jpg')
def publish(self):
self.publish_date = timezone.now()
self.save()
def __str__(self):
return self.title
forms.py:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'text', 'image']
views.py:
class Image(TemplateView):
form = PostForm
template_name = 'blog/image.html'
def post(self, request, *args, **kwargs):
form = PostForm(request.POST, request.FILES)
if form.is_valid():
obj = form.save()
return HttpResponseRedirect(reverse_lazy('image_display', kwargs={'pk': obj.id}))
context = self.get_context_data(form=form)
return self.render_to_response(context)
def get(self, request, *args, **kwargs):
return self.post(request, *args, **kwargs)
class ImageDisplay(DetailView):
model = Post
template_name = 'blog/image_display.html'
context_object_name = 'image'
def post_list(request):
posts = Post.objects.filter(publish_date__lte=timezone.now()).order_by('publish_date')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
def error_404_view(request, exception):
data = {"name": "Blog for programmers"}
return render(request, 'blog/404.html', data)
def post_new(request):
if request.method == "POST":
form = forms.PostForm(request.POST, request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.publish_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
post_detail.html:
{% block content %}
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<h2>{{ post.title }}</h2>
<img src="{{ post.image.url }}" alt="Image" width="250">
<p>{{ post.text|linebreaksbr }}</p>
</div>
post_list.html:
{% block content %}
{% for post in posts %}
<div class="post">
<div class="data">
<p>Published: {{ post.publish_date }}</p>
</div>
<h2>{{ post.title }}</h2>
<img src="{{ post.image.url }}" alt="Image" width="100">
<em>{{ post.text|linebreaksbr }}</em>
</div>
{% endfor %}

Related

My comments are not being displayed in a django blog

I am trying to add a comment section to add a comment section to my blog detail using django but when i run my server i get no error in the development server and the comments are not being displayed. I added the comments from my admin site.
The snippet of my code is below.
views.py
from .models import Post
from django.utils import timezone
from .forms import PostForm, CommentsForm
from django.contrib.auth.decorators import user_passes_test
# Create your views here.
def home(request):
return render (request, 'blogapp/home.html')
def blog_list(request):
post = Post.objects.order_by('-published_date')
context = {
'posts':post
}
return render(request, 'blogapp/blog_list.html', context)
def blog_detail(request, pk=None):
detail = Post.objects.get(pk=pk)
context = {
'detail': detail
}
return render(request, 'blogapp/blog_detail.html', context)
def add_post(request, pk=None):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid:
body = form.save(commit=False)
body.published_date = timezone.now()
body.save()
return redirect('blog_list')
form = PostForm()
else:
form = PostForm()
context = {
'form': form
}
return render(request, 'blogapp/add_post.html', context)
def add_comments(request, pk=None):
if request.method == "POST":
form = CommentsForm(request.POST)
if form.is_valid:
comment = form.save(commit=False)
comment.date_added = timezone.now()
comment.save()
return redirect('blog_detail')
form = CommentsForm()
else:
form = CommentsForm()
context = {
'form': form
}
return render(request, 'blogapp/add_comments.html', context)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="homepage"),
path('blog/', views.blog_list, name="blog_list"),
path('blog/post/<int:pk>/', views.blog_detail, name="blog_detail"),
path('blog/add_post/', views.add_post, name="add_post"),
path('blog/add_comments/', views.add_comments, name="add_comments"),
]
forms.py
from django import forms
from .models import Post, Comments
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('author', 'title', 'post_description', 'image', 'image_description', 'body',)
class CommentsForm(forms.ModelForm):
class Meta:
model = Comments
fields = ('post', 'name', 'body',)
models.py
from django.db import models
from django.utils import timezone
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.user', on_delete=models.CASCADE)
title = models.CharField(max_length=300)
body = models.TextField()
post_description = models.CharField(max_length=500, blank=True, null=True)
image = models.ImageField(blank=True, null=True, upload_to="image/")
image_description = models.CharField(max_length=500, blank=True, null=True)
published_date = models.DateTimeField(default=timezone.now, blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
class Comments(models.Model):
post = models.ForeignKey('Post', related_name="comments", on_delete=models.CASCADE)
body = models.TextField()
name = models.CharField(max_length=300)
date_added = models.DateTimeField(default=timezone.now, blank=True, null=True)
def __str__(self):
return '%s - %s' % (self.post.title, self.name)
blog_detail.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<article>
<strong>
<h1><b>{{ detail.title }}</b></h1>
</strong>
<h3>POST AUTHOR: {{ detail.author }}</h3>
<h4><i>{{ detail.post_description }}</i></h4>
<h4>PUBLISHED:{{ detail.published_date }}</h4>
<p>
<hr>
{% if detail.image %}
<center>
<br>
<img src="{{ detail.image.url }}" width="1000" height="700">
<br><br>
<i>IMAGE DESCRIPTION: {{ detail.image_description }}</i>
</center>
{% endif %}
<hr>
<br><br><br>
{{ detail.body|linebreaksbr }}
</p>
<hr class="solid">
<h2>COMMENTS ...</h2>Add One
{% for comment in post.comments.all %}
<strong>
{{ comment.name }}-{{ comment.date_added }}
</strong>
{{ comment.body }}
{% endfor %}
</article>
{% endblock %}
add_comments.html
{% extends 'base.html' %}
{% block content %}
<article>
{% if user.is_authenticated %}
<h1>CREATE NEW BLOG POST.</h1>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">ADD COMMENT</button>
<input type="hidden" name="next" value="{% url 'blog_detail' pk=post.pk %}"/>
</form>
{% else %}
<h2>Login HERE to add comments.</h2>
{% endif %}
</article>
{% endblock %}
in your template you use
{% for comment in post.comments.all %}
but in template context there is no post variable
you should use {% for comment in detail.comments.all %}

Trying to make comments editable in django

I have a blog app and the comments can be added on the detail page of the blog, im having trouble implementing a way for users to edit comments they have already made. I have it so a url shows up on comments where only the person signed in can click the link to edit their comments on the post however im getting this error when I try to load the detail page now. Any help would be appreciated thank you
Reverse for 'update_comment' with arguments '(None,)' not found. 1 pattern(s) tried: ['posts(?P[0-9]+)/(?P[0-9]+)/(?P[0-9]+)/(?P[-a-zA-Z0-9_]+)/(?P<comment_id>[0-9]+)/update$']
edit:
I corrected my detail.html file and now im getting this error:
update_comment() missing 1 required positional argument: 'id'
models.py
from django.db.models.signals import pre_save
from Date.utils import unique_slug_generator
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from django.conf import settings
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,
self).get_queryset()\
.filter(status='cleared')
class Post(models.Model):
STATUS_CHOICES = (
('cleared','Cleared'),('UnderReview','Being Reviewed'),('banned','Banned'),)
title = models.CharField(max_length = 300)
slug = models.SlugField(max_length = 300, unique_for_date='publish')
author = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='forum_posts',null=True)
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=12,choices=STATUS_CHOICES,default='cleared')
objects = models.Manager()
cleared = PublishedManager()
class Meta:
ordering =('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('posts:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug])
def slug_generator(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = unique_slug_generator(instance)
pre_save.connect(slug_generator, sender=Post)
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.SET_NULL, related_name='comments',null=True)
name = models.ForeignKey(User, on_delete=models.SET_NULL,null=True)
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 f'Comment by {self.name} on {self.post}'
urls.py
from . import views
from django.urls import path, include
from django.contrib.auth import views as auth_views
from .views import PostListView, PostCreateView,PostUpdateView
app_name = 'posts'
urlpatterns = [
path('', views.PostListView.as_view(), name='post_list'),
#path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.PostDetailView.as_view(),name='post_detail'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.post_detail,name='post_detail'),
path('post/new/',PostCreateView.as_view(), name='post-create'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/update/',PostUpdateView.as_view(), name='post-update'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/<int:comment_id>/update',views.update_comment, name='update_comment'),
]
views.py
from django.shortcuts import render, get_object_or_404
from .models import Post, Comment
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import ListView, CreateView, UpdateView
from .forms import CommentForm, PostForm
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib import messages
from django.urls import reverse
class PostListView(ListView):
queryset = Post.cleared.all()
context_object_name = 'posts'
paginate_by = 3
template_name = 'posts/post/list.html'
"""class PostDetailView(DetailView, Post):
queryset = Post.cleared.all()
model = Post
fields = ['title','body']
template_name = 'posts/post/detail.html'
form_class = CommentForm
def get_object(self, *args, **kwargs):
return get_object_or_404(
Post,
publish__year=self.kwargs['year'],
publish__month=self.kwargs['month'],
publish__day=self.kwargs['day'],
slug=self.kwargs['post'],
)
return post
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['comment'] = Comment.objects.all()
context['comment_form'] = CommentForm()
return context
def post(self, request, *args, **kwargs):
post = get_object_or_404(Post , slug=post, status='cleared',publish__year=year,publish__month=month,publish__day=day)
comment_form = self.form_class(request.POST)
if comment_form.is_valid():
return HttpResponseRedirect( post.get_absolute_url() )
return render(request, self.template_name, {'comment_form': comment_form})"""
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
fields = ['title','body']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin, UpdateView):
model = Post
fields = ['title','body']
template_name = 'posts/post-update.html'
def get_object(self, *args, **kwargs):
return get_object_or_404(
Post,
publish__year=self.kwargs['year'],
publish__month=self.kwargs['month'],
publish__day=self.kwargs['day'],
slug=self.kwargs['post'],
author=self.request.user
)
def get_success_url(self):
return reverse('posts:post_detail',
args=[
self.object.publish.year,
self.object.publish.month,
self.object.publish.day,
self.object.slug
]
)
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def post_detail(request, year, month, day, post, comment_id = None):
post = get_object_or_404(Post , slug=post, status='cleared',publish__year=year,publish__month=month,publish__day=day)
comments = post.comments.filter(active=True)
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
comment_form.instance.post = post
comment_form.instance.name = request.user
comment_form.save()
return HttpResponseRedirect( post.get_absolute_url() )
else:
comment_form = CommentForm()
return render(request,'posts/post/detail.html', {'post':post , 'comments': comments,'comment_form': comment_form, 'comment_id':comment_id })
def update_comment(request, year, month, day, post,id, comment_id = None):
post = get_object_or_404(Post , slug=post, status='cleared',publish__year=year,publish__month=month,publish__day=day, id=id)
comments = post.comments.filter(active=True)
comment_form = CommentForm
if comment_id:
comment_form = CommentForm(instance=Comment.objects.get(id=comment_id), data=request.POST)
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
comment_form.instance.post = post
comment_form.instance.name = request.user
comment_form.save()
return HttpResponseRedirect( post.get_absolute_url() )
else:
comment_form = CommentForm()
return render(request,'posts/update_comment.html', {'post':post , 'comments': comments,'comment_form': comment_form, 'comment_id':comment_id })
forms.py
from django import forms
from .models import Comment,Post
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('body',)
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields =('title','body',)
detail.html
{% extends "Main/Base.html" %}
{% block title %}{{ post.title }}{% endblock %}
{% block content %}
<h1>{{ post.title }}<h1>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|linebreaks }}
{% if user.is_authenticated and user == post.author %}
<h3>Update your post</h3>
{% endif %}
{% with comments.count as total_comments %}
<h2>
{{ total_comments }} comment{{ total_comments|pluralize }}
</h2>
{% endwith %}
{% for comment in comments %}
<div class="comment">
<p class="info">
Comment by {{comment.name }}
{{ comment.created }}
</p>
{{ comment.body|linebreaks}}
{% if user.is_authenticated and user == comment.name %}
<p>edit</p>
{% endif %}
</div>
{% empty %}
<p>There are no comments yet.</p>
{% endfor %}
{% if new_comment %}
<h2>Your comment has been added.</h2>
{% else %}
{% if request.user.is_authenticated %}
<h2>Add a new comment</h2>
<form method="post">
{{ comment_form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Add comment"></p>
</form>
{% else %}
<h3>You need to be logged in to make a comment please log-in if you dont have an account register here now</h3>
{% endif %}
{% endif %}
{% endblock %}
update_comment.html
{% extends "Main/Base.html" %}
{% block content %}
<form method="POST" action="{% url 'posts:update_comment' post.publish.year post.publish.month post.publish.day post.slug comment.id %}">
{{ comment_form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Add comment"></p>
</form>
{% endblock %}
Ive been trying a bunch of this to try and make it work so my code is a bit of a mess, there aren't many tutorials on making editable comments with django.

Reverse for 'detail' with keyword arguments '{'id': 5}' not found. 1 pattern(s) tried: ['posts/(?P<slug>[\\w-]+)/$']

I'm super stuck with NoReverseMatch at /posts/ error. Maybe I am overlooking something small or maybe this issue is much bigger than where I am digging.
http://imgur.com/nlyMi9V
Error message when models.py is like this:
def get_absolute_url(self):
#return reverse("detail", kwargs={ "slug": self.slug })
return reverse("posts:detail", kwargs={ "slug": self.slug })
http://imgur.com/a/RilrB
Error message when models.py is like this:
def get_absolute_url(self):
return reverse("detail", kwargs={ "slug": self.slug })
#return reverse("posts:detail", kwargs={ "slug": self.slug })
models.py
#from _future_ import __unicode__literals
from django.db import models
from django.core.urlresolvers import reverse
from django.db.models.signals import pre_save
from django.utils.text import slugify
# Create your models here.
# MVC Models Views Controller
def upload_location(instance, filename):
# filebase, extension = filename.spilt(".")
# return "%s/%s.%s" %(instance.id, instance.id, filename)
return "%s/%s" %(instance.id, filename)
class Post(models.Model):
title = models.CharField(max_length=120)
slug = models.SlugField(unique=True)
image = models.ImageField(upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="height_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
content = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def __unicode__(self):
return self.title
def __str__(self):
return self.title
def get_absolute_url(self):
#return reverse("detail", kwargs={ "slug": self.slug })
return reverse("posts:detail", kwargs={ "slug": self.slug })
class Meta:
ordering = ["-timestamp", "-updated"]
def create_slug(instance, new_slug=None):
slug = slugify(instance.title)
if new_slug is not None:
slug = new_slug
qs = Post.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, sender=Post)
views.py
from django.contrib import messages
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, redirect
from .forms import PostForm
# Create your views here.
from .models import Post
def post_create(request):
form = PostForm(request.POST or None, request.FILES or None,)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
# message success
messages.success(request, "Successfully Created!")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"form": form,
}
return render(request, "post_form.html", context)
def post_detail(request, slug=None):
#instant = Post.objects.get(id=0)
instance = get_object_or_404(Post, slug=slug)
context = {
"title": instance.title,
"instance": instance,
}
return render(request, "post_detail.html", context)
def post_list(request):
queryset_list = Post.objects.all() #.order_by("-timestamp")
paginator = Paginator(queryset_list, 5) # Show 5 contacts per page
page_request_var = "page"
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
queryset = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
queryset = paginator.page(paginator.num_pages)
context = {
"object_list": queryset,
"title": "List",
"page_request_var": page_request_var
}
return render(request, "post_list.html", context)
#return HttpResponse("<h1>List</h1>")
def post_update(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
form = PostForm(request.POST or None, request.FILES or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
# message success
messages.success(request, "<a href='#'>Item</a> Saved", extra_tags='html_safe')
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"title": instance.title,
"instance": instance,
"form":form,
}
return render(request, "post_form.html", context)
def post_delete(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
instance.delete()
messages.success(request, "Successfully deleted!")
return redirect("posts:list")
urls.py
from django.conf.urls import url
from django.contrib import admin
from . import views
# from .views import (
# post_list,
# post_create,
# post_detail,
# post_update,
# post_delete,
# )
# video: https://www.youtube.com/watch?annotation_id=annotation_3160187747&feature=iv&index=14&list=PLEsfXFp6DpzQFqfCur9CJ4QnKQTVXUsRy&src_vid=nw3R2TXlkwY&v=1KuyH8JVn6A
# shows a different solution here for version 1.10
urlpatterns = [
#url(r'^$', views.post_home),
# url(r'^$', views.post_list, name='list'),
# url(r'^create/', views.post_create), #name='create'
# url(r'^(?P<slug>[\w-]+)/', views.post_detail, name='detail'),
# url(r'^(?P<slug>[\w-]+)/edit/', views.post_update, name='update'),
# url(r'^(?P<slug>[\w-]+)/delete/', views.post_delete),
url(r'^$', views.post_list, name='list'),
url(r'^create/$', views.post_create, name='create'),
url(r'^(?P<slug>[\w-]+)/$', views.post_detail, name='detail'),
url(r'^(?P<slug>[\w-]+)/edit/$', views.post_update, name='update'),
url(r'^(?P<slug>[\w-]+)/delete/$', views.post_delete),
# url(r'^$', posts.views.post_home),
# url(r'^create/', home_create),
# url(r'^list/', home_list),
# url(r'^detail/', home_detail),
# url(r'^update/', home_update),
# url(r'^delete/', home_delete),
# url(r'^posts/$', "<appname>.views.<function_name>"),
]
post_list.py
{% extends "base.html" %}
{% block head_title %}
{{ instance.title }} | {{ block.super }}
{% endblock head_title %}
{% block content %}
<div class="row justify-content-md-center">
<div class='col-md-8'>
<h1>{{title}}</h1>
</div>
{% for obj in object_list %}
<div class='col-md-8 pt-3'>
<div class="card" style="min-width: 20rem;">
{% if obj.image %}
<img src="{{ obj.image.url }}" class="card-img-top">
{% endif %}
<div class="card-body">
<h4 class="card-title">
<a href='{{ obj.get_absolute_url }}'>{{ obj.title }}</a>
<small>{{ obj.timestamp|timesince }} ago</small>
</h4>
<p class="card-text">{{ obj.content|linebreaks|truncatechars:120 }}</p>
<p class="card-text">{{ obj.updated }}</p>
<p class="card-text">{{ obj.id }}</p>
<!-- <a href='{% url "posts:detail" id=obj.id %}'>{{ obj.title }}</a><br/> -->
View
</div>
</div>
</div>
{% endfor %}
<div class='col-md-8'>
<div class="pagination">
<span class="step-links">
{% if object_list.has_previous %}
previous
{% endif %}
<span class="current">
Page {{ object_list.number }} of {{ object_list.paginator.num_pages }}.
</span>
{% if object_list.has_next %}
next
{% endif %}
</span>
</div>
</div>
</div>
{% endblock content %}
The error is coming from this line
<!-- <a href='{% url "posts:detail" id=obj.id %}'>{{ obj.title }}</a><br/> -->
<!-- is an html comment, so Django still tries to reverse the url when it renders the template.
You can either remove the line entirely, change it to a Django comment {# ... #}, or change it to use the slug instead of id.

HiddenInput ForeignKey Django

I can't seem to figure out why its not letting me display my ForeignKey fields that I'm passing to the forms on my templates. I researched all over but couldn't figure out an answer with explanation that works. Anyone have any ideas what I'm doing wrong?
forms.py
class MeetingForm(forms.ModelForm):
meeting_date = forms.ModelChoiceField(widget=forms.HiddenInput(), queryset=Date.objects.all())
person = forms.ModelChoiceField(widget=forms.HiddenInput(), queryset=Person.objects.all())
class Meta:
model = MeetingAttendance
fields = ['meeting_date', 'person', 'attended',]
Models.py
class MeetingAttendance(models.Model):
meeting_date = models.ForeignKey('Date', on_delete=models.CASCADE)
person = models.ForeignKey('Person', on_delete=models.CASCADE)
attended = models.BooleanField()
def __str__(self):
return "%s - %s" % (self.person, self.meeting_date)
Views.py
def date_detail(request, slug):
people = Person.objects.all()
detail = Date.objects.get(slug=slug)
MeetingFormSet = formset_factory(MeetingForm, extra=len(people)-2, max_num=len(people))
if request.method == "POST":
form = MeetingFormSet(request.POST)
if form.is_valid():
formset = form.save(commit=True)
formset.save()
return redirect('date_detail', slug=slug)
else:
initial_data = [{'person': person, 'meeting_date': detail} for person in people]
form = MeetingFormSet(initial=initial_data)
context = {
'form': form,
'people': people,
}
return render(request, 'date_detail.html', context)
Template
<div class="directory panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Meeting Details</h3>
</div><!-- end paneil-heading -->
<div class="panel-body">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
</div>
</div>

uploading files from form

I have a ModelForm that I'm using to upload files with and it doesn't want to work. I had it working yesterday but I'm not sure what was done to make it stop all of a sudden.
Here's my ModelForm:
class UserForm(forms.ModelForm):
description = forms.CharField(max_length=500, widget=forms.Textarea(attrs={'cols': 80, 'rows': 5}))
class Meta:
model = UserProfile
exclude = {'user', 'description'}
Here's the Model:
def get_image_path(instance, filename):
return os.path.join('images', str(instance.id), filename)
def get_video_path(instance, filename):
return os.path.join('videos', str(instance.id), filename)
def get_randfile_path(instance, filename):
return os.path.join('randfile', str(instance.id), filename)
class UserProfile(models.Model):
user = models.OneToOneField(User)
description = models.CharField(max_length=500, blank=True, null=True)
photo = models.FileField(upload_to=get_image_path, blank=True, null=True)
video = models.FileField(upload_to=get_video_path, blank=True, null=True)
rand_file = models.FileField(upload_to=get_randfile_path, blank=True, null=True)
def photo_name(self):
return os.path.basename(self.photo.name)
def video_name(self):
return os.path.basename(self.video.name)
Here's the View:
def detail(request, user_id):
user = get_object_or_404(User, pk=user_id)
userprofile = get_object_or_404(UserProfile, user=user)
year = datetime.now().year
userform = UserForm()
delvid = Del_Video()
if request.method == 'POST':
userform = UserForm(request.POST, request.FILES, instance=user)
delvid = Del_Video(request.POST)
if userform.is_valid():
userprofile.description = request.POST.get('description', userprofile.description)
userprofile.photo = request.FILES.get('photo', userprofile.photo)
userprofile.video = request.FILES.get('video', userprofile.video)
userprofile.rand_file = request.FILES.get('rand_file', userprofile.rand_file)
userprofile.save()
else:
messages.add_message(request, messages.INFO, 'Invalid Form')
userform = UserForm()
if delvid.is_valid():
if request.POST['Delete']:
userprofile.video.delete()
else:
delvid = Del_Video()
context = {'user': user, 'year': year, 'userform': userform, 'userprofile': userprofile, 'delvid': delvid}
return render(request, 'users/detail.html', context)
And here is the form in the template:
<div class="row">
<div class="col-md-4">
<h4>Update User:</h4>
{% if userform.errors %}
<h6>{{ userform.errors }}</h6>
{% endif %}
{% if messages %}
{% for message in messages %}
<h5>{{ message }}</h5>
{% endfor %}
{% endif %}
<form action="{% url 'users:detail' user.id %}" method="post" enctype="multipart/form-data" data-ajax="false">
{% csrf_token %}
{{ userform.as_p }}
<input type="submit" value="Update">
</form>
</div>
</div>

Categories