我正在尝试开发一个小应用,用户可以在登录后上传图片。我已使用ModelForm
生成上传图片及其说明的表单。 ArtWork
模型与User
模型具有外键关系。我从ModelForm中排除user
字段。现在我没有任何线索如何将登录用户以及表单数据保存到数据库中。提前谢谢。
这是我的ArtWork
模型
class Artwork(models.Model):
art_image = models.ImageField("Art Image", upload_to="images", blank=True,null=True)
art_name = models.CharField(max_length=100, blank=True,null=True)
user = models.ForeignKey(AuthUser, default=1)
def __unicode__(self):
return self.art_name
这是我的观点
class UploadArtworkView(FormView):
form_class = ArtworkForm
success_url = "/"
template_name = "artwork/upload.html"
def form_valid(self, form):
#artwork = Artwork(art_image= self.get_form_kwargs().get('files')['art_image'])
#print "Art name is" + form.post['art_name']
form.save()
print self.request.user.name
return super(UploadArtworkView,self).form_valid(form)
这是表格
from django.forms import ModelForm
from .models import Artwork
class ArtworkForm(ModelForm):
class Meta:
model = Artwork
fields = ['art_image','art_name']
答案 0 :(得分:1)
您的用例与Django文档中的this example非常相似。您已经意识到form_valid
是要覆盖的正确方法,因此您非常接近答案。诀窍是使用self.form.instance
访问对象,并设置用户:
def form_valid(self, form):
form.instance.user = self.request.user
return super(UploadArtworkView,self).form_valid(form)