Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML tags for choicefield in Django

I cant seem to find ANYWHERE on how to do choicefield HTML tags in Django. I found radio buttons and other advance choice fields, but nothing on basic drop down HTML tags with Django. I have models.py and view.py set up passing list1 to the html pages, but cant seem to make it display anything except

<select style="width:300px">
  {% for choice in list1.VIEWS %}
  <option>{{choice}}</option>
  {{choice}}
  {% endfor %}
</select>

Help would be greatly appreciated

models.py

class preset_list(models.Model):
    VIEWS = (
        ('1', 'X'),
        ('2', 'Y'),
    )
    query_choice = forms.ChoiceField(choices=VIEWS)

view.py

list1 = models.preset_list()
return render_to_response('services.html', 
         {'array':json.dumps(data, cls=SpecialEncoder),
         'list1':list1},
                          )
like image 825
rodling Avatar asked Jan 02 '14 02:01

rodling


Video Answer


2 Answers

ModelForms are your friend here.

models.py

class PresetList(models.Model):
    VIEWS = (
        ('1', 'X'),
        ('2', 'Y'),
    )
    query_choice = forms.ChoiceField(choices=VIEWS)

forms.py

from django.forms import ModelForm
from . import models

class PresetListForm(ModelForm):
    class Meta:
        model = models.PresetList

view.py

from . import forms

def my_view(request):

    preset_form = forms.PresetListForm()

    return render_to_response('services.html', {
        'array': json.dumps(data, cls=SpecialEncoder),
        'preset_form': preset_form,
    })

services.html

<form method=POST action="/somewhere">
    {{ preset_form.as_p }}
</form>
  • https://docs.djangoproject.com/en/dev/topics/forms/modelforms/
  • https://docs.djangoproject.com/en/1.6/ref/forms/fields/#choicefield
like image 156
Thomas Avatar answered Oct 03 '22 01:10

Thomas


Give the generic CreateView a try.

views.py

from django.views.generic.edit import CreateView
from .models import PresetList

class PresetListCreate(CreateView):
    model = PresetList

presetlist_form.html

<form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Create" />
</form>
like image 40
Nathaniel Avatar answered Oct 03 '22 03:10

Nathaniel