gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:43:42 26 4
gpt4 key购买 nike

我有一个基于 ModelForm 的更新 View ,我使用 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)

最佳答案

如果我理解正确的话,您只想更新表单中不为空的字段。所以你可以使用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')

关于python - 使用 ModelForm 仅更新带有文本的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51618219/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com