提交表单Django时参考当前模型

时间:2018-11-16 10:45:30

标签: python django django-forms

views.py

form = StudentTaskForm(request.POST or None, request.FILES or None)

if form.is_valid():
    form.instance.user = User.objects.get(id=request.user.id)

    obj = form.save(commit=False)
    obj.student = request.user
    obj.todo = qs
    obj.level = instance
    obj.save()



ImageFormSet = modelformset_factory(Images,
                                        form=ImageForm,min_num=0,
                                 max_num=3,  validate_min=True,extra=3)

if request.method == 'POST':
    formset = ImageFormSet(request.POST, request.FILES,
                           queryset=Images.objects.none())
    if formset.is_valid():
       for form in formset.cleaned_data:
         try:
          image = form['image']

          Images.objects.create(post=todo[0],image=image)
         except KeyError:
             pass
       return redirect('student:dashboard')
else:
    formset = ImageFormSet(queryset=Images.objects.none())

forms.py:

class StudentTaskForm(forms.ModelForm):
 title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form- 
 control',' type': "text",'placeholder':'Enter Title'}))
 content = forms.CharField(widget=SummernoteWidget())


 class Meta:
    model = Task
    fields = [
        'title',
        'content',

    ]
    widgets = {
        'content': SummernoteWidget(),
    }

 def clean_object(self):
    instance = self.instance

class ImageForm(forms.ModelForm):
 image = forms.ImageField(label='Image')
 class Meta:
    model = Images
    fields = ('image', )

我使用表单集保存图像。一个任务最多可以包含三张图像。

在models.py中,我有:

 class Task(models.Model):
  level = models.ForeignKey(Level, on_delete=models.CASCADE)
  todo = models.ForeignKey(ToDo, 
  on_delete=models.CASCADE,related_name='todo')
  student = models.ForeignKey(User, on_delete=models.CASCADE)
  title = models.CharField(max_length=150)
  content = models.TextField()
  timestamp = models.TimeField(auto_now=True)
  datestamp = models.DateField( auto_now=True)
  like = 
  models.ManyToManyField(User,related_name='user_likes',blank=True)
  is_verified=models.BooleanField(default=False,blank=True)
   def __str__(self):
     return self.title

   def get_absolute_url(self):
     return reverse('student:dashboard')
   objects = PostManager()

   @property
    def comments(self):
     instance = self
     qs = Comment.objects.filter_by_instance(instance)
     return qs

   @property
     def get_content_type(self):
     instance = self
     content_type = 
     ContentType.objects.get_for_model(instance.__class__)
    return content_type


 class Images(models.Model):
  post = models.ForeignKey(Task, 
  default=None,on_delete=models.CASCADE)
  image = models.ImageField(verbose_name='Image',blank=True)

   def __str__(self):
     return self.post.title

我正在创建另一个模型来保存属于特定任务的图像 提交表单时如何定位帖子?

Images.objects.create(post=todo[0],image=image)

我很困惑在post =中输入什么?通过模型的定义,帖子是任务对象的外键。我希望该任务对象成为当前从StudentTaskForm提交表单模型的模型。

1 个答案:

答案 0 :(得分:1)

您应该使用CLICK TO SEE THE ACTIVITY WHERE THE DOWNLOAD URL OF THE IMAGE UPLOADED TO THE FIREBASE STORAGE IS REQUIRED.,它将为您处理此问题。

ImageFormSet = inlineformset_factory(Task, Images,
                                     form=ImageForm, min_num=0,
                                     max_num=3, validate_min=True, extra=3)

formset = ImageFormSet(request.POST, request.FILES, instance=obj)
if formset.is_valid():
    formset.save()

这里根本不需要迭代。