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?
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.
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.
Starting new projects in Django 3.2, the default type for primary keys is set to a BigAutoField which is a 64 bit integer.
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()
#...
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With