Ошибка Django при попытке добавить новые атрибуты HTML в форму модели

#django #django-forms

#django #django-forms

Вопрос:

У меня есть эта модель

  40 class Item(models.Model):
 41     event = models.ForeignKey(Event)
 42     name = models.CharField('Item Name', max_length=50 )
 43     description = models.CharField('Description', max_length=150, blank=True, null=True)
 44     quantity = models.IntegerField(blank=True, null=True)
 45     start = models.DateTimeField('Availability Start Date', blank=True, null=True)
 46     end = models.DateTimeField('Expiry Date', blank=True, null=True)
 47     cost_price = models.DecimalField('Cost Price Per Item', decimal_places=2, max_digits=10, blank=True, null=True)
 48     selling_price = models.DecimalField('Selling Price Per Item', decimal_places=2, max_digits=10, blank=True, null=True)
 49 
 50     def __unicode__(self):
 51         return u"%s" % self.name
  

И эта форма модели

  39 class ItemForm(forms.ModelForm):
 40     description = forms.CharField(label='Description', max_length=250, widget=forms.Textarea, required=False)
 41     image = forms.ImageField(label='Item Picture', max_length=50, required=False)
 42     start = forms.DateField(widget=SelectDateWidget, required=False)
 43     end = forms.DateField(widget=SelectDateWidget, required=False)
 55  
 56     class Meta:
 57         model = Item
 58         fields = ('image',
 59                   'name',
 60                   'description',
 61                   'quantity',
 62                   'start',
 63                   'end',
 64                   'cost_price',
 65                   'selling_price',
 66                   )
 67         widgets = {'cost_price': forms.TextInput(attrs={'onChange':'updateSellingPrice()'})}
  

Я пытаюсь добавить новый атрибут в cost_price поле, которое, в свою очередь, вызовет функцию js ниже:

   8 <script type="text/javascript">
  9     function updateSellingPrice() {
 10         $('#id_cost_price').change(function () {
 11             // get cost price
 12             var costPrice = $('id_cost_price').text();
 13             // set selling price
 14             $('$id_selling_price').val(costPrice);
 16         })
 17     }
 18 </script>
  

Я получаю эту ошибку при включении строки 67 widgets = {'cost_price': forms.TextInput(attrs={'onChange':'updateSellingPrice()'})} в мою форму модели:

 Exception Value: Caught ViewDoesNotExist while rendering: Could not import registration.views.item_details. View does not exist in module registration.views.
  

Когда я удаляю строку 67 из своей формы модели, все работает / загружается нормально. Я думаю, что сообщение об ошибке Django не имеет отношения к моей фактической ошибке. Не по теме: я нахожу, что ошибки в forms.py файл, как правило, вызывает сообщения об ошибках, которые иногда наводят вас на ложный след.

Ответ №1:

Возможно, вам нужно создать формы из ваших моделей и настроить их, вот официальный документ.

Используйте виджеты для настройки с помощью атрибутов HTML

Ответ №2:

Моя глупость. Я делал from django.forms import forms вместо from django import forms .