此表单由通用视图更新:
models.py:
class CustomUser(User):
user_bio = models.TextField(blank=True, null=True)
birth_date = models.DateField(null=True, blank=True)
def __str__(self):
return self.username
class SafeTransaction(models.Model):
trans_recipient = models.ForeignKey(CustomUser, on_delete = models.CASCADE,related_name = 'trans_Recipient',null = True)
trans_recipient_email = models.CharField(max_length = 1000, blank=True, null=True)
trans_sender = models.ForeignKey(CustomUser, on_delete = models.CASCADE,related_name = 'safe_Transactions', null = True)
date = models.DateTimeField(auto_now_add=True, blank=True)
subject = models.CharField(max_length = 1000, blank = True)
#trans_type = models.CharField(choices=(1,'Buildingwork'))#DROPDOWN BOX
trans_unread = models.BooleanField(default = True)
arbitrator_name = models.CharField(max_length=1000,blank=True, null=True)
payment_condition = models.TextField(blank=True, null=True)
amount_to_pay = models.DecimalField(blank=True, null=True, max_digits=50, decimal_places=2)
is_finalised = models.BooleanField(default=False)
views.py:
class SafeTransUpdateView(UpdateView):
'''
This view lets the user Update a SafeTransaction receipt
'''
form_class = SafeTransactionForm
model = SafeTransaction
template_name = "myInbox/safeTrans_update.html"
forms.py:
class SafeTransactionForm(forms.ModelForm):
''' SafeTranSactionForm '''
#version one of trans recipient
trans_recipient = forms.ModelChoiceField(queryset=CustomUser.objects.all(), widget=forms.TextInput())
#version two of trans_recipient
#trans_recipient = forms.CharField(widget=forms.TextInput(attrs={'class':'special'}))
def clean_trans_recipient(self):
data = self.cleaned_data['trans_recipient']
try:
return CustomUser.objects.get(username=data)
except CustomUser.DoesNotExist:
raise forms.ValidationError("No user with this username exists")
class Meta:
model = SafeTransaction
fields = [ 'trans_recipient',
'trans_recipient_email',
'subject',
'arbitrator_name',
'payment_condition',
'amount_to_pay']
所以在表单中,我主要是试图从ChoiceField继承TextInput小部件。实际提交带有此版本的表格后:
trans_recipient = forms.ModelChoiceField(queryset=CustomUser.objects.all(), widget=forms.TextInput())
,我被告知输入的选项无效。
对于第二个版本:trans_recipient = forms.CharField(widget=forms.TextInput(attrs={'class':'special'}))
,在提交此表格时,第一个错误是:
之后,该项目实际上已更新!
我尝试了几种方法,但是由于它们似乎是最可行的,所以坚持使用这两种方法。我认为将trans_recipients保留为Django为ForeignKey model属性提供的默认下拉字段是没有意义的,因为它在庞大的用户群中很快会变得很笨拙。
我想知道一种方便的方法来使用TextInput小部件进行搜索,并在数据库中查询键入的术语,在这种情况下,请使用通用的UpdateView类更新Item。