How to make the column "user" to be auto selected in a form.

26 views
Skip to first unread message

John Son

unread,
Jul 24, 2018, 9:16:41 AM7/24/18
to Django users
models.py
class Post(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True)
    date = models.DateField(default=datetime.now, blank=True)
    text_author = models.CharField(max_length=200, null=True, blank=True)

forms.py
class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ("title", "body", "user", "text_author")
views.py
def create_Post(request):
    form = PostForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        return HttpResponseRedirect (instance.get_absolute_url())
    context = {
        "form": form,
    }
    return render(request, 'blog/create.html', context)

As shown in attached image, the user has to select themselves from list of users before they can submit their post.(which doesn't make sense). I want the form to know which user is writing the form(assuming they are logged in) so the user doesn't have to identify themselves before they submit their post. I'm guessing I need to edit my models.py but I have no idea. Please Help.

Thank you.
form.png

Mikhailo Keda

unread,
Jul 24, 2018, 9:35:40 AM7/24/18
to Django users
you need to set initial in admin.py for this field, check this example - https://bitbucket.org/voron-raven/maps/src/004eaa07612fd44b398dfdc61b5f9cb29ad23668/core/admin.py#lines-39

if it's not admin page - you need to pass initial to your Model form - https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/#providing-initial-values

Reply all
Reply to author
Forward
0 new messages