显示CheckboxSelectMultiple的输出

时间:2018-09-07 08:27:53

标签: python html django

我为Django应用创建了一个CheckboxSelectMultiple表单。 当用户选择选项时,我想在“详细信息”页面上显示它。但是当我制作时,它显示<django.forms.fields.CharField object at 0x7faf189cad10> 如何解决它并显示用户选择的输出?

models.py

from __future__ import unicode_literals
from django.utils import timezone
from django.db import models
from django import forms

LANG_CHOICES = (
    ('java', 'JAVA'),
    ('c/c++', 'C/C++'),
    ('python', 'PYTHON'),
    ('html', 'HTML'),
    ('css', 'CSS'),
    ('javascript', 'JAVASCRIPT'),
)


class Project(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.CharField(max_length=100)
    project_name = models.CharField(max_length=300)
    project_description = models.TextField()
    project_notes = models.TextField()
    select_langs = forms.CharField(label='dil sec: ', widget=forms.Select(choices=LANG_CHOICES))
    created_date = models.DateTimeField(
        default=timezone.now)
    published_date = models.DateTimeField(
        blank=True, null=True)

views.py

def project_details(request, pk):
project = get_object_or_404(Project, pk=pk)
return render(request, 'blog/project_detail.html', {'project': project})
...                
def project_new(request):
if request.method == 'POST':
    form = ProjectForm(request.POST)
    if form.is_valid():
        project = Project()
        project.first_name = form.cleaned_data['first_name']
        project.last_name = form.cleaned_data['last_name']
        project.email = form.cleaned_data['email']
        project.project_name = form.cleaned_data['project_name']
        project.project_description = form.cleaned_data['project_description']
        project.project_notes = form.cleaned_data['project_notes']
        project.published_date = timezone.now()
        project.lang_choices = form.cleaned_data['select_lang']
        project.save()
        return redirect('project_detail', pk=project.pk)
else:
    form = ProjectForm()
return render(request, 'blog/project_new.html', {'form': form})

forms.py

    ...   
 select_lang = forms.CharField(label='languages: ', widget=forms.CheckboxSelectMultiple(choices=LANG_CHOICES))

project_details.html

    <h1> The programming languages that user's will use:  {{project.select_langs}} </h1>

1 个答案:

答案 0 :(得分:0)

您正在将模型中的 model 定义与 form 定义混合

...
select_langs = forms.CharField(
    label='dil sec:', # Wrong: this a form attribute
    widget=forms.Select(choices=LANG_CHOICES)) # Wrong: this a form attribute
...

labelwidget form 属性,不是模型的

模型是数据库中表的表示,因此您无需定义 form 的构造方式。

但是:

您正面临有关如何存储数据的问题,因为您要将多个选项保存到数据库中:

选中Django Model MultipleChoice