Django not saving ModelChoiceField to base - django

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())
...

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.

Django Model Form field data not displaying

So I am trying to figure out why my dropdown menu will not display the list of collections for the user to pick from.
Form Screenshot: [1]: https://i.stack.imgur.com/UIrq6.png
Here is the Form.py file class used for this problem:
class ProductForm(ModelForm):
class Meta:
model = listing
fields = 'all'
_---------------------------------------------
Here is the user form VIEW:
def index(request):
form = ProductForm
if request.method == 'POST':
form = ProductForm(request.POST)
if form.is_valid():
form.save()
context = {'form':form}
return render(request, 'index.html', context)
Here is also the code for the 2 models here:
class Collection(models.Model):
title = models.CharField(max_length=255)
def __str__(self) -> str:
return self.title
class Meta:
ordering = ['title']
class listing(models.Model):
image = models.ImageField(blank=True, null=True)
name = models.CharField(max_length=255)
description = models.TextField()
unit_price = models.DecimalField(max_digits=6, decimal_places=2, validators=[MinValueValidator(1)])
inventory = models.IntegerField()
last_update = models.DateTimeField(auto_now=True)
collection = models.ForeignKey(Collection, on_delete=models.PROTECT, blank=True, null=True)
vendors = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=False)
I'm somewhat new to django and just trying to understand why for the form it won't display the list of collections in the dropdown.

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]

Django - Saving object worked one time but now it doesnt

i want to save an object to db and it worked one time but now it doesnt, i suspect that is something to do with the Glossary
Everything
views.py
#login_required
def product_form_view(request):
if request.method == 'POST':
form = Product_Form(request.POST, request.FILES)
if form.is_valid():
product_form = form.save()
product_form.save()
return redirect('product_management_view')
else:
form = Product_Form()
return render(request, 'product-form.html', {'form': form})
models.py
class Product (models.Model):
sub_chapter = models.ForeignKey(Sub_Chapter, on_delete=models.CASCADE)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
glossary = models.ManyToManyField(Glossary, blank=True )
name = models.CharField(max_length=40, blank=False, null=False)
description = models.TextField(null=True)
product_image = models.ImageField(
upload_to='media/images/product_images', blank=False, null=False)
reference = models.CharField(max_length=40, blank=False, null=False)
width = models.PositiveIntegerField()
height = models.PositiveIntegerField()
length = models.PositiveIntegerField()
unit_price = models.DecimalField(
max_digits=15, decimal_places=4, null=True)
polution = models.DecimalField(decimal_places=8, max_digits=15, null=True, blank=True )
technical_implementation = models.TextField(null=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse_lazy("manufacter_product_view", kwargs={'id': self.pk})
forms.py
class Product_Form(forms.ModelForm):
sub_chapter = forms.ModelChoiceField(queryset=Sub_Chapter.objects.all(),
required=True, widget=forms.Select())
supplier = forms.ModelChoiceField(queryset=Supplier.objects.all(),
required=True, widget=forms.Select())
glossary = forms.ModelChoiceField(queryset=Glossary.objects.all(),
required=False, widget=forms.SelectMultiple())
product_image = forms.ImageField(
required=True, widget=forms.FileInput())
class Meta():
model = Product
fields =[ 'name', 'description', 'reference', 'width', 'height', 'length', 'polution', 'unit_price', 'technical_implementation', 'sub_chapter', 'supplier', 'glossary', 'product_image', ]
There is a bug in your product_form_view, you are calling the save method on product_form variable i.e product_form.save() but product_form will have None in it as form.save() will return None on successfully saving the object,so it will break the code there.And you don't need to again call the save method at all.Calling form.save() is enough for saving the object and you should move the code in else part out of it as it not currently handling the form invalid case.
Your code should be like this:
#login_required
def product_form_view(request):
if request.method == 'POST':
form = Product_Form(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('product_management_view')
form = Product_Form()
return render(request, 'product-form.html', {'form': form})

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.