django类基于视图多对多字段显示选定值

时间:2013-01-05 19:36:03

标签: python django django-models django-views django-class-based-views

我有一个使用基于Update View类的视图创建的表单。它显示数据库中输入类型字段中的每个值,但多个字段的值除外。
我应该在视图或模型中插入什么,以便用户看到他们选择了哪些选项(如内置管理模块)。

这是我的观点:

class StudentUpdateView(LoginRequiredMixin, UpdateView):

form_class = StudentForm
model = Student
template_name = 'forms/modify.html'

def get_context_data(self, **kwargs):
    context = super(StudentUpdateView, self).get_context_data(**kwargs)
    context['year'] = Setting.objects.get(id=2)
    return context

def form_valid(self, form):
    if self.request.is_ajax():
        self.object = form.save()
        return HttpResponse(json.dumps("success"),
            mimetype="application/json")
    return super(StudentUpdateView, self).form_valid(form)

def form_invalid(self, form):
    if self.request.is_ajax():
        return HttpResponseBadRequest(json.dumps(form.errors),
            mimetype="application/json")
    return super(StudentUpdateView, self).form_invalid(form)

修改

这是我使用的模型,作为模型表单 并且StudentForm不存在

class Student (models.Model):
name = models.CharField(u'Imię', max_length=40)
surname = models.CharField(max_length=80)
email = models.EmailField(blank=True)
subjects = models.ManyToManyField(Subjects, blank=True)
programs = models.ManyToManyField(Programs, editable=False)
history = models.CharField(max_length=50, editable=False)
added = models.DateTimeField(auto_now=True)

def __unicode__(self):
    return u'%s %s'(self.name, self.surname)

class StudentForm(ModelForm):
    class Meta:
        model = Student

0 个答案:

没有答案