How to save forms in django with foreign key - python

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")

Related

Check In System by input user data in Django

I trying to do a check In System where Students can do it themselves by inputting their ID's but I am really struggling.
Follow views, models, forms, and html
VIEW
class Attendance(CreateView):
template_name = 'homepage.html'
model = GetAttendance
fields = ['aluno']
success_msg = "Check In Succesfully"
def form_valid(self, form):
form.save()
success_msg = self.get_success_message(form.cleaned_data)
if success_msg:
messages.success(self.request, success_msg)
return super().form_valid(form)
def get_success_url(self):
return reverse('attendance:homepage')
def get_success_message(self, cleaned_data):
return self.success_msg % cleaned_data
MODELS
class Aluno(models.Model):
id = ShortUUIDField(primary_key=True, editable=False, alphabet="0123456789", length=5)
photo = models.ImageField(upload_to='photos/', default='static/images/defaultuser.jpeg', blank=True)
nome = models.CharField(max_length=255)
phone = models.CharField(max_length=255)
email = models.EmailField(max_length=255, unique=True)
location = models.ForeignKey(MasterUser, on_delete=models.CASCADE)
belt = models.CharField(max_length=255, choices=BELT)
stripe = models.CharField(max_length=255, choices=GRAU)
join_date = models.DateField(default=timezone.now)
last_graduation = models.DateField(default=timezone.now)
gender = models.CharField(max_length=255, choices=GENDER)
def __str__(self):
return self.nome
class GetAttendance(models.Model):
aluno = models.ForeignKey(Aluno, on_delete=models.CASCADE)
attendance = models.DateTimeField(default=timezone.now)
def __str__(self):
return str(self.aluno) + ' - ' + str(self.attendance)
That's views.py
My models.py
forms
html
check in page
Basically what I need is instead of having the form of a choice be able to input the student ID and run the model GetAttendance.

'QuerySet' object has no attribute 'save' Error Occurred

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

How to add manytomany relation in other class . In my case in InfoCreateView class

I am making a CV page,
I want to link my Skill, Language etc class(table) to Main Person table/class,
But for that, I need to submit skill table first because my person table contains the foreign key for skills.
But as per CV form name & personal info comes first.
Also, I can put the whole form on one page but I want to go to the next page for each sub information, so is it possible to pass the request data from one class-based view to another class-based view.
models.py
from django.db import models
from django.core.validators import MinLengthValidator
from django.conf import settings
import datetime
class Workexperience(models.Model):
work = models.CharField(null=True, blank=True,
max_length=256,
help_text='eg: Juniorengineer: at L&T ')
person = models.ForeignKey('Person', on_delete=models.CASCADE, blank=True, null=False, default=1 )
def __str__(self):
return self.work
class Education(models.Model):
school = models.CharField(max_length=200)
college = models.CharField(null=True, blank=True,max_length=200)
person = models.ForeignKey('Person', on_delete=models.CASCADE, blank=True, null=False, default=1 )
def __str__(self):
return self.school
class Skills(models.Model):
skill = models.CharField(
max_length=256,
help_text='Add skills sperated by commas eg: programming, Matlab')
person = models.ForeignKey('Person', on_delete=models.CASCADE, blank=True, null=False, default=1 )
def __str__(self):
return self.skill
class Languages(models.Model):
language = models.CharField(
max_length=256,
help_text='Add language sperated by commas eg: English, Gujarati')
person = models.ForeignKey('Person', on_delete=models.CASCADE, blank=True, null=False, default=1 )
def __str__(self):
return self.language
class Person(models.Model):
name = models.CharField(
max_length=100,
help_text='Enter a name (e.g. Harry Virani)',
validators=[MinLengthValidator(2, "It must be greater than 1 character")]
)
picture = models.BinaryField(null=True, blank=True, editable=True)
content_type = models.CharField(max_length=256, null=True, blank=True,
help_text='The MIMEType of the file')
profession = models.CharField(
max_length=100,
validators=[MinLengthValidator(2, "It must be greater than 1 character")]
)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default='')
address = models.CharField(max_length=256)
email = models.EmailField(max_length = 254)
phone = models.CharField(
max_length=15,
help_text='Enter a phone number like this (e.g. +91000000000)',
validators=[MinLengthValidator(10, "It must be greater than 10 character")] )
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
facebook = models.URLField(null=True, blank=True, max_length=200,
help_text='enter your facebook URL' )
instagram = models.URLField(null=True, blank=True, max_length=200,
help_text='enter your instagram link URL' )
linkedin = models.URLField(null=True, blank=True, max_length=200,
help_text='enter your Linked link URL' )
skill = models.ManyToManyField(Skills, related_name='skills', default=1)
language = models.ManyToManyField(Languages, related_name='languages', default=1)
edu = models.ManyToManyField(Education, default=1,related_name='edu' )
work = models.ManyToManyField(Workexperience,default=1, blank=True, related_name='works')
# Shows up in the admin list
def __str__(self):
return self.name
views.py
I want to save it in another class which is for creating skill & other models.
class PersonCreateView(LoginRequiredMixin, View):
template_name = 'MYP/form.html'
success_url = 'MYP:myp_create_info'
def get(self, request, pk=None):
personform = PersonForm()
ctx = { 'personform': personform}
return render(request, self.template_name, ctx)
def post(self, request, pk=None) :
# if 'personform' in request.POST:
personform = PersonForm(request.POST, request.FILES or None)
if not personform.is_valid():
ctx = {'personform': personform}
return render(request, self.template_name, ctx)
pform = personform.save(commit=False)
#adding onwer
pform.owner = self.request.user
pform.save()
return redirect(self.success_url, pform.id)
class InfoCreateView(LoginRequiredMixin, View):
template_name = 'MYP/form2.html'
success_url = reverse_lazy('MYP:all')
def get(self, request, pk):
person = get_object_or_404(Person,id=pk)
skill= SkillsForm()
skill_list = Skills.objects.filter(person=person)
ctx = { 'skill':skill, 'skill_list':skill_list }
return render(request, self.template_name, ctx)
def post(self, request, pk):
if 'skill' in request.POST:
skill = SkillsForm(request.POST or None)
if not skill.is_valid() :
ctx = { 'skill':skill}
return render(request, self.template_name, ctx)
person = get_object_or_404(Person,id=pk)
print(person)
skill = Skills(skill=request.POST['skill'], person=person)
skill.save()
print(skill.person)
return redirect('MYP:myp_create_info', pk=pk)
forms.py
class PersonForm(forms.ModelForm):
max_upload_limit = 2 * 1024 * 1024
max_upload_limit_text = naturalsize(max_upload_limit)
# Call this 'picture' so it gets copied from the form to the in-memory model
# It will not be the "bytes", it will be the "InMemoryUploadedFile"
# because we need to pull out things like content_type
picture = forms.FileField(required=False, label='File to Upload <= '+max_upload_limit_text)
upload_field_name = 'picture'
# Hint: this will need to be changed for use in the ads application :)
class Meta:
model = Person
fields = ['name', 'profession', 'picture', 'address', 'email', 'phone','facebook','linkedin','instagram'] # Picture is manual
# Validate the size of the picture
def clean(self) :
cleaned_data = super().clean()
pic = cleaned_data.get('picture')
if pic is None : return
if len(pic) > self.max_upload_limit:
self.add_error('picture', "File must be < "+self.max_upload_limit_text+" bytes")
# Convert uploaded File object to a picture
def save(self, commit=True) :
instance = super(PersonForm, self).save(commit=False)
# We only need to adjust picture if it is a freshly uploaded file
f = instance.picture # Make a copy
if isinstance(f, InMemoryUploadedFile): # Extract data from the form to the model
bytearr = f.read();
instance.content_type = f.content_type
instance.picture = bytearr # Overwrite with the actual image data
if commit:
instance.save()
return instance
class WorkexperienceForm(forms.ModelForm):
class Meta:
model = Workexperience
fields = ['work']
class EducationForm(forms.ModelForm):
class Meta:
model = Education
fields = ['school','college']
class SkillsForm(forms.ModelForm):
class Meta:
model = Skills
fields = ['skill']
class LanguagesForm(forms.ModelForm):
class Meta:
model = Languages
fields = ['language']
Ignore the rest of the code it is just for image handling....
This is what I want to do but I know it is the wrong format
I want to just add id for everything later.
In my opinion, your models are messed up. Here is how I would have write them :
class WorkExperience(models.Model):
work = models.CharField(
blank=True,
max_length=256,
help_text='eg: Juniorengineer: at L&T'
)
def __str__(self):
return self.work
class Education(models.Model):
school = models.CharField(max_length=200)
college = models.CharField(blank=True, max_length=200)
def __str__(self):
return self.school
class Skill(models.Model):
name = models.CharField(
max_length=256,
help_text='Add a skill name (eg: Programming)'
)
def __str__(self):
return self.name
class Language(models.Model):
name = models.CharField(
max_length=256,
help_text='Add a language name (eg: Gujarati)'
)
def __str__(self):
return self.name
class Person(models.Model):
name = models.CharField(
max_length=100,
help_text='Enter a name (e.g. Harry Virani)',
validators=[MinLengthValidator(2, "It must be greater than 1 character")]
)
# [...Other fields...]
skills = models.ManyToManyField(Skill, related_name='persons', blank=True)
languages = models.ManyToManyField(Language, related_name='persons', blank=True)
educations = models.ManyToManyField(Education, related_name='persons', blank=True)
work_experiences = models.ManyToManyField(WorkExperience, related_name='persons', blank=True)
def __str__(self):
return self.name
Then I need to see your forms.py to better understand how you handle it in your view.

IntegrityError at * UNIQUE constraint failed

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

image not saving on django models

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"

Categories

Resources