So below is the views.py
and I'm trying to load a view with modelform. And within the modelform I need to load modelchoicefield
depending on the current user logged in and tried the below solution(check forms.py
.) When I run it, i get
Attribute Error :object has no attribute 'get'
Help is highly appreciated, there's nothing in stackoverflow.
views.py:
class HomeView(View):
def get(self, request, *args, **kwargs):
form=PreDataForm(request.user)
return render(request, 'mainlist.html',
{ "form":form,
})
models.py:
class PreData(models.Model):
journalname = models.CharField(max_length=400, blank=False, null=True, default='')
forms.py:
class PreDataForm(forms.ModelForm):
journalname = forms.ModelChoiceField(required=True)
class Meta:
model=PreData
fields=['journalname']
def __init__(self,user, *args, **kwargs):
super(PreDataForm, self).__init__(user, *args, **kwargs)
self.fields["journalname"].queryset = Journals.objects.filter(journalusername=user)
html file:
{% extends 'home-base.html' %}
{% load crispy_forms_tags %}
{% block title %}
Welcome to Metrics - JSM
{% endblock %}
{% block content %}
<div class="col-md-9 col-centered" >
<div class="backeffect" >
{% if data %}
{% else %}
<b>Seems you are first time around here, Why not <b>{% include 'modal_first_stage.html' %}</b> to get started? :)</b>
{% endif %}
{% endblock %}
ModelForm
does not take user
. You should remove it from your super()
call.
def __init__(self, user, *args, **kwargs):
super(PreDataForm, self).__init__(*args, **kwargs)
self.fields["journalname"].queryset = Journals.objects.filter(journalusername=user)
A slightly more re-usable version, which will work with the generic create/update views, is:
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super(PreDataForm, self).__init__(*args, **kwargs)
self.fields["journalname"].queryset = Journals.objects.filter(journalusername=user)