Django saving to Foreign field - python

I'm trying to save an Item based on the Foreign Key Primary Key for topCategory and middleCategory.
models.py
class MiddleCategory(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
def __str__(self):
return self.title
class TopCategory(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
middleCategory = models.ManyToManyField(MiddleCategory)
def __str__(self):
return self.title
# Item
class Product(models.Model):
title = models.CharField(max_length=500, db_index=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
brand = models.CharField(max_length=100)
# brand_id = models.IntegerField()
retailer = models.CharField(max_length=255)
image = models.CharField(max_length=1000)
url = models.URLField(max_length=800, unique=True, default='')
model_numbers = models.BigIntegerField(default=0)
description = models.CharField(max_length=500)
featured = models.CharField(max_length=255, db_index=True, default='NO')
timestamp = models.DateTimeField(auto_now=True)
topCategory = models.ForeignKey(TopCategory)
middleCategory = models.ForeignKey(MiddleCategory)
def __str__(self):
return self.title
In my script I'm saving like this:
Product(title=title,
price=price,
brand=brand,
retailer=retailer,
image=image,
url=url,
description=description,
midCategory=midCategory,
topCategory=topCategory
).save()
This is the error I am getting:
ValueError: Cannot assign "'1'": "Product.topCategory" must be a "TopCategory" instance.

You can get instance of TopCategory
instance = TopCategory.objects.get(id=topCategory)
then
Product(title=title,
price=price,
brand=brand,
retailer=retailer,
image=image,
url=url,
description=description,
midCategory=midCategory,
topCategory=instance
).save()

Related

How to do auto assign in django

I am working on a django project. where there's two table one is developer table and another one is Jira table. developer table and jira table are connected with m2m relation.
here's my model.py
class developer(models.Model):
Developer_Name = models.CharField(max_length=100, unique=True)
Role = models.CharField(max_length=500)
Level = models.CharField(max_length=30)
Expertise = models.CharField(max_length=200)
Availability_Hours = models.CharField(max_length=500)
def __str__(self):
return self.Developer_Name
class jira(models.Model):
Jira_ID = models.CharField(max_length=100, blank=True)
Jira_Story = models.CharField(max_length=500)
Short_Description = models.CharField(max_length=500)
Story_Points = models.CharField(max_length=30)
Sprint = models.CharField(max_length=200)
DX4C_Object = models.CharField(max_length=500)
Developer = models.ManyToManyField(developer)
Sandbox = models.ForeignKey(environments, on_delete=models.CASCADE, limit_choices_to={'Mainline': None},blank=True, null=True)
def developer_assigned(self):
return ",".join([str(p) for p in self.Developer.all()])
Now my query is how to set a rule where if Dx4c object is changing then automatically one developer will assign based on the rule?
here's my view.py
def dependency_management(request):
jira_story = jira.objects.all()
return render(request, 'hello/Dependency_Management.html', {'JIRA': jira_story})
I want to make that dynamic. I mean if everytime I add any new DX4C object then without the code change that particular developer will assign based on the rule
Something like this:
class Developer(models.Model):
name = models.CharField(max_length=100, unique=True)
role = models.CharField(max_length=500)
level = models.CharField(max_length=30)
expertise = models.CharField(max_length=200)
availability_hours = models.CharField(max_length=500)
def __str__(self):
return self.name
class Jira(models.Model):
Jira_ID = models.CharField(max_length=100, blank=True)
story = models.CharField(max_length=500)
story_points = models.CharField(max_length=30)
sprint = models.CharField(max_length=200)
DX4C_Object = models.CharField(max_length=500)
developers = models.ManyToManyField(developer)
sandbox = models.ForeignKey(
environments,
on_delete=models.CASCADE,
limit_choices_to={'Mainline': None},
blank=True, null=True,
)
def developer_assigned(self):
return ",".join(self.developers.values_list('name', flat=True))
def save(self, *args, **kwargs):
if pk := getattr(self, 'id', 0):
old_value = self.__class__.objects.get(id=pk).DX4C_Object
super().save(*args, **kwargs)
if pk and self.DX4C_Object != old_value:
# do sth

While defining method for autosaving in CreateView for ManyToMany field Error shows

I have three Models, in third models Foreign Key and ManyToMany fields are linked, which are:
Personal_info Models.py
class Personal_info(models.Model):
gen_choices = (
("पुरुष", "पुरूष"),
("महिला", "महिला"),
("तेस्रो", "तेस्रो"),
)
pinfo_id = models.AutoField(primary_key=True)
userid = models.OneToOneField(User, on_delete=models.CASCADE)
nfullname = models.CharField(validators=[max_len_check], max_length=128)
efullname = models.CharField(validators=[max_len_check], max_length=128)
dob_ad = models.DateField()
dob_bs = models.DateField()
gender = models.CharField(max_length=6, choices=gen_choices)
citizen_no = models.CharField(max_length=56)
cissue_dist = models.ForeignKey(District, on_delete=models.CASCADE)
cissue_date = models.DateField()
language = models.CharField(max_length=56)
p_district = models.CharField(max_length=56)
p_vdc = models.CharField(max_length=56)
p_ward = models.CharField(max_length=2)
p_city = models.CharField(max_length=56)
t_district = models.CharField(max_length=56)
t_vdc = models.CharField(max_length=59)
t_ward = models.CharField(max_length=2)
t_city = models.CharField(max_length=56)
telephone = models.BigIntegerField(null=True, blank=True)
mobile = models.BigIntegerField()
mother_name = models.CharField(validators=[max_len_check], max_length=128)
mother_cit = models.CharField(max_length=10, null=True)
father_name = models.CharField(validators=[max_len_check], max_length=128)
father_cit = models.CharField(max_length=10, null=True)
gfather_name = models.CharField(validators=[max_len_check], max_length=128)
gfather_cit = models.CharField(max_length=10, null=True)
spose_name = models.CharField(validators=[max_len_check], max_length=128, null=True)
spose_cit = models.CharField(max_length=10, null=True, blank=True)
image = models.FileField(upload_to="photos/", null=True, blank=True)
cit_image = models.FileField(upload_to="citizens/")
inclu_image = models.FileField(upload_to="inclusions/", null=True)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
def __str__(self):
return str(self.efullname)
Educational Models.py
class Education(models.Model):
edu_id = models.AutoField(primary_key=True)
userid = models.ForeignKey(User, on_delete=models.CASCADE)
institute = models.CharField(max_length=255, validators=[max_len_check])
board = models.CharField(max_length=128, validators=[max_len_check1])
pexam = models.CharField(max_length=16, choices=exam_choices)
faculty = models.CharField(max_length=16, choices=fac_choices)
division = models.CharField(max_length=16, validators=[max_len_check2])
tmarks = models.IntegerField()
percent = models.FloatField(null=True, blank=True)
mainsub = models.CharField(max_length=16, validators=[max_len_check2])
image = models.FileField(upload_to="educations/", null=True, blank=True)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
def __str__(self):
return str(self.userid)
V_applied models.py
class V_applied(models.Model):
appNo = models.IntegerField(null=True, blank=True, default=add_one)
p_srlno = models.IntegerField(blank=True, null=0, default=0)
userid = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Vacancy,on_delete=models.CASCADE)
inclusive = models.ManyToManyField(Inclusive)
bank = models.CharField(max_length=128)
v_no = models.CharField(max_length=32, validators=[max_len_check1])
dep_date = models.DateField()
ser_fee = models.IntegerField()
image = models.FileField(upload_to="vouchers/")
personal_info = models.ForeignKey(Personal_info, on_delete=models.CASCADE, blank=True)
education = models.ManyToManyField(Education, blank=True, default=0)
active = models.BooleanField(default=True)
status = models.CharField(max_length=10, validators=[max_len_check], default="Pending")
remarks = models.CharField(max_length=56, validators=[max_len_check1], default="Pending")
comment = models.CharField(max_length=128, validators=[max_len_check2], blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
#property
def per_info(self):
return (self.personal_info.efullname, self.personal_info.gender, )
'''
def __str__(self):
return str(self.userid) + ':' + str(self.post)
Here I want to make auto save method in CreateView for ForeignKey & ManyToMany fields of V_applied models, for this I tried views.py as below:
#method_decorator(login_required(login_url='login'), name='dispatch')
class v_appliedadd(CreateView):
form_class = V_appliedForm
template_name = 'v_applied/v_applied_form.html'
success_url = '/v_applied/vapp_details/'
def form_valid(self, form):
form.instance.userid = self.request.user
form.instance.personal_info = Personal_info.objects.get(userid=self.request.user)
educationall = Education.objects.filter(userid=self.request.user)
for edu in educationall:
form.instance.education.add(edu)
return super().form_valid(form)
While saving data Error display like this:
ValueError at /v_applied/v_appliedadd/
"<V_applied: testuser>" needs to have a value for field "id" before this many-to-many relationship can be used.
Request Method: POST
Request URL: http://localhost:8000/v_applied/v_appliedadd/
Django Version: 3.0.8
Exception Type: ValueError
Exception Value:
"<V_applied: testuser>" needs to have a value for field "id" before this many-to-many relationship can be used.
Exception Location: C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related_descriptors.py in __init__, line 846
Python Executable: C:\Users\User\AppData\Local\Programs\Python\Python38\python.exe
Python Version: 3.8.1
Python Path:
['D:\\DjangoProject\\app_epf',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\lib',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38',
'C:\\Users\\User\\AppData\\Roaming\\Python\\Python38\\site-packages',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages']
Server time: Mon, 14 Sep 2020 23:09:21 +0545
I am new in python-django, please help me how to solve it.
form.instance.userid = self.request.user
form.instance.personal_info = Personal_info.objects.get(userid=self.request.user)
instance_from = form.save()
educationall = Education.objects.filter(userid=self.request.user)
for edu in educationall:
instance_edu = Education.objects.get(pk=edu.pk)
instance_from.education.add(instance_edu)
instance_from.save()
return super().form_valid(form)

How to link a select category from template to django model object?

I have a many to many relationship in my product model (category field). I am able to display the category data in a select box which is a multiple selection. What I want to do is have the user select one or more categories from the template and then save the data in my product model. Here is my code:
if request.method =='POST':
print ('entered')
name = request.POST['name']
brand = request.POST['brand']
sku = request.POST['sku']
price = request.POST['price']
quantity = request.POST['quantity']
description = request.POST['description']
imageurls = request.POST['urls']
print('imageurls',imageurls)
categorylist = request.POST['categories']
print('categorylist',categorylist)
categories = re.findall(r"[\w']+", categorylist)
print categories
imageurls = imageurls.split('~')
print('iageurls',imageurls)
for x in categories:
categoryobj = Category.objects.filter(name=x).values()
_id = categoryobj.id
print('_id',_id)
print ('categoryobj',categoryobj)
# Product.objects.create(name=name,sku=sku,brand=brand,price=price,quantity=quantity,description=description,imageurls=imageurls,categories=categoryobj)
return HttpResponse('success')
models.py
class Category(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True,
help_text='Unique value for product page URL, created from name.')
description = models.TextField()
is_active = models.BooleanField(default=True)
meta_keywords = models.CharField("Meta Keywords", max_length=255,
help_text='Comma-delimited set of SEO keywords for meta tag')
meta_description = models.CharField("Meta Description", max_length=255,
help_text='Content for description meta tag')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('catalog:categories', kwargs={'category_slug': self.slug})
class Meta:
ordering = ['-created_at']
verbose_name_plural = 'Categories'
class Product(models.Model):
name = models.CharField(max_length=255, unique=True)
slug = models.SlugField(max_length=255, unique=True,
help_text='Unique value for product page URL, created from name.')
brand = models.CharField(max_length=50)
sku = models.CharField(max_length=50)
price = models.DecimalField(max_digits=9, decimal_places=2)
old_price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, default=0.00)
thumbnail = models.FileField(upload_to='static/images/products/thumbnails')
imageurls = models.CharField(max_length=1000)
is_active = models.BooleanField(default=True)
is_bestseller = models.BooleanField(default=False)
is_featured = models.BooleanField(default=False)
quantity = models.IntegerField()
description = models.TextField()
meta_keywords = models.CharField(max_length=255, help_text='Comma-delimited set of SEO keywords for meta tag')
meta_description = models.CharField(max_length=255, help_text='Content for description meta tag')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
categories = models.ManyToManyField(Category)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('catalog:products', kwargs={'product_slug': self.slug})
def sale_price(self):
if self.old_price > self.price:
return self.price
else:
return None
class Meta:
ordering = ['-created_at']
You should use Django ModelForms. So you only need to check if form.is_valid() and then do form.save().
Save method authomatically creates a new object for you.
Let me know if this works!

Can't create table in django database

Hello guys I am trying to create table in django database or in other word I am trying to syncdb but here is the error I encounter
-bash-3.2$ ~/html/ENV/bin/python2.7 manage.py syncdb
Creating tables ...
Creating table red_carpet_contactus
ValueError: The database backend does not accept 0 as a value for AutoField.
and here is the models file
from django.db import models
#from django.contrib.auth.models import User
class Page (models.Model):
Info= models.TextField()
page_name=models.CharField(max_length=100)
def __unicode__(self):
return u"%s" % self.page_name
class category(models.Model):
category_name = models.CharField(max_length=255)
def __unicode__(self):
return u"%s" %(self.category_name)
class contactus(models.Model):
PageName = models.CharField(max_length=255)
Phone = models.CharField(max_length=255)
Mob = models.CharField(max_length=255)
Address = models.CharField(max_length=255)
Fax = models.CharField(max_length=255)
Email = models.CharField(max_length=255)
def __unicode__(self):
return u"%s" %(self.page_name)
class gallery(models.Model):
title = models.CharField(max_length=200, blank=True, null=True)
Description = models.CharField(max_length=200, blank=True, null=True)
picture = models.FileField(upload_to='photos/')
thumbnail = models.FileField(upload_to='thumbnail/', blank=True, null=True)
def __unicode__(self):
return u"%s" % self.picture.url
class images(models.Model):
image = models.FileField(upload_to='images/')
#addition of the main page logo
class Main_page_img(models.Model):
logo = models.FileField(upload_to='images/')
def __unicode__(self):
return u"%s" % self.logo.url
class fields_class(models.Model):
data = models.TextField()
content = models.CharField(max_length=150)
def __unicode__(self):
return u"%s" % self.content
class trips_main_data(models.Model):
image = models.ManyToManyField(gallery)
short_description = models.CharField(max_length=255)
trip_name = models.CharField(max_length=255)
country_info = models.TextField(blank=True, null=True)
trip_info = models.TextField()
fields = models.ManyToManyField(fields_class,blank=True, null=True)
category = models.ForeignKey(category)
def __unicode__(self):
return u"%s" % self.trip_name
So would u suggest me guys to how to solve this problem??

how to add photo

I have a simple model, witch is used as a form .
class Test(models.Model):
name = models.CharField(max_length=100, unique=True, db_index=True)
location = models.CharField(max_length=300)
details = models.TextField()
def __unicode__(self):
return self.image.name
I would like to add the following class Album as a foreign key to Test :
class Album(models.Model):
title = models.CharField(max_length=60)
public = models.BooleanField(default=False)
def __unicode__(self):
return self.title
class Tag(models.Model):
tag = models.CharField(max_length=50)
def __unicode__(self):
return self.tag
class Image(models.Model):
title = models.CharField(max_length=60, blank=True, null=True)
image = models.FileField(upload_to="images/")
tags = models.ManyToManyField(Tag, blank=True)
albums = models.ManyToManyField(Album, blank=True)
created = models.DateTimeField(auto_now_add=True)
rating = models.IntegerField(default=50)
width = models.IntegerField(blank=True, null=True)
height = models.IntegerField(blank=True, null=True)
user = models.ForeignKey(User, null=True, blank=True)
def __unicode__(self):
return self.image.name
Questions:
How to add class Album as a foreigh key to class Test?
How to put this relation on the form? - e.g. user is selecting multiple images for uploads wich results in unique Album related to Test class.
Do you mean something like this for the foreign-key
class Test(models.Model):
name = models.CharField(max_length=100, unique=True, db_index=True)
location = models.CharField(max_length=300)
details = models.TextField()
album = models.ForeignKey(Album, null=True, blank=True)
def __unicode__(self):
return self.name

Categories

Resources