I have an Item model. It has both a primary key and an item number; the users refer to item numbers when finding things, and the actual primary key is not exposed. I'm trying to write a CreateView that will allow the user to input the item number.
I see that CreateView defaults to using the primary key to find model objects, which any other time makes sense. I'm thinking the solution is to use a ModelForm, but I'm stuck on the same problem--I'm not sure how to accept a string from the user (instead of the primary key), do my own query, and fetch the required model object that way. I think overriding is_valid() is the correct way to go, but I'm not sure what I'm leaving out--when I override this method, the data is never committed to the database even though I call super(). I've also tried overriding save() and clean() on the ModelForm, but with the same results (that is, no data in the database). I'm writing a simple app that uses Item as a foreign key: class ItemsTestCollection(models.Model): """An item to be tested in Box Opt.""" item = models.ForeignKey('item.Item', on_delete=models.CASCADE) qty = models.IntegerField() case = models.ForeignKey('EvaluateTestCase', on_delete=models.CASCADE) box = models.ForeignKey('BoxResults', on_delete=models.CASCADE, null=True) ...using this CreateView: class AddItemsToEvaluateCreateView(CreateView): model = ItemsTestCollection form_class = AddItem # fields = ['item', 'qty', 'case'] template_name = 'utils\evaluate.html' # Not working... def form_valid(self, form): data = form.save(commit=False) item_num = data.item data.item = Item.objects.get(item_number=item_num) data.save() return self.get_success_url() ...and this ModelForm: class AddItem(forms.ModelForm): class Meta: model = ItemsTestCollection fields = ['item', 'qty', 'case'] # widgets = {'item': CharField(max_length=6)} # item = forms.CharField(max_length=6) def is_valid(self): item_num = self.data['item'] # ???? # self.data['item'] = Item.objects.get(item_number=item_num) self.instance.item = Item.objects.get(item_number=item_num) # self.instance.qty = self.data['qty'] # self.instance.case = EvaluateTestCase.objects.get(pk=self.data['case']) super().is_valid() And I somehow need to refer to the Item by item_number and not the auto-assigned pk: class Item(models.Model): """Item attributes""" item_number = models.CharField(max_length=6, null=True, unique=True) Thank you! -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5f4a4128-71f4-482a-b443-affe42fee109%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.