将模型表单字段更改为文本输入小部件
Change model form field to text input widget
我想将 'trans_recipient' 字段小部件从下拉列表更改为文本输入字段。在大的情况下
我尝试了以下方法:
class SafeTransactionForm(forms.ModelForm):
''' SafeTranSactionForm '''
trans_recipient = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
class Meta:
model = SafeTransaction
fields = [ 'trans_recipient',
'subject',
'arbitrator_name',
'payment_condition',
'amount_to_pay']
产生这个:
虽然小部件本身已经改变,但实际上尝试使用它会产生这样的值错误:
没有我错误的一行更改小部件的尝试:
class SafeTransactionForm(forms.ModelForm):
''' SafeTranSactionForm '''
class Meta:
model = SafeTransaction
fields = [ 'trans_recipient',
'subject',
'arbitrator_name',
'payment_condition',
'amount_to_pay']
下拉菜单:
我试过语法,尝试更新元中的小部件 class,我大多以语法错误告终,而且我无法找到这个特定的示例经过一些 Google 搜索后的情况。
非常欢迎和赞赏您的见解和解释。
编辑:
现在我收到一个错误:ValueError: invalid literal for int() with base 10: 'inbox'
堆栈跟踪:
更新视图 class :
class SafeTransUpdateView(UpdateView):
'''
This view lets the user Update a SafeTransaction receipt
then send an automatic email to the email address
'''
form_class = SafeTransactionForm
model = SafeTransaction
template_name = "myInbox/safeTrans_update.html"
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(SafeTransUpdateView, self).__init__(*args, **kwargs)
def form_valid(self, form):
trans = form.save(commit=False)
trans.save()
### Send an email to the user upon transaction update.
usr_obj = User.objects.get(customuser=trans.trans_recipient)
user_mail = usr_obj.email
from_email = 'timi.ogunkeye@gmail.com'
contents = "This transaction [ " +trans.payment_condition+" ] has been updated !"
email_subject = 'Transaction Update !'
try:
send_mail(email_subject, contents, from_email, [user_mail], fail_silently=False)
pass
except:
pass
else:
pass
return HttpResponseRedirect('inbox')
我的更新表格:
class SafeTransactionForm(forms.ModelForm):
''' SafeTranSactionForm '''
# trans_recipient = forms.CharField(widget=forms.TextInput(attrs={'class':'special'}))
trans_recipient = forms.ModelChoiceField(queryset=CustomUser.objects.all(),
widget=forms.TextInput(attrs={'value':"username"}), to_field_name="username")
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']
safeTrans_update.html :
<h1>TRANSACTION UPDATE: </h1>
<form action="{% url 'ST_update' object.pk %}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Confirm Update" />
</form>
urls.py:
path('ST_update/<pk>',SafeTransUpdateView.as_view(),name='ST_update'),
我想知道为什么现在会出现此错误:ValueError: invalid literal for int() with base 10: 'inbox'。非常感谢任何信息。
好吧,问题是 Django 不知道如何将表单字段中的数据 转换回模型的 trans_recipient
属性(应该是CustomUser
个实例)。
但是这没有问题:您可以执行 表单清理 ,然后编写自定义函数将字符串转换回 CustomUser
对象,例如:
class SafeTransactionForm(forms.ModelForm):
''' SafeTranSactionForm '''
trans_recipient = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
def <b>clean_trans_recipient</b>(self):
data = self.cleaned_data['recipients']
try:
return CustomUser.objects.get(username=data)
except CustomerUser.DoesNotExist:
raise forms.ValidationError("No user with this username exists")
class Meta:
model = SafeTransaction
fields = [ 'trans_recipient', 'subject', 'arbitrator_name',
'payment_condition', 'amount_to_pay' ]
尽管您可能需要对 CustomUser
提取进行一些调整。因此,我们旨在获取诸如 CustomUser
和 return 之类的内容。如果不存在这样的 CustomUser
,那么我们提出 ValidationError
.
我想将 'trans_recipient' 字段小部件从下拉列表更改为文本输入字段。在大的情况下
我尝试了以下方法:
class SafeTransactionForm(forms.ModelForm):
''' SafeTranSactionForm '''
trans_recipient = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
class Meta:
model = SafeTransaction
fields = [ 'trans_recipient',
'subject',
'arbitrator_name',
'payment_condition',
'amount_to_pay']
产生这个:
虽然小部件本身已经改变,但实际上尝试使用它会产生这样的值错误:
没有我错误的一行更改小部件的尝试:
class SafeTransactionForm(forms.ModelForm):
''' SafeTranSactionForm '''
class Meta:
model = SafeTransaction
fields = [ 'trans_recipient',
'subject',
'arbitrator_name',
'payment_condition',
'amount_to_pay']
下拉菜单:
我试过语法,尝试更新元中的小部件 class,我大多以语法错误告终,而且我无法找到这个特定的示例经过一些 Google 搜索后的情况。
非常欢迎和赞赏您的见解和解释。
编辑:
现在我收到一个错误:ValueError: invalid literal for int() with base 10: 'inbox'
堆栈跟踪:
更新视图 class :
class SafeTransUpdateView(UpdateView):
'''
This view lets the user Update a SafeTransaction receipt
then send an automatic email to the email address
'''
form_class = SafeTransactionForm
model = SafeTransaction
template_name = "myInbox/safeTrans_update.html"
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(SafeTransUpdateView, self).__init__(*args, **kwargs)
def form_valid(self, form):
trans = form.save(commit=False)
trans.save()
### Send an email to the user upon transaction update.
usr_obj = User.objects.get(customuser=trans.trans_recipient)
user_mail = usr_obj.email
from_email = 'timi.ogunkeye@gmail.com'
contents = "This transaction [ " +trans.payment_condition+" ] has been updated !"
email_subject = 'Transaction Update !'
try:
send_mail(email_subject, contents, from_email, [user_mail], fail_silently=False)
pass
except:
pass
else:
pass
return HttpResponseRedirect('inbox')
我的更新表格:
class SafeTransactionForm(forms.ModelForm):
''' SafeTranSactionForm '''
# trans_recipient = forms.CharField(widget=forms.TextInput(attrs={'class':'special'}))
trans_recipient = forms.ModelChoiceField(queryset=CustomUser.objects.all(),
widget=forms.TextInput(attrs={'value':"username"}), to_field_name="username")
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']
safeTrans_update.html :
<h1>TRANSACTION UPDATE: </h1>
<form action="{% url 'ST_update' object.pk %}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Confirm Update" />
</form>
urls.py:
path('ST_update/<pk>',SafeTransUpdateView.as_view(),name='ST_update'),
我想知道为什么现在会出现此错误:ValueError: invalid literal for int() with base 10: 'inbox'。非常感谢任何信息。
好吧,问题是 Django 不知道如何将表单字段中的数据 转换回模型的 trans_recipient
属性(应该是CustomUser
个实例)。
但是这没有问题:您可以执行 表单清理 ,然后编写自定义函数将字符串转换回 CustomUser
对象,例如:
class SafeTransactionForm(forms.ModelForm):
''' SafeTranSactionForm '''
trans_recipient = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
def <b>clean_trans_recipient</b>(self):
data = self.cleaned_data['recipients']
try:
return CustomUser.objects.get(username=data)
except CustomerUser.DoesNotExist:
raise forms.ValidationError("No user with this username exists")
class Meta:
model = SafeTransaction
fields = [ 'trans_recipient', 'subject', 'arbitrator_name',
'payment_condition', 'amount_to_pay' ]
尽管您可能需要对 CustomUser
提取进行一些调整。因此,我们旨在获取诸如 CustomUser
和 return 之类的内容。如果不存在这样的 CustomUser
,那么我们提出 ValidationError
.