Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i auto-populate fields in django?

I have a model Question with a field called userid, before one ask a question, one needs to login, i want when saving to capture the user ID of the currently logged-in user and assign it to the userid of the Question model.

Please note am not showing the userid on my form i.e. in the Question model i have declared the userid as follows;

class Question(models.Model): ... userid=models.ForeignKey(User, editable=false) ...

How do i assign logged-in user ID to the Question model userid?

like image 763
Gath Avatar asked Jan 05 '09 13:01

Gath


People also ask

How do you autofill a field in Django?

If you want to combine some fields you already have in the database, please implement them as methods on your model, ref: docs.djangoproject.com/en/4.0/topics/db/models/#model-methods Also, it's better to implement 'business rules' like this on your model instead of in the view.

How do you auto populate a field?

Highlight the field you want to auto-populate and click the Auto-populate button. The Auto Populate window opens. In the Destination Element field, enter the name of the data element you want to populate. Enter the data element name; not the field label.

What is default auto field in Django?

Starting new projects in Django 3.2, the default type for primary keys is set to a BigAutoField which is a 64 bit integer.


3 Answers

Your code may look like this:

from django.contrib.auth.decorators import login_required

class QuestionForm(forms.ModelForm):
    class Meta:
         model = Question

@login_required
def ask(request):
    form = QuestionForm(request.POST)

    if form.is_valid():
        question = form.save(False)
        question.userid = request.user
        question.save()

    #...
like image 104
Alex Koshelev Avatar answered Oct 08 '22 04:10

Alex Koshelev


This blog entry (by James Bennett) might prove useful for you as well...it lays out a way to do almost exactly what you require.

like image 33
bkev Avatar answered Oct 08 '22 03:10

bkev


For a more recent - and likely to be updated - resource, I recommend the official Django documentation. This very example has made it's way into the ModelAdmin methods section of the ModelAdmin documentation.

If you're like me, you'll be tempted to just grab that example and run, but you might benefit from slowing down, taking a few minutes to read, and then implementing - I certainly would have...

like image 25
sage Avatar answered Oct 08 '22 04:10

sage