I’m following Beginning Django E-Commerce but I found a part regarding user profiles a bit perplexing. Basically, I have an abstract class like this:
class BaseOrderInfo(models.Model):
class Meta:
abstract = True
# a bunch of fields follow
shipping_name = models.CharField()
# etc
After this, a UserProfile class inherits BaseOrderInfo:
class UserProfile(BaseOrderInfo):
user = models.ForeignKey(User, unique = True)
# Possibly other methods or fields here
Finally, there is a retrieve method which, as its name suggests, retrieves a user profile (if this user profile doesn’t exist, it creates one for that User object):
def retrieve(request):
try:
profile = request.user.get_profile()
except UserProfile.DoesNotExist:
profile = UserProfile(user=request.user)
profile.save()
return profile
Well, my question is the following: How is it possible to save this UserProfile instance in the retrieve method by only adding a User instance given the fact that UserProfile inherited quite a few other fields from the BaseOrderInfo class? As far as I know, Model and ModelForm create required fields by default.
Thanks
Django does not validate the model when the form is saved. (See the docs on Validating Objects). If you explicitly call
profile.full_clean()before saving, then you will see the validation errors.If a required foreign key was not specified, then you would get a database
IntegrityError. Other required fields are validated by Django, not the database. If Django does not validate the model, there will not be any errors saving an empty string to aCharFieldin the database.