Я хочу изменить виджет поля «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']
раскрывающийся список:
Я пробовал играть с синтаксисом, пытаясь обновить виджет в метаклассе, в основном я столкнулся с синтаксическими ошибками, и мне не удалось найти примеры этого конкретного случая после некоторых поисков в Google.
Понимание и объяснения очень приветствуются и ценятся.
РЕДАКТИРОВАТЬ:
Теперь я получаю сообщение об ошибке: ValueError: invalid literal for int() with base 10: 'inbox'
Класс UpdateView:
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 = '[email protected]'
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>
URL.py:
path('ST_update/<pk>',SafeTransUpdateView.as_view(),name='ST_update'),
Я хотел бы знать, почему сейчас возникает эта ошибка: ValueError: неверный литерал для int() с базой 10: 'inbox'. Любая информация очень ценится.
clean_trans_recipient
в форме, которая сопоставляет данные с действительным экземпляромCustomUser
. - person Willem Van Onsem   schedule 30.08.2018