Забыл прикрепить код.
views.py
def image_new(request):
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
image = form.save(commit=False)
image.user = request.user
image.published_date = timezone.now()
image.save()
return redirect('image_view')
else:
form = ImageForm()
return render(request, 'blog/image_edit.html', {'form':form})
forms.py
class ImageForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request',None)
return super(ImageForm, self).__init__(*args,**kwargs)
def save(self, *args, **kwargs):
kwargs['commit']=False
pic = super(ImageForm, self).save(*args, **kwargs)
if self.request:
pic.current_user = self.request.user
pic.save()
return pic
class Meta:
model = Image
fields = ['title', 'image']
Отдельно по поводу модели.
def user_directory_path(instance, filename):
return 'blog/{0}/images'.format(instance.user.username)
class Image(models.Model):
user = models.ForeignKey('auth.User')
title = models.CharField(max_length = 200)
current_user = User.objects.get(pk=2)
folder_upload = path.join('blog',current_user.username,'images')
image = models.ImageField(upload_to=folder_upload)
published_date = models.DateTimeField(blank=True, null=True)
created_date = models.DateTimeField(default=timezone.now)
Если в image брать для поля загрузки folder_upload, появляется указанная выше IntegrityError, а если user_directory_path, то выдает следующее:
RelatedObjectDoesNotExist at /image/new/
Image has no user.
Updated 15 Dec. 2016, 15:42 by aigin95.