How to save the attribute of my ForeignKey? - django

I am trying to create a view that allows users to upload their documents in my Lessons model. However when documents are uploaded, I am not able to save the instance in which the form is being submitted. When I access the admin page, the field for my ForeignKey is left empty.
This is the views.py for users to submit their documents:
class UploadLessonView(CreateView):
model = Lesson
fields = ['title', 'file']
template_name = 'store/upload_lesson.html'
success_url = '../'
def form_valid(self, form):
form.instance.author = self.request.user
return super(UploadLessonView, self).form_valid(form)
This is the models.py for my child model:
class Lesson(models.Model):
title = models.CharField(max_length=100)
file = models.FileField(upload_to="lesson/pdf")
date_posted = models.DateTimeField(default=timezone.now)
post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('lesson_upload', kwargs={'pk': self.pk})
For my parent model:
class Post(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(default = 'default0.jpg', upload_to='course_image/')
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=6)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
rating = models.IntegerField(default = 0)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk' : self.pk})
Field for Post is left empty when I submit documents.

You are not setting the Post object in Lesson with the View. So you can fix it in two ways.
One way, is to send it via url, for example:
# url
url('lesson/<int:post_id>/create/', UploadLessionView.as_view())
And use the value of post_id in View:
class UploadLessonView(CreateView):
model = Lesson
fields = ['title', 'file']
template_name = 'store/upload_lesson.html'
success_url = '../'
def form_valid(self, form):
form.instance.post = get_object_or_404(Post, pk=self.kwargs.get('post_id'))
return super(UploadLessonView, self).form_valid(form)
Two, you can add post in fields:
class UploadLessonView(CreateView):
model = Lesson
fields = ['title', 'file', 'post'] # <-- Here
template_name = 'store/upload_lesson.html'

Related

I have created models and my views function to add the attendance of employee. But data is not saving in database and no error comes up

I have created a form named as AttendanceForm :
class AttendanceForm(forms.ModelForm):
class Meta:
model = Attendance
fields = '__all__'
These are models
class Employee(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
eid = models.IntegerField(primary_key=True)
salary = models.IntegerField()
gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default=1)
contactno = models.CharField(max_length=10)
email = models.CharField(max_length=30)
country = models.CharField(max_length=30)
city = models.CharField(max_length=20)
pincode = models.IntegerField()
address = models.CharField(max_length=60)
def __str__(self):
return self.user.first_name + ' ' + self.user.last_name
class Attendance(models.Model):
employee = models.ForeignKey(Employee, on_delete=models.CASCADE, default=1)
attendancedate = models.DateField()
in_time = models.TimeField()
out_time = models.TimeField()
description = models.TextField()
def __str__(self):
return str(self.employee)
view for attendance.
#csrf_exempt
def addattendance(request):
form = AttendanceForm()
emp_list = Employee.objects.all()
if request.method == 'POST':
form = AttendanceForm(request.POST)
if form.is_valid():
form.save(commit=True)
return redirect('employee/detail_attendance')
return render(request, 'employee/addattendance.html', {'form': form, 'emp_list': emp_list})
I tried everything, but I don't know why the data is not saving into the database. Also, models are created fine, and the main thing is that there are no errors coming up. 
Please let me know if any changes are required.
I can suggest simple solution with Class-Based-Views:
from django.views.generic.edit import FormView
def AddAttendanceFormView(FormView):
form_class = AttendanceForm
extra_context = {"emp_list": Employee.objects.all()}
success_url = reverse_lazy('employee/detail_attendance')
template_name = 'employee/addattendance.html'
def post(self, *args, **kwargs):
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
return self.form_invalid(form)
Remember, that in urls.py you need to use .as_view() for class based views, like:
path((...), AddAttendanceFormView.as_view())
Also, you will not need #csrf_exempt, just put {% csrf_token %} anywhere inside your form's template.

Not Found: /post/12/responses/

What I am trying to do is to get particular post comments.
models.py
class Post(models.Model):
title = models.CharField(max_length = 100)
content = models.TextField()
date = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
class Comments(models.Model):
post = models.ForeignKey(Post,related_name='comments',on_delete=models.CASCADE)
name = models.CharField(max_length=50)
date = models.DateTimeField(default=timezone.now)
content = models.TextField()
def get_absolute_url(self):
return reverse('Home')
views.py
class CommentDetailView(DetailView):
model = Comments
template_name = 'CovidHelp/comment_response.html'
context_object_name = 'comments'
paginate_by = 10
def get_queryset(self):
post = get_object_or_404(Post, id=self.kwargs.get('pk'))
return Comments.objects.filter(post=post).order_by('-date')
urls.py
path('post/<int:pk>/responses/', CommentDetailView.as_view(), name='responses')
However I'm getting error when trying to access such an url:
Not Found: /post/12/responses/
you want to return a list of comments for a post right?
so you need to use Listview instead of using detailview to return a list of comments and then use get_queryset to filter it by the post id.

Sort Blog Post comments by date DJANGO

Hi i have a problem with comments on my Blog app in Django.
Everything is working fine except that i want to display comment sorted by date (newest on top)
o and it'll be great i'll be able to put in to the author field user that is actually loged in.. TY
views.py
#login_required
def add_comment_to_post(request, pk):
post = get_object_or_404(Post, 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('post-detail', pk=post.pk)
else:
form = CommentForm()
return render(request, 'blog/add_comment_to_post.html', {'form': form})
models.py
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
author = models.CharField(max_length=100)
text = models.TextField()
created_on = models.DateTimeField(default=timezone.now)
active = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def __str__(self):
return self.text
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('author', 'text', 'created_on')
one option is, in your models add a meta class as follows
class Meta:
ordering = ['-created_on']
Add class Meta: ordering(-date_posted), date_posted can be changed to the variable containing the DateTimeField()
class BlogComment(models.Model):
blogpost_connected = models.ForeignKey(Posts, related_name='comments', on_delete=models.CASCADE)
author = models.ForeignKey(User, on_delete=models.CASCADE)
comment = models.CharField(max_length=255, null=True)
date_posted = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ['-date_posted']
def __str__(self):
return str(self.author) + ', ' + self.blogpost_connected.title[:40]

How to enter ForeginKey values in a model with CreateView

I am creating a wiki and need to put in values in the model called revision. This table has a foreigkey to wikipage.
My problem is that I am unable to insert values in the revision model.
I have tried using def form_valid(self, form) like you would when entering user, without any luck.
Models.py
class Wikipage(models.Model):
title = models.CharField(max_length=100)
date_created = models.DateTimeField('Created', auto_now_add=True)
def __str__(self):
return self.title
class Meta:
verbose_name_plural = "Wikipages"
class Revision(models.Model):
wikipage = models.ForeignKey(Wikipage, null=True, on_delete=models.CASCADE, related_name='revisions')
content = models.TextField('Content')
author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
last_edit = models.DateTimeField('Last Edited', auto_now=True)
comment = models.TextField('Comment', blank=True)
class Meta:
verbose_name = 'Revision'
verbose_name_plural = 'Revisions'
ordering = ['-last_edit']
get_latest_by = ['last_edit']
def __str__(self):
return self.content
View.py
Class WikipageCreateView(CreateView):
template_name = 'wiki/wikipageform.html'
model = Wikipage
fields = ['title']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
The template are as simple as possible with {{ form.as_p }} and all the necessary stuff.

Django not saving ModelChoiceField to base

This is my model:
class User(models.Model):
name = models.CharField(max_length=50)
mail = models.CharField(max_length=50)
nickname = models.CharField(max_length=50)
def __str__ (self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=200)
lead = models.CharField(max_length=10, default='default')
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
user = models.ForeignKey(User, related_name="User", null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
This is my view:
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'post_new.html', {'form': form})
This is my forms.py:
class PostForm(forms.ModelForm):
selectuser = forms.ModelChoiceField(queryset=User.objects.all())
class Meta:
model = Post
fields = ('title','lead', 'text',)
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('name','nickname','mail')
My problem is that selected value from ModelChoiceField is saving to base without value just empty field. Can u help me resolve that problem?
My problem is that selected value from ModelChoiceField is saving to
base without value just empty field. Can u help me resolve that
problem?
The model field is Post.user, but your form field PostForm.selectuser. Try using user in the PostForm.
class PostForm(forms.ModelForm):
user = forms.ModelChoiceField(queryset=User.objects.all())
...