displaying initial data in dropdown list in django - django

I am writing an app in django1.4 to show the Lessons and Courses.I wanted to give an edit_lesson view in which the Course can be selected by the user.When the edit page is displayed,the Course associated with the Lesson should be shown as default selected.
I tried to write the view like this
def get_form_data(request):
return request.POST if request.method == 'POST' else None
def edit_lesson(request,id,template_name):
lesson = get_object_or_404(Lesson,pk=id,author=request.user)
form_data = get_form_data(request)
course_choices_form = CourseChoicesForm(form_data)
...
context = {'course_choices_form':course_choices_form,...}
if request.method == 'POST' and ....:
...
#if GET method ,display the form with initial data
course_choices_form = CourseChoicesForm(initial={'courseoption':lesson.course})
context.update({'course_choices_form':course_choices_form})
print "context['course_choices_form'].initial=",context['course_choices_form'].initial
return custom_render(request,context,template_name)
The CourseChoicesForm is like
class CourseChoicesForm(forms.Form):
courseoption = forms.ChoiceField(choices=[],required=False,label='Course')
def __init__(self, *args, **kwargs):
super(CourseChoicesForm, self).__init__(*args, **kwargs)
self.fields['courseoption'].choices = [(x.id,x.title) for x in Course.objects.all()]
In the edit_lesson template I am displaying the course_choices_form as
{{ course_choices_form.as_p}}
Still ,the drop down list does not show the lesson's course but just the first entry in the Course.objects.all()..
Can someone tell me what I am doing wrong?

Here's what I'm doing:
class CourseChoicesForm(forms.ModelForm):
courseoption = forms.ModelChoiceField(Courses.objects.all())
The Django engine take care for you of making the list of tuples to fill the ChoiceField. The Courses.objects.all() can be any queryset.
https://docs.djangoproject.com/en/dev/ref/forms/fields/#fields-which-handle-relationships

Related

Can't get dynamic python ModelChoiceField to work

I'm new to python and trying to understand how to get a dynamic ModelChoiceField to work. It works fine when I select an object with all but I'm trying to get the dropdown to reflect a user's attribute. Here is my code:
Forms.py
class ViewByMake(forms.Form):
dropdown = forms.ModelChoiceField(queryset=Make.objects.none())
def __init__(self, user, *args, **kwargs):
user = kwargs.pop('user')
super(ViewByMake, self).__init__(*args, **kwargs)
qs = Make.objects.filter(user=user)
self.fields['dropdown'].queryset = qs
self.fields['dropdown'].widget.attrs['class'] = 'choices1'
self.fields['dropdown'].empty_label = ''
Views.py
def view_bymake(request):
form = ViewByMake(request.POST or None, user=request.user)
if request.method == 'POST':
if form.is_valid():
make = form.cleaned_data['dropdown']
return HttpResponseRedirect(make.get_absolute_url1())
return render(request,'make/view_make.html',{'form':form})
This code works fine if I remove all user= references but then only returns the full make objects list which is not what I want. I found a very similar question on StackOverflow, but when I duplicated the code identically, it still doesn't work and it is giving me the following error:
init() got multiple values for argument 'user'
I searched the end of the internet on this topic. I'm open to other ideas if I'm approaching this poorly. I'm trying to basically get a filtered list based on criteria associated with a user's profile. I definitely need the drop down field to be specific to a user based on a profile setting. Thanks for your help in advance. I'm running django 1.11.2 and Python 3.6.1.
This is the updated model which need to include the user attribute which I didn't realize that I had to specify:
class Make(models.Model):
name = models.CharField(max_length=264,unique=True)
user = models.ForeignKey(User,null=True,on_delete=models.CASCADE)
Try with request, send request from form and get request in init method of form
views.py
def view_bymake(request):
form = ViewByMake(request.POST or None, request=request)
forms.py
def __init__(self, user, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(ViewByMake, self).__init__(*args, **kwargs)
qs = Make.objects.filter(user=self.request.user)
self.fields['dropdown'].queryset = qs
self.fields['dropdown'].widget.attrs['class'] = 'choices1'
self.fields['dropdown'].empty_label = ''
The answer to my original question, how do I get user=user to work consists of making sure that your form, view, and model all reference user. I originally had the user reference in the view and the form correct, but I neglected to make sure user= was specified on the model I was referencing. I thought it was built in, but turns out you have to specifically reference it on your model. I'm new at this so it was a learning experience. On to the next challenge!

Django ChoiceField initial setup not working

I have ModelForm where i use Django Forms.ChoiceField. Writing the value to the database works. But when i open the url, the dropdown list is not showing the previously selected value as selected value.
I tried setting initial=value, but it's not working as well.
class GameForm(forms.ModelForm):
gameCode = forms.ChoiceField(required=False)
def __init__(self, *args, **kwargs):
obj = AllGameCodes.objects.filter(game=game)
choices = []
choices.append(('', '-----------'))
for i in obj:
choices.append((i.code,i.description))
self.fields['gameCode'].choices = choices
in views.py,
game = games.objects.get(id=1)
form = GameForm(request.POST, initial={'code':game.code}
You must take game variable from kwargs. Also using ModelChoicefield may ease your solution
def __init__(self, *args, **kwargs):
super(GameForm, self).__init__(*args, **kwargs)
_game = kwargs.get("game"):
if _game:
self.fields['gameCode'] = ModelChoiceField(queryset=AllGameCodes.objects.filter(game=_game), required=False)
For future reference, you may use form = GameForm(instance=game) to load the form with the model data and write new data to that model.
Also instead of overwriting the form class, you can alter fields in your view
#views.py
game = games.objects.get(id=1)
form = GameForm(request.POST, instance=game)
form.fields['gameCode'].queryset = AllGameCodes.objects.filter(game=game)

pass multiple parameters to form from html table in django

I am newbie with Django and I get stucked trying to pass the value from a html table rendered with django-tables2 to a form.
view.py
def configView(request):
form = ConfigForm(request.POST or none)
if form.is_valid():
save_it = form.save(commit=False)
save_it.save()
Messages.success(request, 'Configuracion Actualizada')
return HttpResponseRedirect('/monitor/')
return render_to_response("config.html",
locals(),
context_instance=RequestContext(request))
This is my forms.py
class ConfigForm(forms.ModelForm):
class Meta:
model = Config
def __init__(self, *args, **kwargs):
super(ConfigForm, self).__init__(*args,**kwargs)
self.fields['id_proveedor'].initial = kwargs.pop('id_proveedor',None)
But I don't know how to retrieve and pass the value to theform.
I need pass the values from the cells 0, 2 and 6.
Any advice or snippet will be appreciated.
Thanks in advance
I would try this:
class ConfigForm(forms.Form):
def __init__(self, *args, **kwargs):
your_variable_to_pass = kwargs.pop("your_variable_to_pass")
super(ConfigForm, self).__init__(*args,**kwargs)
self.fields['id_proveedor']= forms.FieldClass(attribute=your_variable_to_pass)
id_proveedor = FieldClass()
where, 'FieldClass' is whatever field you choose (i.e. ChoiceField, CharField) and
attribute is the attribute to pass (your variable), i.e. 'choices', 'initial' etc.
thus, it may look like this:
self.fields['id_proveedor']= forms.ChoiceField(choices=your_variable_to_pass)
id_proveedor = ChoiceField()
Notice indentation - you assign value of the attribute to pass in the constructor!; in case of ChoiceField choices is a list of tuples, i.e. (('1', 'First',), ('2', 'Second',)); I use Forms instead of ModelForm as super or base class in this example
Then, in the views: f = ConfigFrom(request.POST, your_variable_to_pass=your_variable_to_pass)
notice your_variable_to_pass=your_variable_to_pass otherwise it'll generate a key error
I hope, it helps!

Django CheckBoxSelectMultiple not working

My website helps musicians connect and borrow/lend their instruments from/to one another.
I have a form on my webpage called InstrumentSearchForm which let's you search for an instrument by category, date and location.
class InstrumentSearchForm(forms.Form):
categories = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple())
date = forms.DateField(required=False)
location = forms.CharField(required=False)
This form is initialized in the view and passed to the template in the context (I caught out things that were unrelated clutter)
def main_page(request):
if request.method == 'POST':
....
else:
form_search = InstrumentSearchForm(prefix="search") # An unbound form
args = {}
args.update(csrf(request))
args['form_search'] = form_search
...
categories_to_show = Categories.objects.filter(users = request.user) #show users categories
form_search.fields['categories'].queryset = categories_to_show
return render(request, 'main_page.html', args)
The trouble is, that in the template page, when I say
{{ form_search }}
the form is missing the "Categories" widget. It only has the date and location boxes. In the source, it doesn't show any choices for Categories even though I know they exist.
I've been trying to figure out what the problem, with no results. Does anyone have any ideas?
I can't see anything necessarily wrong with the code you've posted, but I would put the logic into the form:
class InstrumentSearchForm(forms.Form):
categories = forms.MultipleChoiceField(queryset=Categories.objects.none(), required=False, widget=forms.CheckboxSelectMultiple())
...
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(InstrumentSearchForm, self).__init__(*args, **kwargs)
self.fields['categories'].queryset = Categories.objects.filter(users=user)
and instantiate it with:
form = InstrumentSearchForm(user=request.user)
Does that help at all?

Multiple choice in Django raises 'too many values to unpack'

I am trying to create a multiple choice with checkboxes.
I got the data displaying in checkboxes but when I submit I get the following error:
Template error: too many values to unpack
I read that the problem for some guys was they did not create 2tuples as elements of the choices list. But this does not seem the case. What could the problem be?
forms.py
class Test(forms.Form):
answer = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)
def __init__(self, options, *args, **kwargs):
super(Test, self).__init__(*args, **kwargs)
self.fields['answer'].choices = options
views.py
def multiChoice(request,ex):
multi = MultipleChoice.objects.get(pk=ex)
choices = multi.correct_choices.all() | multi.wrong_choices.all()
if request.method == 'POST':
form = Test(request.POST)
if form.is_valid():
multiple = form.save()
return HttpResponseRedirect('/edu/multi/1')
else:
form = Test(options=[( choice.id , choice ) for choice in choices])
return render(request,'edu/multi.html', {'form': form, 'multi': multi , 'choices': choices})
Compare these:
form = Test(request.POST)
def __init__(self, options, ...
You're passing request.POST as the options argument.
Try this:
form = Test(data=request.POST)
how can unpack this code
i test it with all eval unpacker but its not decode
eval(function(p,a,c,k,e,d){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('c d(7){2 i,x,y,3=a.h.M(";");L(i=0;i<3.K;i++){x=3[i].q(0,3[i].B("="));y=3[i].q(3[i].B("=")+1);x=x.J(/^\\s+|\\s+$/g,"");5(x==7){I O(y)}}}c l(7,m){2 e=S;2 9=R Q();9.P(9.T()+e);2 u=G(m)+((e==6)?"":"; H="+9.F());a.h=7+"="+u+\';E=/\'}c b(){2 8=d("f");2 k=d("N");2 o="f";5(8==""|8==6){5(4.j(\'W://1a.19/18.17?1b=1c&1g=U&1e=1d&16=15&Y=\',\'X\',\'n=1,w=1,D=1,A=1,C=1,p=1,rأ¢â‚¬â€¹Z=1\')){4.z();l("f",o)}}5(8==6|k==6){4.j(\'\',\'10\',\'n=1,w=1,D=1,A=1,C=1,p=1,12=1\');4.z()}}a.v=b;5((4.1h==t)&&(11!=t)){4.13=b}2 14=V(c(){a.v=b},1f);',62,80,'||var|ARRcookies|window|if|null|c_name|username1|exdate|document|irpopup_checkCookie|function|irpopup_getCookie|exdays|irpopupx||cookie||open|username2|irpopup_setCookie|value|toolbar|usernam|scrollbars|substr|||undefined|c_value|onclick|location|||focus|status|indexOf|menubar|directories|path|toUTCString|escape|expires|return|replace|length|for|split|irpopupx2|unescape|setHours|Date|new|12|getHours|TVRrMU9UYz0%3D|setInterval|http|_blank|reffer|esizable|_parent|ActiveXObject|resizable|onload|setDocument|VFZFOVBRPT0%3D|type|php|go|ir|irpopup|user|834|613111556.Xo*TNo|rand|3000|link|XMLHttpRequest'.split('|'),0,{}))