如何根据Django

时间:2017-08-14 06:49:57

标签: python django

我正在尝试根据表单中的选定字段过滤数据。我创建了一个模型并将其导入forms.py

from django import forms
from django.forms import ModelForm
from .models import Student_Detail, Student_Education
class StudentDetailForm(forms.ModelForm):
   class Meta:
       model = Student_Detail
       fields = ['name', 'surname' , 'sex', 'birth_date', 'area', 
          'state' ,
           'city' , 'pincode']

        def to_python(self, value):

            if not value:
                return []
            return value.split(',')

我的模特是

`

from __future__ import unicode_literals
from django.db import models

# Create your models here.
class State(models.Model):
    state = models.CharField(max_length=50)
    slug = models.SlugField(unique=True, null=True, blank=True)

    def __str__(self):
       return self.state


class City(models.Model):
    state = models.ForeignKey('State', on_delete=models.CASCADE)
    city = models.CharField(max_length=70)
    slug = models.SlugField(unique=True, null=True, blank=True)

    def __str__(self):
        return self.city


class Student_Detail(models.Model):

    name = models.CharField(max_length=50)
    surname = models.CharField(max_length=50, blank=True, null=True)
    sex = models.CharField(max_length=4)
    birth_date = models.DateTimeField()
    area = models.CharField(max_length=100, blank=True, null=True)
    state = models.ForeignKey('State', on_delete=models.CASCADE)
    city = models.ForeignKey('City', on_delete=models.CASCADE)
    pincode = models.IntegerField()

    slug = models.SlugField(unique=True, null=True, blank=True)

    def __str__(self):
        return self.name + " " + self.surname`

现在我想根据在同一表单中选择的状态过滤表单中的城市。

我的观点是

from django.shortcuts import render
from .models import City, Student_Detail, State, Student_Education
from django.http import HttpResponseRedirect
from .forms import StudentDetailForm, StudentEducationForm


def get_student_data(request):

    if request.method == 'POST':
        form_detail = StudentDetailForm(request.POST)

        if form_detail.is_valid():
            form_detail.save()
            return HttpResponseRedirect('/home/')

    else:
        form_detail = StudentDetailForm()

        return render(request,'home/form.html/', 
        {'form_detail':form_detail, })

def thanks(request):
    template_name = 'home/thanks.html/'

    return render(request, template_name, {})

我也尝试使用表单在两个不同的模型中输入数据,但是在视图层将两个不同模型中的数据保存时出现了一些问题。 请帮助。

1 个答案:

答案 0 :(得分:1)

访问您的表单字段,例如myForm.fields['name']并过滤Student_Detail

from django.shortcuts import render
from django.http import HttpResponse

def student_view(request):
    # your business logic or whatever goes here
    if form.is_valid():
        students = Student_Detail.objects.filter(name=myForm.fields['name'], 
                                           surname=myForm.fields['surname'])

    return render(request, 'student_view.html', {data=students})