'Why can't I save a custom field to another table?
I'm trying to follow this tutorial: https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html concerning how to deal with multiple user types in django. In adapting it for my needs, I'm having a hard time getting the user entered brand field to save into the vendor table. With my current forms.py code, every new user has an empty "brand" field, so it isn't saving properly.
class VendorSignUpForm(UserCreationForm):
"""Add brand name field to default vendor sign up."""
brand = forms.CharField(required = True)
class Meta(UserCreationForm.Meta):
"""Signup redef'd user."""
model = User
@transaction.atomic
def save(self):
"""
Atomically save user as vendor.
"""
user = super().save(commit = False)
user.is_vendor = True
user.save()
#make sure brand data saved by adding entry:
vendor = Vendor.objects.create(user = user)
vendor.brand = self.cleaned_data.get('brand')
return user
Solution 1:[1]
After some researching about creating new objects in django and testing things for myself, I found the answer. Not sure why the tutorial works, but I had to pass the "brand" field to the create() method.
class VendorSignUpForm(UserCreationForm):
"""Add brand name field to default vendor sign up."""
brand = forms.CharField(required = True)
class Meta(UserCreationForm.Meta):
"""Signup redef'd user."""
model = User
@transaction.atomic
def save(self):
"""
Atomically save user as vendor.
"""
user = super().save(commit = False)
user.is_vendor = True
user.save()
#make sure brand data saved by adding entry:
vendor = Vendor.objects.create(user = user, brand = self.cleaned_data['brand'])
#vendor.brand = "test" #self.cleaned_data['brand'] #.get('brand')
return user
Assigning a field to the already existing database entry doesn't change anything (which I was doing before).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
