How to save from html select to sql in django - django

I want to save from HTML select to SQL but "Cannot assign "'27'": "UserProduct.category" must be a "Category" instance." I get an error. What am I doing wrong?
sell.html
<div class="form-group">
<p>Yerləşdirdiyiniz məhsul "İkinci əl məhsullar" kateqoriyasında görünəcək.</p>
<select class="input search-categories" name="up_category">
<option value="0">Kateqoriya seç</option>
{% for category in category %}
{% if category.active %}
{% if category.parent_id %}
<option value="{{category.id}}">{{category.name}}</option>
{% else %}
<option value="{{category.id}}" style="font-weight: bold;">{{category.name}}</option>
{% endif %}
{% endif %}
{% endfor %}
</select>
</div>
views.py
def sell(request):
category = Category.objects.all()
context = {'category': category}
if request.POST:
product_name = request.POST.get('product_name')
up_category = request.POST.get('up_category')
keywords = request.POST.get('keywords')
descriptions = request.POST.get('descriptions')
main_image = request.POST.get('main_image')
price = request.POST.get('price')
detail = request.POST.get('detail')
image1 = request.POST.get('image1')
image2 = request.POST.get('image2')
image3 = request.POST.get('image3')
if product_name == '' or up_category == 'Kateqoriya seç' or keywords == '' or descriptions == '' or price == '' or price == str or detail == '':
messages.warning(request, 'Bütün xanaları doldurduğunuzdan əmin olun!')
else:
newUserProduct = UserProduct(user=request.user,
name=product_name,
category=up_category,
keywords=keywords,
descriptions=descriptions,
detail=detail,
main_image=main_image,
image1 = image1,
image2 = image2,
image3 =image3
)
newUserProduct.save()
messages.warning(request, 'Məhsulunuz satışa çıxdı.')
return render(request, 'forms/sell.html', context)
return render(request, 'forms/sell.html', context)
models.py
class UserProduct(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default=False)
name = models.CharField(max_length=100)
category = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
main_image = models.ImageField(upload_to='static/product_images/%Y/%m/%d/')
detail = models.TextField()
keywords = models.CharField(max_length=50)
description = models.CharField(max_length=1000)
price = models.FloatField()
sale = models.IntegerField(blank=True, null=True, verbose_name="Sale (%)")
image1 = models.ImageField(upload_to='static/product_images/%Y/%m/%d/', blank=True, null=True)
image2 = models.ImageField(upload_to='static/product_images/%Y/%m/%d/', blank=True, null=True)
image3 = models.ImageField(upload_to='static/product_images/%Y/%m/%d/', blank=True, null=True)
date_created = models.DateTimeField(auto_now_add=True)
I want to save from HTML select to SQL but "Cannot assign "'27'": "UserProduct.category" must be a "Category" instance." I get an error. What am I doing wrong?

In your UserProduct class, the field category is a ForeignKey to the Category class. Try getting the Category first from your request.POST, then adding it:
def sell(request):
category = Category.objects.all()
context = {'category': category}
if request.POST:
product_name = request.POST.get('product_name')
up_category = request.POST.get('up_category')
keywords = request.POST.get('keywords')
descriptions = request.POST.get('descriptions')
main_image = request.POST.get('main_image')
price = request.POST.get('price')
detail = request.POST.get('detail')
image1 = request.POST.get('image1')
image2 = request.POST.get('image2')
image3 = request.POST.get('image3')
if product_name == '' or up_category == 'Kateqoriya seç' or keywords == '' or descriptions == '' or price == '' or price == str or detail == '':
messages.warning(request, 'Bütün xanaları doldurduğunuzdan əmin olun!')
else:
cat = Category.objects.get(pk=up_category) # CHANGED
newUserProduct = UserProduct(user=request.user,
name=product_name,
category=cat, # CHANGED
keywords=keywords,
descriptions=descriptions,
detail=detail,
main_image=main_image,
image1 = image1,
image2 = image2,
image3 =image3
)
newUserProduct.save()
messages.warning(request, 'Məhsulunuz satışa çıxdı.')
return render(request, 'forms/sell.html', context)
return render(request, 'forms/sell.html', context)

Related

i Cannot access forigenkey table data in template

views.py
def product_display_detail(request, id, *args, **kwargs):
obj21 = Product.objects.filter(id=id).values()
obj3 =Stock.objects.filter(product_id=id).values()
obj1 =Product_type.objects.all()
context = {
"object21" : obj21,
"object1" : obj1,
"object3" : obj3
}
return render(request,"product_detail.html",context)
html file
{% for s in object3 %}
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" class="custom-control-input" id="size-1" name="size">
<label class="custom-control-label" for="size-1">{{ s.size_id.size_name }}</label>
</div>
{% endfor %}
models.py
class Size(models.Model):
size_name = models.CharField(max_length=20)
class Colour(models.Model):
col_name = models.CharField(max_length=40)
class Product(models.Model):
product_name = models.CharField(max_length=120)
product_type = models.ForeignKey(Product_type, null=False, on_delete=models.PROTECT)
product_desc = models.TextField(max_length=500 , blank=False)
product_price = models.DecimalField(max_digits = 5,decimal_places = 2)
product_qty = models.IntegerField()
product_image = models.ImageField(null=False,blank=False,upload_to="images/")
def __str__(self):
return self.product_name
class Stock(models.Model):
product_id = models.ForeignKey(Product, null=True,on_delete=models.CASCADE)
size_id = models.ForeignKey(Size, null=True,on_delete=models.CASCADE)
colour_id = models.ForeignKey(Colour,null=True,on_delete=models.CASCADE)
qty = models.IntegerField()
product_details = models.TextField(max_length=500 , null=True , blank=True)
image = models.ImageField(null=False,blank=False,upload_to="images/")
i want size name from size table using stock object

filter category Django

I want to make a button to filter product by category.. Example Salad or Meat. Without Model ProductAtribuut im able to do it, but now i added the model, so im real confused how i can get the data of a Foreign Key inside a Foreign Key
ProductAtribuut -> Product(FK) -> Categorie(FK)
Models.py
class Categorie(models.Model):
naam = models.CharField(max_length=150,db_index=True)
slug = models.SlugField(unique=True)
class MPTTMeta:
order_insertion_by = ['naam']
class Meta:
ordering=('-naam',)
def __str__(self):
return self.naam
def get_absolute_url(self):
return reverse('JavaKitchen:product_by_categorie', args=[self.slug])
#property
def get_products(self):
return Product.objects.filter(categorie__naam=self.naam)
class Groente(models.Model):
groente = models.CharField(max_length=100)
def __str__(self):
return self.groente
class Vlees(models.Model):
vlees = models.CharField(max_length=100)
def __str__(self):
return self.vlees
class Product(models.Model):
slug = models.SlugField(unique=True, primary_key=True)
titel = models.CharField(max_length=200)
beschrijving = models.TextField(blank=True, null=True)
categorie = models.ForeignKey(Categorie, on_delete=models.CASCADE)
class Meta:
ordering=('-titel',)
def __str__(self):
return self.titel
def get_title_uppercase(self):
return self.titel.upper()
def get_absolute_url(self):
return reverse('JavaKitchen:product_detail',args=[self.id,])
class ProductAtribuut(models.Model):
def groente():
return Groente.objects.filter(groente='geen').first()
def vlees():
return Vlees.objects.filter(vlees='geen').first()
product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=False)
groente = models.ForeignKey(Groente, on_delete=models.CASCADE, default=groente)
vlees = models.ForeignKey(Vlees, on_delete=models.CASCADE, default=vlees)
prijs = models.FloatField(default=0)
afbeelding = models.ImageField(blank=True, upload_to='gerechten/') #later upgrade..
zichtbaar = models.BooleanField(default=True)
def __str__(self):
return self.product.titel
def image_tag(self):
return mark_safe('<img src="/media/%s" width="80" height="auto" />' % (self.afbeelding))
image_tag.short_description = 'Image'
Views.py
def product_list(request,categorie_slug=None):
categorie = None
javakitchen = JavaKitchen.objects.get(id=1)
openings_tijden = Openings_tijden.objects.all()
categories = Categorie.objects.all().filter(zichtbaar=True)
product = Product.objects.all()
productatribuut = ProductAtribuut.objects.all().filter(zichtbaar=True)
if categorie_slug:
categorie = get_object_or_404(Categorie,slug=categorie_slug)
product = productatribuut.filter(product=product)
context = { 'categories':categories,
'categorie':categorie,
'product':product,
'form':form,
'javakitchen':javakitchen,
'openings_tijden': openings_tijden,
'productatribuut': productatribuut
}
return render(request, 'pages/index.html', context)
HTML template
<div class="categories">
<h1>{% if categorie %}{{ categorie.naam }}{% else %} ALLE GERECHTEN {% endif %}</h1>
<ol class="type">
<li><a class="page-scroll" href='{% url "JavaKitchen:product_list" %}#dinner'>Alles</a></li>
{% for c in categories %}
<li><a class="page-scroll" href="{{ c.get_absolute_url }}#dinner">{{ c.naam }}</a></li>
{% endfor %}
</ol>
<div class="clearfix"></div>
</div>
I used this before to get the category. when i didnt have class ProductAtribuut
if categorie_slug:
categorie = get_object_or_404(Categorie,slug=categorie_slug)
product = product.filter(categorie=categorie)
but now i dont know how i do get the category
ProductAtribuut -> Product(fk) -> Categorie(fk)

'str' object has no attribute 'objects' django

My views.py file is
def studentFeedBack(request):
studentid = ''
courseid = ''
teacherid = ''
if request.method == 'POST':
studentid_id = request.POST.get("studentid")
studentid = studentid.objects.get(id=studentid_id)
courseid_id = request.POST.get("courseid")
courseid = courseid.objects.get(id=courseid_id)
teacherid_id = request.POST.get("teacherid")
teacherid = teacherid.objects.get(id=teacherid_id)
description = request.POST.get("description")
rating = request.POST.get("rating")
studentFeedBack.objects.create(
courseid=courseid,
description=description,
studentid=studentid,
teacherid=teacherid,
rating=rating
)
return render(
request,
'forms/studentFeedBack.html',
{
'studentids':studentid.objects.all(),
'courseids':courseid.objects.all(),
'teacherids':teacherid.objects.all(),
}
)
and my models.py file is
class StudentFeedBack(models.Model):
feedbackid = models.AutoField(primary_key=True)
courseid = models.ForeignKey('Course', on_delete=models.CASCADE)
description = models.CharField(max_length=500)
submitdate = models.DateTimeField(auto_now_add=True)
teacherid = models.ForeignKey('schoolTeacher', on_delete=models.CASCADE)
studentid = models.ForeignKey('Student', on_delete=models.CASCADE)
option = [('Good','Good'),('Average','Average'),('Bad','Bad')]
rating = models.CharField(max_length=100, choices=option, default='none')
class Course(models.Model):
courseid = models.IntegerField(primary_key=True)
coursedescription = models.CharField(max_length=500)
coursename = models.CharField(max_length=50)
userid = models.IntegerField()
code = models.CharField(max_length=50)
videolink = models.FileField(default='default_link')
createddate = models.DateTimeField()
imagelink = models.URLField(default='default_link')
duration = models.DateTimeField()
longdes = models.TextField()
coursetype = models.CharField(max_length=50)
assignto = models.CharField(max_length=200)
status = models.BinaryField()
def _str_(self):
return self.coursename
class Meta:
db_table = "courseids"
class schoolTeacher(models.Model):
teacherid = models.IntegerField(primary_key=True)
name = models.CharField(max_length=50)
address = models.CharField(max_length=200)
email = models.EmailField()
contact = models.IntegerField()
passowrd = models.CharField(max_length=13)
image = models.ImageField(default='default.jpg')
regno = models.CharField(max_length=20)
joiningdate = models.DateTimeField()
def _str_(self):
return self.name
class Meta:
db_table = "teacherids"
class Student(models.Model):
studentid = models.IntegerField(primary_key=True)
regno = models.CharField(max_length=20)
name = models.CharField(max_length=50)
email = models.EmailField(max_length=50)
contactno = models.CharField(max_length=13)
registrationdate = models.DateTimeField()
address = models.CharField(max_length=200)
password = models.CharField(max_length=13)
imagepath = models.ImageField(max_length=100, default='default.jpg')
sectionid = models.IntegerField()
def _str_(self):
return self.name
class Meta:
db_table = "studentids"
and studentFeedBack html file has the following form
<form action="/studentFeedBack/" method="POST">
{% csrf_token %}
<label for="studentid">Student Id</label>
<!-- <input type="number" name="studentid"><br><br> -->
<select name="studentid" required>
{% for studentid in studentids %}
<option value="{{studentid.id}}">{{studentid.name}}</option>
{% endfor %}
</select><br><br>
<!-- <label for="courseid">Course Id</label>
<input type="number" name="courseid"><br><br> -->
<label for="courseid">Course Id</label>
<select name="courseid" required>
{% for courseid in courseids %}
<option value="{{courseid.id}}">{{courseid.coursename}}</option>
{% endfor %}
</select><br><br>
<label for="teacherid">Teacher Id</label>
<!-- <input type="number" name="teacherid"><br><br> -->
<select name="teacherid" required>
{% for teacherid in teacherids %}
<option value="{{teacherid.id}}">{{teacherid.name}}</option>
{% endfor %}
</select><br><br>
<label for="description" >Feedback</label>
<textarea class="form-control" rows="3" name="description"></textarea><br><br>
<label for="rating">Rating</label><br>
<input type="radio" id="Good" name="rating" value="Good">
<label for="Good">Good</label><br>
<input type="radio" id="Average" name="rating" value="Average">
<label for="Average">Average</label><br>
<input type="radio" id="Bad" name="rating" value="Bad">
<label for="Bad">Bad</label><br><br>
<button type="submit" class="btn btn-primary" >Submit</button>
</form>
The studentFeedBack model has foreign keys from student, schoolTeacher and Course. This is giving error on browser that 'str' object has no attribute 'objects'
Other than that my form is not giving any values in select options and that is also probably because of this error.
The design of the view is the issue
According to the line
studentid =''
studentid remains a string . You could try proper importation of the models.
Try:
views.py
from .models import Course, Student,schoolTeacher,studentFeedBack
def studentFeedBack(request):
#studentid = ''
#courseid = ''
#teacherid = ''
if request.method == 'POST':
studentid_id = request.POST.get("studentid")
studentid = Student.objects.get(id=studentid_id)
courseid_id = request.POST.get("courseid")
courseid = Course.objects.get(id=courseid_id)
teacherid_id = request.POST.get("teacherid")
teacherid = schoolTeacher.objects.get(id=teacherid_id)
description = request.POST.get("description")
rating = request.POST.get("rating")
studentFeedBack.objects.create(
courseid=courseid,
description=description,
studentid=studentid,
teacherid=teacherid,
rating=rating
)
return render(
request,
'forms/studentFeedBack.html',
{
'studentids':Student.objects.all(),
'courseids':Course.objects.all(),
'teacherids':schoolTeacher.objects.all(),
}
)
Alternatively, Django is superb at handing forms for models
https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/#modelform
This will be better for your view as there is no validation at the moment
You could also have:
views.py
...
from django.forms.models import modelform_factory
from .models import studentFeedBack
def studentFeedBack(request):
fields=[
'courseid','description','studentid','teacherid','rating']
form=modelform_factory(studentFeedBack, fields=fields)
if request.method == 'POST':
form=modelform_factory(studentFeedBack, fields=fields, data=request.POST)
## Validates the data submitted
if form.is_valid():
## Creates a studentFeedBack instance
form.save()
## If form is invalid, it will fall through to the template with the incorrect data.
else:
### Handle the incorrect form
pass
return render(
request,
'forms/studentFeedBack.html',
{
'studentids':Student.objects.all(),
'courseids':Course.objects.all(),
'teacherids':schoolTeacher.objects.all(),
'form':form,
}
)
forms/studentFeedBack.html
<form action="/studentFeedBack/" method="POST">
{% csrf_token %}
{{form.as_p}}
</form>
https://docs.djangoproject.com/en/3.1/topics/forms/#working-with-form-templates
You may need to add a verbose_name attribute to your model fields:
models.py
class StudentFeedBack(models.Model):
...
teacherid = models.ForeignKey('schoolTeacher', on_delete=models.CASCADE, verbose_name="Teacher")
...
https://docs.djangoproject.com/en/3.1/ref/models/fields/#verbose-name
Customize as needed.
I hope this helps you understand Django better.
Edit
The function-based view has the same name as an imported model
For the first view:
from .models import Course, Student,schoolTeacher
from .models import studentFeedBack as studentFeedBackModel
def studentFeedBack(request):
#studentid = ''
#courseid = ''
#teacherid = ''
if request.method == 'POST':
studentid_id = request.POST.get("studentid")
studentid = Student.objects.get(id=studentid_id)
courseid_id = request.POST.get("courseid")
courseid = Course.objects.get(id=courseid_id)
teacherid_id = request.POST.get("teacherid")
teacherid = schoolTeacher.objects.get(id=teacherid_id)
description = request.POST.get("description")
rating = request.POST.get("rating")
studentFeedBackModel.objects.create(
courseid=courseid,
description=description,
studentid=studentid,
teacherid=teacherid,
rating=rating
)
return render(
request,
'forms/studentFeedBack.html',
{
'studentids':Student.objects.all(),
'courseids':Course.objects.all(),
'teacherids':schoolTeacher.objects.all(),
}
)

I filling the fields but do not enter in form.is_valid ():

Experts I am waiting for my problem to be solved on the internet
Why when I finished filling the fields in django do not enter in form.is_valid (): Although the results are presented correctly I hope to solve this problem
class Listing(models.Model):
property_type = models.IntegerField(choices=PROPERTY_TYPE_CHOICES, default=1)
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
price = models.BigIntegerField()
roomsTotal = models.PositiveSmallIntegerField(null=True)
Bathrooms = models.PositiveSmallIntegerField(default=0)
bedrooms = models.PositiveSmallIntegerField(default=0)
Receptionrooms = models.PositiveSmallIntegerField(default=0)
livingArea = models.DecimalField(max_digits=9, decimal_places=1)
lotSize = models.DecimalField(max_digits=9, decimal_places=1)
unitType = models.IntegerField(choices=UNIT_TYPE_CHOICES, default=1)
VOnSea = models.BooleanField(default=False, blank=True)
yearBuilt = models.PositiveIntegerField(
validators=[
MinValueValidator(1900),
MaxValueValidator(datetime.datetime.now().year)],
help_text="Use the following format: <YYYY>")
hoaPrice = models.BigIntegerField(null=True,blank=True)
groundTankSize = models.DecimalField(max_digits=6, decimal_places=1,null=True,blank=True)
garageSize = models.DecimalField(max_digits=6, decimal_places=1,null=True,blank=True)
homeDescription = models.TextField(blank=True)
class ForSaleForm(forms.Form):
property_type = forms.ChoiceField(widget=forms.Select, choices=PROPERTY_TYPE_CHOICES,required=False)
price = forms.IntegerField(required=True)
roomsTotal = forms.IntegerField()
Bathrooms = forms.IntegerField(required=True)
bedrooms = forms.IntegerField(required=True)
Receptionrooms = forms.IntegerField(required=True)
livingArea = forms.DecimalField(required=True)
lotSize = forms.DecimalField(required=True)
unitType = forms.ChoiceField(widget=forms.Select, choices=UNIT_TYPE_CHOICES,required=False)
yearBuilt = forms.DateField(required=True)
def clean(self):
data = self.cleaned_data
if data.get('price', None) or (data.get('Bathrooms', None) and data.get('bedrooms', None)):
return data
else:
raise forms.ValidationError('Provide either a price and Bathrooms or a bedrooms')
form = ForSaleForm(request.POST or None)
for key in request.POST.keys():
if key != 'csrfmiddlewaretoken':
print(key,":",request.POST[key])
if form.is_valid():
propertyType = form.cleaned_data.get('propertyType')
price = form.cleaned_data.get('price')
roomsTotal = form.cleaned_data.get('roomsTotal')
Bathrooms = form.cleaned_data.get('Bathrooms')
bedrooms = form.cleaned_data.get('bedrooms')
Receptionrooms = form.cleaned_data.get('Receptionrooms')
livingArea = form.cleaned_data.get('livingArea')
lotSize = form.cleaned_data.get('lotSize')
unitType = form.cleaned_data.get('unitType')
yearBuilt = form.cleaned_data.get('yearBuilt')
listing = Listing(
user=request.user,
price=price,
roomsTotal=roomsTotal,
Bathrooms=Bathrooms,
bedrooms=bedrooms,
Receptionrooms=Receptionrooms,
livingArea=livingArea,
lotSize=lotSize,
unitType=unitType,
yearBuilt=yearBuilt,
remodelYear=remodelYear
)
listing.save()
print("saved listing")
request.POST Output: propertyType : 1 price : 443 roomsTotal : 44 Bathrooms : 5454 bedrooms : 44 Receptionrooms : 55 livingArea : 45 lotSize : 4334 unitType : 2 yearBuilt : 11 hoaPrice : groundTankSize : garageSize : homeDescription : terms : on
When you press the send button, the form refresh without showing verification messages so that it is supposed to not respond to the wrong information
<div class="md-form mb-5">
<input type='text' placeholder='حدد السعر الخاص بك' id='price' name='price' class='form-control'/>
<label for="price" class="">السعر</label>
{{ form.price.errors }}
</div>
Thanking your cooperation
add {% csrf_token %} before form.
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>

Rendering a ManyToMany Field

I'm trying to display a manytomany field in my template, but all I get is a blank...I'm displaying it as below:
{% for vehicle in vehicle.features.features %}
<li>vehicle.features</li>
{% endfor %}
My model is as follows:
class Vehicle(models.Model):
stock_number = models.CharField(max_length=6, blank=False)
vin = models.CharField(max_length=17, blank=False)
common_vehicle = models.ForeignKey(CommonVehicle)
exterior_colour = models.ForeignKey(ExteriorColour)
interior_colour = models.ForeignKey(InteriorColour)
interior_type = models.ForeignKey(InteriorType)
odometer_unit = models.ForeignKey(OdometerUnit)
status = models.ForeignKey(Status)
odometer_reading = models.PositiveIntegerField()
selling_price = models.PositiveIntegerField()
purchase_date = models.DateField()
sales_description = models.CharField(max_length=60, blank=False)
feature_sets = models.ManyToManyField(FeatureSet, blank=True)
features = models.ManyToManyField(Feature, blank=True)
def __unicode__(self):
return self.stock_number
The classes I'm linking to are:
class Feature(models.Model):
name = models.CharField(max_length=32)
type = models.ForeignKey(FeatureType)
def __unicode__(self):
return self.name
class FeatureSet(models.Model):
name = models.CharField(max_length=12)
features = models.ManyToManyField(Feature)
def __unicode__(self):
return self.name
Use this:
{% for feature in vehicle.features.all %}
<li>{{ feature }}</li>
{% endfor %}