brain storm
brain storm

Reputation: 31252

django get the logged in user in the form to build queryset?

I have this model:

class Searches(models.Model):
    user = models.ForeignKey(User)
    .....other fields

Each user has certain saved searches. I want to display a form(a choiceSelect widget) to select one of the several searches and click go. I want to filter in the form to display only the searches of that particular User. This is what I tried. but request.user below does not work. how to fix this?

This is my form:

class SearchesForm(forms.Form):
    #get the queryset for the searches model of logged in user
    qset=Searches.objects.filter(user=request.user) ----> error
    #get the most recent entry
    default=Searches.objects.latest('id')
    choices = forms.ModelChoiceField(queryset=qset,label='select search',initial=default)

EDIT: my view:

def display_search_user(request):
    form=SearchesdiffForm(request)
    if request.method=='POST':
        search=SearchesdiffForm(request,data=request.POST)
        print search
        return HttpResponse(search)
    return render(request,'search_list.html',{'form':form})

Upvotes: 0

Views: 1265

Answers (1)

Bogdan Iulian Bursuc
Bogdan Iulian Bursuc

Reputation: 2275

The instance of the queryset is created when the server starts and there is no knowledge about the request at that moment. The request is specific to each request

You have to pass the request to the form __init__ when you create the form in the view:

class SearchesForm(forms.Form):
    choices = forms.ModelChoiceField(queryset=Searches.objects.none(),
                                     label='select search')

    def __init__(self, request, *args, **kwargs):
        super(SearchesForm, self).__init__(*args, **kwargs)
        if request.user:
            queryset = Searches.objects.filter(user=request.user)
        else:
            queryset = Searches.objects.all()
        latest = queryset.latest('id')
        self.fields['choices'].queryset = queryset

def my_view(request):
    if request.method == 'POST':
        form = SearchesForm(request, request.POST)
        if form.is_valid():
            # return search template here.
            return render(...)
    else:
        form = SearchesForm(request, request.POST)
    return render(request, 'template_name.html', {'form': form})

Upvotes: 5

Related Questions