I am trying to create a django application to keep track of a product(product stock application).whenever I try to add new product ,I cannot add more than one product in the same category. It gives UNIQUE constraint failed error .
I want to add multiple products in same category.
models.py
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=100, blank=True, null=True)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=100)
slug = models.CharField(max_length=100)
price = models.DecimalField(max_digits=6, decimal_places=2)
quantity = models.IntegerField(null=True, blank=True)
category = models.ForeignKey(
Category, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Stock(models.Model):
sold_quantity = models.IntegerField(null=True, blank=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)
def __str__(self):
return self.product.name
Edit:
Views
def createProduct(request):
form = AddProductForm()
if request.method == 'POST':
form = AddProductForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
contex = {'form': form}
return render(request, 'stockmgmt/add_products.html', contex)
Forms.py
class AddProductForm(ModelForm):
class Meta:
model = Product
fields = '__all__'
Error Message
Related
i'm building a small webstore , in the product page i put the order form using FormMixin and TemplateView, when i submit the order i get a "Direct assignment to the forward side of a many-to-many set is prohibited. Use product.set() instead." error
Bellow you can check the code
Models.py
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=255, unique=True, )
description = models.TextField(max_length=1500)
class Meta:
verbose_name_plural = "categories"
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
nominal_price = models.PositiveIntegerField(verbose_name='prix normal',)
reduced_price = models.PositiveIntegerField(blank=True, null=True)
quantity = models.PositiveIntegerField(default=10)
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products')
photo = models.ImageField(upload_to="img/products/", default="img/products/user_default.png")
def __str__(self):
return self.name
class Customer(models.Model):
full_name = models.CharField(max_length=150)
address = models.CharField(max_length=1500, null=True)
phone = models.IntegerField()
city = models.CharField(max_length=100)
email = models.EmailField(null=True)
class Order (models.Model):
product = models.ManyToManyField(Product, through='OrderProduct')
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
class OrderProduct(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
Views.py
class ProductDetailView(FormMixin, TemplateView):
model = Product
template_name = 'product.html'
form_class = OrderForm
def get_success_url(self):
return reverse('index')
def post(self, request, *args, **kwargs):
context = self.get_context_data()
form = OrderForm(request.POST)
if context['form'].is_valid():
product = get_object_or_404(Product, name=self.kwargs['product_name'])
customer = form.save()
Order.objects.create(product=product, customer=customer)
return super(TemplateView, self)
def get_context_data(self, **kwargs):
context = super(ProductDetailView, self).get_context_data(**kwargs)
context['product'] = Product.objects.get(name=self.kwargs['product_name'])
context['form'] = self.get_form()
return context
urls.py
path('', views.ProductListView.as_view(), name='index'),
Did i missed something
For handling many-to-many relations, you cannot directly set the product from Order. Also you would need to create the order first before you can set or add a product:
order = Order.objects.create(customer=customer)
order.product.add(product)
I am a student studying Django. Currently, the member information has been entered in the Member table. I want to create Mypage so that member information registered in the Member table can be modified, and develop so that member information can be modified on Mypage. But while developing, I faced the following error: How can I solve this? Any help would be greatly appreciated.
Detail Error :
AttributeError at /mypage/mypage_modify/
'QuerySet' object has no attribute 'save'
Request Method: POST
Request URL: http://127.0.0.1:8000/mypage/mypage_modify/
Django Version: 3.1.5
Exception Type: AttributeError
Exception Value:
'QuerySet' object has no attribute 'save'
Exception Location: C:\zeronine_project\mypage\views.py, line 27, in mypage_modify
Python Executable: D:\anaconda3\envs\vnv_zn\python.exe
Python Version: 3.7.6
Python Path:
['C:\\zeronine_project',
'D:\\anaconda3\\envs\\vnv_zn\\python37.zip',
'D:\\anaconda3\\envs\\vnv_zn\\DLLs',
'D:\\anaconda3\\envs\\vnv_zn\\lib',
'D:\\anaconda3\\envs\\vnv_zn',
'D:\\anaconda3\\envs\\vnv_zn\\lib\\site-packages']
Server time: Thu, 08 Jul 2021 21:05:53 +0900
view.py
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from mypage.forms import *
from zeronine.models import *
# Create your views here.
def mypage_list(request):
categories = Category.objects.all()
return render(request, 'mypage/mypage_list.html', {'categories':categories})
def mypage_modify(request):
current_category = None
categories = Category.objects.all()
member = Member.objects.all()
if not request.user.is_authenticated:
return HttpResponseRedirect(reverse('zeronine:login'))
if request.method == "POST":
member.name = request.POST['name']
member.password = request.POST['password']
member.username = request.user
member.save()
return redirect('zeronine:post')
else:
memberForm = MemberForm
return render(request, 'mypage/mypage_modify.html', {'memberForm':memberForm, 'member':member, 'current_category': current_category, 'categories': categories})
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.urls import reverse
# 회원
class Member(AbstractUser):
username = models.CharField(primary_key=True, max_length=20, verbose_name='아이디')
name = models.CharField(max_length=20, verbose_name='이름', default='')
password = models.CharField(max_length=64, verbose_name='비밀번호')
phone = models.CharField(max_length=64, verbose_name='전화번호')
def __str__(self):
return self.username
class Meta:
verbose_name = ('Member')
verbose_name_plural = ('Members')
# 카테고리
class Category(models.Model):
category_code = models.AutoField(primary_key=True)
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, allow_unicode=True)
class Meta:
ordering =['category_code']
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('zeronine:product_in_category', args=[self.slug])
# 상품
class Product(models.Model):
product_code = models.AutoField(primary_key=True)
username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username')
category_code = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=False, allow_unicode=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
benefit = models.TextField()
detail = models.TextField()
target_price = models.IntegerField()
start_date = models.DateField()
due_date = models.DateField()
class Meta:
ordering = ['product_code']
index_together = [['product_code', 'slug']]
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('zeronine:product_detail', args=[self.product_code, self.slug])
class Post(models.Model):
post_code = models.AutoField(primary_key=True)
username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username')
title = models.CharField(max_length=64)
content = models.TextField()
register_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Meta:
ordering = ['register_date']
# 댓글(댓글코드, 게시글코드(fk), 아이디(fk), 내용, 등록날짜)
class Comment(models.Model):
comment_code = models.AutoField(primary_key=True)
post_code = models.ForeignKey(Post, on_delete=models.CASCADE, db_column='post_code')
username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username')
content = models.TextField()
register_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.content
class Meta:
ordering = ['register_date']
# Zzim 모델부터 새로 추가하려는 모델들 입니다.
# 찜하기(찜코드, 아이디(fk), 상품코드(fk))
class Zzim(models.Model):
zzim_code = models.AutoField(primary_key=True)
username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username')
product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')
def __str__(self):
return str(self.zzim_code)
# 상품이미지(이미지코드, 상품코드(fk), 이미지경로)
class Photo(models.Model):
photo_code = models.AutoField(primary_key=True)
product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')
photo = models.ImageField(upload_to="photos/%Y%m%d")
def __str__(self):
return str(self.photo_code)
class Meta:
ordering = ['photo_code']
# 옵션(옵션코드, 옵션명, 상품코드(fk))
class Option(models.Model):
option_code = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')
def __str__(self):
return self.name
# 옵션값(옵션값코드, 옵션값명, 옵션코드(fk), 상품코드(fk))
class Value(models.Model):
value_code = models.AutoField(primary_key=True)
option_code = models.ForeignKey(Option, on_delete=models.CASCADE, db_column='option_code')
product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')
name = models.CharField(max_length=32)
def __str__(self):
return self.name
# 옵션지정상품(옵션지정상품코드, 상품코드(fk), 가격, 참여수량)
class Designated(models.Model):
designated_code = models.AutoField(primary_key=True)
product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')
price = models.IntegerField()
rep_price = models.BooleanField(default=True)
class Meta:
ordering = ['designated_code']
def __str__(self):
return str(self.designated_code)
# 상품옵션구성(상품옵션구성코드, 옵션지정상품코드, 옵션값코드)
class Element(models.Model):
element_code = models.AutoField(primary_key=True)
designated_code = models.ForeignKey(Designated, on_delete=models.CASCADE, db_column='designated_code')
value_code = models.ForeignKey(Value, on_delete=models.CASCADE, db_column='value_code')
class Meta:
ordering = ['element_code']
def __str__(self):
return str(self.element_code)
# 참여(참여코드, 아이디(fk), 상품코드(fk), 수량)
class Join(models.Model):
join_code = models.AutoField(primary_key=True)
username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username')
product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')
part_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.join_code)
class Meta:
ordering = ['join_code']
#참여상세(참여상세코드, 수량, 가격, 참여코드, 옵션지정상품코드)
class JoinDetail(models.Model):
joindetail_code = models.AutoField(primary_key=True)
join_code = models.ForeignKey(Join, on_delete=models.CASCADE, db_column='join_code')
designated_code = models.ForeignKey(Designated, on_delete=models.CASCADE, null=True, blank=True, db_column='designated_code')
quantity = models.IntegerField()
price = models.IntegerField()
def __str__(self):
return str(self.joindetail_code)
class Meta:
ordering = ['joindetail_code']
You are not specifying a member object to update. member = Member.objects.all() will get a queryset of all the member objects in your database.
Try doing:
def mypage_modify(request):
current_category = None
categories = Category.objects.all()
member = Member.objects.all()
if not request.user.is_authenticated:
return HttpResponseRedirect(reverse('zeronine:login'))
if request.method == "POST":
member = Member.objects.get(name=request.POST['name']) #specifying the member
member.name = request.POST['name']
member.password = request.POST['password']
member.username = request.user
member.save()
return redirect('zeronine:post')
else:
memberForm = MemberForm
return render(request, 'mypage/mypage_modify.html', {'memberForm':memberForm, 'member':member, 'current_category': current_category, 'categories': categories})
Or if you are making a new member object then instead of member = Member.objects.get(name=request.POST['name'])
Do: member = Member()
EDIT:
Not sure why you'd want to do this in practise, but to change every member object in the database you'd do the following:
def mypage_modify(request):
current_category = None
categories = Category.objects.all()
member = Member.objects.all()
if not request.user.is_authenticated:
return HttpResponseRedirect(reverse('zeronine:login'))
if request.method == "POST":
for m in member:
m.name = request.POST['name']
m.password = request.POST['password']
m.username = request.user
m.save()
return redirect('zeronine:post')
What you're accessing with member = Member.objects.all() is a list of Member objects.
To get a desired member use
member = Member.objects.get()
or
member = Member.objects.filter()
In the latter, you'd also need to check
if member:
member = member.first()
Check
https://docs.djangoproject.com/en/3.2/ref/models/querysets/#filter
https://docs.djangoproject.com/en/3.2/ref/models/querysets/#get
I'm making a to-do list app and I'm trying to make the create page for an Item. Most of it works except that I don't get it to save in what Todo List to go and therefor get this error. 'Cannot assign "'Home'": "Item.todolist" must be a "TodoList" instance.'
This is my view:
def create_todo(request):
context = {"lists": TodoList.objects.filter(user=request.user)}
if request.method == "POST":
if request.POST.get("create"):
title = request.POST.get("item_title")
date_due = request.POST.get("item_date")
text = request.POST.get("item_note")
todolist = request.POST.get("todolist")
t = Item(
user=request.user,
todolist=todolist,
title=title,
date_due=date_due,
text=text,
complete=False,
)
t.save()
redirect("all-todos-view")
return render(request, "create_todo.html", context)
Here is my models.py:
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
class TodoList(models.Model):
name = models.CharField(max_length=50)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("all-todos-view")
class Item(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
todolist = models.ForeignKey(TodoList, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
date_due = models.DateTimeField(
auto_now=False, auto_now_add=False, blank=True, null=True
)
text = models.TextField(blank=True, null=True)
complete = models.BooleanField(blank=True, null=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("all-todos-view")
Try this way
t = Item( title=title,
date_due=date_due,
text=text,
complete=False,
)
t.save(commit=False)
t.user = request.user
t.todolist.name = todolist
t.save()
return redirect("all-todos-view")
I am working on an online-shop in django.
I have linked the order model with the cart model through ForeignKey which is further linked with products model through ForeignKey.
models.py:
class products(models.Model):
image = models.ImageField(upload_to='products/')
name = models.CharField(max_length=50)
slug = models.SlugField(blank=True, unique=True)
title = models.CharField(max_length=50)
price = models.FloatField()
def __str__(self):
return self.name
class cart(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
item = models.ForeignKey(products, on_delete=models.CASCADE) ###
slug = models.CharField(max_length=50, default='#')
quantity = models.IntegerField(default=1)
created_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'{self.quantity} of {self.item.name}'
def get_total(self):
total = self.item.price * self.quantity
floattotal = float("{0:.2f}".format(total))
return floattotal
class order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
item = models.ForeignKey(cart, on_delete=models.CASCADE) ###
slug = models.SlugField()
quantity = models.IntegerField()
created_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'{self.quantity} of {self.item.item__name}'
I wanted to create object of order as:
def order_view(request, slug):
cart_qs = cart.objects.filter(user=request.user, slug=slug)
cart_item = cart_qs[0]
order.objects.create(user=request.user, item=cart_item.item.name, slug=slug, quantity=cart_item.quantity) ####
It raises error as:
Cannot assign "'The latest one'": "order.item" must be a "cart" instance.
Why this error arises and how can I resolve this?
You are trying to assign string on Order instance creation where it's expecting a Cart instance. The error raised here:
item=cart_item.item.name
It should be simply:
item=cart_item
, because your model schema expect this:
item = models.ForeignKey(cart, on_delete=models.CASCADE) ###
I created an album with a photos as foreign key but somehow when i add a photo it does not save probably in my database or admin site
Here are my models:
class AlbumPluginModel(CMSPlugin):
name = models.CharField(max_length=255,
help_text=_('e.g: Zuerich city, or Zuerich Hoengg'))
slug = models.SlugField(_('Slug'), blank=True, null=True, unique=True, db_index=True)
description = HTMLField(blank=True, null=True)
cover_photo = models.ImageField(verbose_name=_('Add cover photo'), null=True, blank=True)
is_active = models.BooleanField(_('active'), blank=True)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
sort = models.IntegerField(_("Sort Order"), null=True, blank=True, default=0)
def __str__(self):
if self.name:
return u"File for %s" % self.name
else:
return u"%s" % self.name
def get_absolute_url(self):
return "/album_detail%i/" % self.id
class Meta:
ordering = ['sort']
verbose_name = "Album"
verbose_name_plural = "Albums"
class Photo(models.Model):
photo = models.ForeignKey(AlbumPluginModel, verbose_name=_('choose album'), null=True, blank=True)
image1 = models.ImageField(verbose_name=_('Photo'), null=True, blank=True, upload_to="/static/img/")
sort = models.IntegerField(_("Sort Order"), null=True, blank=True, default=0)
def __unicode__(self):
return u"%s" % self.image1
def __str__(self):
return u"%s" % self.image1
class Meta:
ordering = ['sort']
verbose_name = _("photo")
verbose_name_plural = _("Photos")
forms.py
class AlbumPluginForm(forms.ModelForm):
class Meta:
model = AlbumPluginModel
fields = ['name', 'description', 'cover_photo', 'is_active',]
class PhotoPluginForm(forms.ModelForm):
photo = forms.ModelChoiceField(label='select album',aqueryset=AlbumPluginModel.objects.all(), required=False)
class Meta:
model = Photo
fields = ('photo', 'image1', )
views.py
def add_photo(request, id=None, **kwargs):
if request.method == 'POST':
all_photos = Photo.objects.all
form = PhotoPluginForm(request.POST, request.FILES, initial={'photo': id})
template_name = 'photo_create.html'
context = {
"form": form,
"all_photos": all_photos,
}
if form.is_valid():
all_photos = form.save(commit=False),
form.save()
messages.success(request, "Photo was added.")
return redirect('/photos')
else:
print("error: form nicht valid")
return render(request, template_name, context)
You should add upload_to parameter for field in which you want to upload some file in server. In your case, in AlbumPluginModel your cover_photo will be
cover_photo = models.ImageField(verbose_name=_('Add cover photo'), null=True, blank=True, upload_to='path_where_you_want_to_save')
If you call save() with commit=False, then it will return an object that hasn’t yet been saved to the database. In this case, it’s up to you to call save() on the resulting model instance. You should change your view like this
all_photos = form.save(commit=False),
all_photos.save()
after a long try i finally found the answer:
in views.py
i chnaged this line from
form = PhotoPluginForm(request.POST or None)
to:
form = PhotoPluginForm(request.POST, request.FILES)
and in my template i forgot this:
enctype="multipart/form-data"