[Fixed]-How to pre-populate field in ModelForm

1👍

The user is in request. So you can write:

user=request.user

Thats all

So your view should look like this

def post(request):

    allauth_login = LoginForm(request.POST or None)
    allauth_signup = SignupForm(request.POST or None)

    form_post = PostForm(request.POST, request.FILES, user=request.user)
    if form_post.is_valid():
        category = form_post.cleaned_data['category']
        for a, b in CATEGORY_CHOICES:
            if a == category:
                category = b
                form_post.save()
        return HttpResponseRedirect('/%s' % category)
    else:
        form_post = PostForm()

    context = {
        'allauth_login': allauth_login,
        'allauth_signup': allauth_signup,
        'form_post': form_post
    }

    return render(request, 'post.html', context)

UPD

it works only when user is authenticated. to check out if user is authenticated, you can add @login_required decorator just befor the view, for example:

from django.contrib.auth.decorators import login_required
@login_required
def post(request):
  ...

Also, i think you have to make if statement, to render page for authenticated users, and not. for example

if request.user.is_authenticated():
  form_post = PostForm(request.POST, request.FILES, user=request.user)
  if form_post.is_valid():
    ...
else:
  ..

Leave a comment