Как поместить корректный ввод в виджет ModelChoiceField, который наследует виджет TextInput - PullRequest
0 голосов
/ 19 января 2019

Эта форма обновляется общим представлением:

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']

Поэтому в формах я в основном пытаюсь унаследовать виджет TextInput от ChoiceField.При фактической отправке формы с этой версией: trans_recipient = forms.ModelChoiceField(queryset=CustomUser.objects.all(), widget=forms.TextInput()) Мне говорят, что введенный мною выбор недействителен.

Что касается второй версии: trans_recipient = forms.CharField(widget=forms.TextInput(attrs={'class':'special'})), при отправке этой формы сначала возникает ошибка:

недопустимый литерал для int () с базой 10: «входящие»

После чего элемент фактически обновляется!

Я пробовал несколько подходов, но застрял наэти два, потому что они кажутся наиболее жизнеспособными.Я не думаю, что имеет смысл оставлять trans_recipients в качестве раскрывающегося поля по умолчанию, которое Django предоставляет для атрибута модели ForeignKey, поскольку это быстро станет непривлекательным с большой базой пользователей.

Я бы хотелзнать удобный способ поиска с помощью виджета TextInput и запрашивать в моей базе данных введенный термин, и в этом случае обновите элемент с помощью общего класса UpdateView.

...