Home > Software design >  How can I make an attribute associate automatically with User? django
How can I make an attribute associate automatically with User? django

Time:05-02

I'm making a simple website using django. I've added a 'Comment' model to make a comment section on a blog post. I'd like to print out each of the 'date_added', 'text', and 'owner' attributes in html.

class User_Comment(models.Model):
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    def __str__(self):
        return self.text

I have problems with the 'owner' attribute.

owner = models.ForeignKey(User, on_delete=models.CASCADE)

if I try to make migrations with it, Django asks me to provide a default value.

It is impossible to change a nullable field 'owner' on user_comment to non-nullable 
without providing a default. This is because the database needs something to populate 
existing rows.
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for 
this column)
 2) Ignore for now. Existing rows that contain NULL values will have to be handled 
manually, for example with a RunPython or RunSQL operation.
 3) Quit and manually define a default value in models.py.

If I add 'blank=True', 'null=True' parameters to the onwer attribute, the attribute works but it doesn't automatically associate with the owner when adding a comment. So I have to go to the admin to designate the comment manually to its owner.

    owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)

What'd be the best solution for this ? I'd like to print the 'owner' attribute in html automatically without having to handle it manually.. Thank you so much for your time.

CodePudding user response:

It may be helpful to explain exactly what has happened here.

You have added an additional field, owner, to an existing Comment model. Because there were already some existing comments, the migration process (that updates Django's understanding of the model in the database) needs to know what to do with the existing comment records that currently have no owner.

This is a one-time process purely to handle the existing records.

However, when you create a new comment, you'll also need to handle who the owner is so the model field gets filled automatically. Let's say you have a model form that takes in user comments and your view tests if a comment is being posted:

form = CommentForm(request.POST or None)

if request.method == "POST" and form.is_valid:
    #create an uncommitted version of the form to add fields to
    form_uncommitted = form.save(commit=False)
    #here we explicitly assign the owner field to the user that made the request
    form_uncommitted.owner = request.user 
    #then save the form data plus our added data
    form_uncommitted.save()
  • Related