Cannot assign "<QuerySet []>": " must be a "" instance - python

I am trying to save this field from Forms.py, which seems to be causing this error: Cannot assign "<QuerySet [Vehicles: Toyota]>": "Group.vehicles" must be a "Vehicle" instance.
Everything saves correctly through the admin page but not through the form.
class GroupForm(forms.ModelForm):
vehicles = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), queryset=Vehicles.objects.all())
class Meta:
model = Group
Models.py:
class Vehicles(models.Model):
Vehicles = models.CharField(max_length=30, null=True, blank=True)
MaxRange = models.DecimalField(null=True, max_digits=20, decimal_places=3, default=Decimal('0.000'))
Speed = models.DecimalField(null=True, max_digits=20, decimal_places=3, default=Decimal('0.000'))
def __str__(self):
return self.Vehicles
class Group(models.Model):
group = models.CharField(max_length=30, blank=True)
vehicles = models.ForeignKey(Vehicles, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.group
'Group' consists of one type of vehicle.
views.py:
def home(request):
group = Group.objects.all()
form = GroupForm()
if request.method == 'POST':
form = GroupForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.vehicles = form.cleaned_data['vehicles']
obj.save()
return redirect('/')
context = {'group': group, 'form': form}
return render(request, 'calculator/Input.html', context)
Thanks you for any input

Nevermind, didn't need a checkbox widget. I deleted the line: "vehicles = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), queryset=Vehicles.objects.all())" and just left 'vehicle' as a field in Forms.py under class Meta: It saves/ users can only select one option now.

Related

How to Filter out Django Models

How do I create a lesson in a course without it showing in another course. I have a foreign key which is the course and it is under the models Lesson. I want to only view the lesson that is created under the certain course. But my problem is when I create a lesson in course 1, the lesson also shows in course 2. (sorry for bad english)
views.py
def lessonpage(request):
lesson = Lesson.objects.all()
if request.user.is_authenticated:
return render(request, "lessons/lessons.html", {'lessons': lesson})
else:
return redirect('loginpage')
def addlesson(request):
if request.method == "POST":
form = AddLessonForm(request.POST)
if form.is_valid():
form.save()
return render(request, "lessons/successlessons.html", {'form1': form})
form = AddLessonForm()
return render(request, "lessons/addlessons.html", {'form': form})
def deletelessons(request, id):
lesson = Lesson.objects.get(id=id)
lesson.delete()
return redirect("lessonspage")
models.py
from django.db import models
class Section(models.Model):
nameofsection = models.CharField(max_length=50, default="")
def __str__(self):
return self.nameofsection
class Course(models.Model):
ctitle = models.CharField(max_length=50, default="")
cdescription = models.TextField(max_length=200, default="")
#csection = models.ForeignKey(Section, on_delete=models.CASCADE)
def __str__(self):
return self.ctitle
def __unicode__(self):
return self.ctitle
class Meta:
db_table="courses"
class Lesson(models.Model):
title = models.CharField(max_length=50, default="")
description = models.TextField(max_length=200, default="")
course = models.ForeignKey(Course, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return self.title
urls.py
path('course/', coursepage, name="coursepage"),
path('course/<int:pk>', CourseDetailView.as_view(), name='detailed'),
path('addcourse/', addcourse, name="addcoursepage"),
path('editcourse/<int:id>', updatecourse, name="editcoursepage"),
path('updatecourse/<int:id>', updatecourserecord, name="updatecourse"),
path('deletecourse/<int:id>', deletecourse, name="deletecourse"),
path('lessons', lessonpage, name="lessonspage"),
path('lessons/addlessons', addlesson, name="addlessonspage"),
path('deletelessons/<int:id>', deletelessons, name="deletelessons"),

Django Error : ValueError at / Field 'ticket_id' expected a number but got 'NS000001'

While Inserting data, I got this error. May be this could be due to change of default primary key. I do not want to enter ticket_id field as I have set default value for that field (default='NS000001')
models.py
class Ticket(models.Model):
ticket_id = models.AutoField(primary_key=True, default='NS000001', editable=False)
server_details = models.CharField(max_length=100)
send_date = models.DateTimeField(default=timezone.now)
license_no = models.CharField(max_length=25)
file = models.FileField(upload_to='documents/%Y/%m/%d/')
def __str__(self):
return self.ticket_id
views.py
def Index(request):
if request.method == "POST":
form = SaveTicket(request.POST,request.FILES or None)
if form.is_valid():
form.save()
print(form)
return redirect('index')
else:
form = SaveTicket()
return render(request, 'index.html')
forms.py
class SaveTicket(forms.ModelForm):
class Meta:
model = Ticket
fields = ['server_details','send_date','license_no','file']
first
you don't need define Autofield yourself.
class Ticket(models.Model):
server_details = models.CharField(max_length=100)
send_date = models.DateTimeField(default=timezone.now)
license_no = models.CharField(max_length=25)
file = models.FileField(upload_to='documents/%Y/%m/%d/')
second
If your Ticket ID is static - you can create a property:
class Ticket(models.Model):
... # any staff here
#property
def ticket_id(self):
return f'NS{(self.pk or 0):06d}'
last
after that you can use it everywhere:
print(ticket.ticket_id)
>>>'NS2134154'

How to assign a default choice value to a user when they sign up in django framework

I am writing a logic where when a users creates and account, i want to automatically assign the free membership to them and i know this should be done in the register view but i don't know why it's not working as expected. I still have to manually go to my admin page and manually assign a value to newly created user and that's not what i really wanted.
Models.py
class Membership(models.Model):
MEMBERSHIP_CHOICES = (
('Enterprise', 'Enterprise'), # Note that they are all capitalize//
('Team', 'Team'),
('Student', 'Student'),
('Free', 'Free')
)
PERIOD_DURATION = (
('Days', 'Days'),
('Week', 'Week'),
('Months', 'Months'),
)
slug = models.SlugField(null=True, blank=True)
membership_type = models.CharField(choices=MEMBERSHIP_CHOICES, default='Free', max_length=30)
duration = models.PositiveIntegerField(default=7)
duration_period = models.CharField(max_length=100, default='Day', choices=PERIOD_DURATION)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
def __str__(self):
return self.membership_type
#### User Membership
class UserMembership(models.Model):
user = models.OneToOneField(User, related_name='user_membership', on_delete=models.CASCADE)
membership = models.ForeignKey(Membership, related_name='user_membership', on_delete=models.SET_NULL, null=True)
reference_code = models.CharField(max_length=100, default='', blank=True)
def __str__(self):
return self.user.username
#receiver(post_save, sender=UserMembership)
def create_subscription(sender, instance, *args, **kwargs):
if instance:
Subscription.objects.create(user_membership=instance, expires_in=dt.now().date() + timedelta(days=instance.membership.duration))
views.py
def register(request):
reviews = Review.objects.filter(status='published')
info = Announcements.objects.all()
categories = Category.objects.all()
if request.method == "POST":
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
obj = request.user
get_membership = Membership.objects.get(membership_type='Free')
instance = UserMembership.objects.create(user=obj, membership=get_membership)
messages.success(request, f'Account Successfully created for {username}! You can Login In Now')
return redirect('userauths:login')
elif request.user.is_authenticated:
return redirect('elements:home')
else:
form = UserRegisterForm()
context = {
'reviews': reviews,
'form': form,
'info': info,
'categories': categories
}
return render(request, 'userauths/register.html', context)
in models you need to special a default="..." attribute

Get the user instance from a profile model

Hella everyone, Alright I'm building an ecommerce website and stuck at a certain point, I got two models Seller and Product, as follows:
class Seller(models.Model):
seller = models.OneToOneField(User, on_delete=models.CASCADE)
city = models.CharField(max_length=30)
country = models.CharField(max_length=30)
phone_number = PhoneNumberField()
email = models.EmailField(max_length=300)
def __str__(self):
return self.seller.username
class Product(models.Model):
STATUS_CHOICES = [
('New', 'New'),
('New', 'Used'),
]
image = models.ImageField(default='dev1.jpg', upload_to='images/')
condition = models.CharField(choices=STATUS_CHOICES, max_length=10)
seller = models.ForeignKey(Seller, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
description = models.TextField()
price = models.CharField(max_length=15)
location = models.CharField(max_length=30)
posted_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Now I have a form to save new Product as:
class SellProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ('image', 'condition', 'title', 'description', 'price', 'location', )
The problem is in views.py:
#login_required
def sell(request):
form = SellProductForm()
if request.method == 'POST':
form = SellProductForm(request.POST)
if form.is_valid():
print('Ok')
instance = form.save(commit=False)
instance.seller = request.user
instance.save()
return redirect('index')
context = {
'form': form,
}
return render(request, 'myapp/sell.html', context)
At the end, I get the ERROR:
"Product.seller must be a Seller instance."
I understand the demand but I can't get myself to imagine the code and come up with a solution, for I'm giving it a User instance not a seller instance.
Since it is a OneToOneField you can obtain the related Seller model of a User object with user.seller, so in this case:
instance.seller = request.user.seller
This will raise an AttributeError if no Seller is linked to the logged in user.

How to get the username of the current user and assign it to a certain field in a form in django?

This is my models.py file
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Book(models.Model):
category_choices =(
#("Undefined","Undefined"),
("Action", "Action"),
("Romance", "Romance"),
("Horror", "Horror"),
("Comedy", "Comedy"),
("Adventure", "Adventure"),
("Dramatic", "Dramatic"),
("Crime","Crime"),
("Fantasy","Fantasy"),
)
name = models.CharField(max_length=100)
author = models.CharField(max_length=100, null=True)
content = models.TextField()
price = models.DecimalField(max_digits=5, decimal_places=2)
image = models.ImageField(upload_to= 'photos/%y/%m/%d', blank = True)
category = models.CharField(
max_length = 20,
choices = category_choices,
#default = 'Undefined'
)
publication_year = models.CharField(max_length=4, null=True)
ISBN = models.CharField(max_length=13, null=True, unique=True)
active = models.BooleanField(default= True)
def __str__(self):
return self.name
class Borrow(models.Model):
name = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
book = models.OneToOneField(Book, null=True, on_delete= models.SET_NULL)
period = models.PositiveIntegerField(default=0)
id = models.IntegerField(primary_key=True)
def __str__(self):
return str(self.book)
and this is my forms.py file
from django import forms
from .models import Borrow
class BorrowForm(forms.ModelForm):
class Meta:
model = Borrow
fields = ('name', 'book', 'period')
and this is the function in my views.py file that renders the form
#login_required
def borrowing(request):
momo = BorrowForm()
if request.method == 'POST':
momo = BorrowForm(request.POST)
if momo.is_valid():
instacne = momo.save(commit=False)
instacne.user = request.user.username
instacne.save()
return redirect('profile')
return render(request, 'books/book.html', {'momo': momo})
The role of this function is to render that form and to save the data that user will enter and automatically assign the username of the current user to the field 'name' in form.
I tried alot of things to get the username of the current user and assign it to the field 'name' but nothing works and that field stays blank.
You're using a models.ForeignKey(User) so that table will store a user id, not a username. I'd call this field user and not name, personally.
Therefore you need to provide a user instance to it like this;
#login_required
def borrowing(request):
initial = {}
if request.user.is_authenticated:
initial.update({'name': request.user})
momo = BorrowForm(initial=initial)
if request.method == 'POST':
momo = BorrowForm(request.POST)
if momo.is_valid():
instance = momo.save(commit=False)
instance.user = request.user
instance.save()
If you wanted to easily get the username for a Borrow instance you could do this;
class Borrow(models.Model):
name = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
book = models.OneToOneField(Book, null=True, on_delete= models.SET_NULL)
period = models.PositiveIntegerField(default=0)
id = models.IntegerField(primary_key=True)
def __str__(self):
return str(self.book)
#property
def username(self):
return self.name.username
If you want the form to offer users by username, you can either have the str method of your user model return username, or create custom choices as a tuple of user ID & username in the form __init__

Categories