使用ModelForm仅更新带有文本的字段

时间:2018-07-31 16:38:34

标签: python django

我有一个基于ModelForm的更新视图,我正在使用instance来更新当前行,但是问题是用户可能不需要更新所有字段。但是当表单保存数据时。它会保存所有内容,并为我提供空白字段(用户未填写)。这是我的代码:

forms.py

class EditYellowForm(forms.ModelForm):
    business_title = forms.CharField(required=False,
                                     widget=forms.TextInput(
                                         attrs={
                                             'placeholder': 'New Title',
                                             'style': 'width: 100%; max-width: 500px'
                                         }
                                     )
                                     )

    contact_address = forms.CharField(required=False,
                                      widget=forms.TextInput(
                                          attrs={
                                              'placeholder': 'New Address',
                                              'style': 'width: 100%; max-width: 500px'
                                          }
                                      )
                                      )

    class Meta:
        model = YellowPages
        fields = ['business_title', 'contact_address']

views.py

def yellow_edit(request, pk):
    current_yellow_ad = get_object_or_404(YellowPages, pk=pk)
    if request.method == "POST":
        edit_yellow_form = EditYellowForm(instance=current_yellow_ad, data=request.POST, files=request.FILES)
        if edit_yellow_form.is_valid():
            instance = edit_yellow_form.save(commit=False)
            instance.save()
            return redirect('yellow_pages')
    else:
        edit_yellow_form = EditYellowForm(instance=current_yellow_ad, data=request.POST, files=request.FILES)

    context = {
        'edit_yellow_form': edit_yellow_form,
        'current_yellow_ad': current_yellow_ad,
    }
    return render(request, 'yellow_pages/edit.html', context)

模型(如果需要):

class YellowPages(models.Model):
    type_of_business_chioces = (
        ('service', 'service '),
        ('product ', 'product '),
    )
    business_title = models.CharField(max_length=120)
    contact_address = models.CharField(max_length=120, blank=True, null=True)
    contact_number = models.IntegerField(blank=True, null=True)
    contact_email = models.EmailField(blank=True, null=True)
    website = models.CharField(validators=[URLValidator()], max_length=120, blank=True, null=True)
    image = models.ImageField(upload_to=content_file_name, blank=True, null=True)
    category = models.ForeignKey(YelllowPagesCategory, on_delete=CASCADE)
    tags = TaggableManager()
    owned = models.BooleanField(default=False)
    owner = models.EmailField(blank=True, null=True)
    otp = models.IntegerField(default=0, blank=True, null=True)
    is_active = models.BooleanField(default=True)

1 个答案:

答案 0 :(得分:3)

如果我理解正确,您只想更新表单中不为空的字段。因此,您可以使用update_fields参数。您应该将要更新的字段名称作为列表传递。这样的事情应该起作用:

    if edit_yellow_form.is_valid():
        instance = edit_yellow_form.save(commit=False)
        form_data = edit_yellow_form.cleaned_data
        fields_to_update = [field for field in form_data if form_data[field] != '']
        instance.save(update_fields=fields_to_update)
        return redirect('yellow_pages')