根据所选选项在视图中使用特定表单

时间:2019-01-30 06:52:59

标签: django django-forms

我正在编写用于水文观测的Web应用程序。 有各种类型的Hydropost。水文站根据它们的观测结果进行分类。

  1. HydropostType1观察水位,水温,空气温度,排放量
  2. HydropostType2观察水位,水温,气温
  3. HydropostType3观察水位,水温,水波纹

以此类推。

我的forms.py看起来像这样

forms.py

#Minimum forms for observation
class BasicObservationForm(forms.Form):
    level = forms.IntegerField(label = 'Уровень воды')
    water_temperature = forms.DecimalField(label = 'Температура воды',
            max_digits = 5, 
            decimal_places = 2, 
            max_value = 70, 
            min_value = -70,
            required = False)

class AirTemperatureForm(forms.Form):
    air_temperature = forms.DecimalField(label = 'Температура воздуха', required = False)

class RippleForm(forms.Form):
    ripple = forms.IntegerField(label = 'Волнения воды', required = False)

class DischargeForm(forms.Form):
    discharge = forms.DecimalField(label = 'Расход воды', required = False)

class PrecipitationForm(forms.Form):
    precipitation = forms.CharField(label = 'Атмосферные осадки', required = False)



class Hydropost1CategoryForm(BasicObservationForm, AirTemperatureForm, DischargeForm):
    pass


class Hydropost2CategoryForm(BasicObservationForm, AirTemperatureForm):
    pass


class Hydropost3CategoryForm(BasicObservationForm, AirTemperatureForm, RippleForm):
    pass

现在,我为每个类别表单使用多个视图。

views.py

@login_required(login_url = '/login/')
def Hydropost1CategoryRecord(request):
    if request.method == 'POST':
        form = Hydropost1CategoryForm()
        context = { 'form': form, }
        if form.is_valid():
            return redirect('/')
    elif request.method == 'GET':
        form = Hydropost1CategoryForm()
        context = { 'form' : form, }
    return render(request, 'hydrology/record.html', context)

@login_required(login_url = '/login/')
def Hydropost2CategoryRecord(request):
    if request.method == 'POST':
        form = Hydropost2CategoryForm()
        context = { 'form': form, }
        if form.is_valid():
            return redirect('/')
    elif request.method == 'GET':
        form = Hydropost2CategoryForm()
        context = { 'form' : form, }
    return render(request, 'hydrology/record.html', context)

然后为每个水文邮政类别创建视图

record.html只是保存表格。

{{ form }}

结果,我需要为每种表单类型使用多个网址

urls.py

urlpatterns = [
    path('', views.home, name = 'home'),
    path('hp1record/', views.Hydropost1CategoryRecord, name = 'hp1record'),
    path('hp2record/', views.Hydropost2CategoryRecord, name = 'hp2record'),
    path('category/', views.search_hydropost_type, name = 'category'),
]

我在首页上确定了Hydropost类别,并重定向到必要的Hydropost网址。
我尝试通过POST Hydropost类别查看elif,但是它创建了一个难以阅读的视图,因为我有几种类型的Hydropost。

我的主视图仅使用Javascript渲染html。所有工作都是通过javascript

完成的

views.py

@login_required(login_url = '/login/')
def home(request):
    user = request.user
    hydrologist = Hydrologist.objects.get(user = user)
    hydroposts = hydrologist.hydropost_set.all()
    context = { 'hydroposts' : hydroposts ,}
    return render(request, 'hydrology/home.html', context)

hydrology.js

var category;
var url_category = {% url 'category' %};
var url_hp1record = {% url 'hp1record' %};
var url_hp2record = {% url 'hp2record' %};

//I get hydropost type using another search_category_view
$('[name="hydropost"]').change(function () {
     hydropost = $(this).val();
      $.ajax({
          url: url_category,
          type: 'GET',
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          data: {
                'hydropost': hydropost
          },
          success: function(data){ 
                category = data.category;
                $( "h3" ).replaceWith( "<h3>" + data.category + "</h3>" );
          },
          error: function(data){
                $( "h3" ).replaceWith( "<h3>" + data.hydropost + "</h3>");
          }
      });
});

$('[name="hydropost"]').trigger("change") //first page load

$('.btn').click(function() {
    hydropost = $('select option:selected').val();
    //Here I compare category, I am using bootstrap modal
    //I load html from url
    if (category == 'пост 1 разряд') {
        $(".modal-body").load(String(url_hp1record));
    } else if (category == 'пост 2 разряд') {
        $(".modal-body").load(String(url_hp2record));
    }
});

还有其他方法可以对每个水文柱使用一个视图,还是对每个水文柱使用一个网址

1 个答案:

答案 0 :(得分:1)

您可以拥有一个将输入作为格式类型的通用视图(即1的{​​{1}}或Hydropost1CategoryForm的{​​{1}})。这种类型的表单变量是将表单ajax发送到2Hydropost2CategoryForm上的一般视图。

然后,您可以使用此信息(表格类型)从包含这些表格的字典中选择特定的POST。这是一个示例:

urls.py:

GET

views.py:

Form

如您所见,我不必为每个表单定义urlpatterns = [ ... # url for general view which handles all your forms in one place url(r'HydropostCategoryRecord/$', views.HydropostCategoryRecord), ... ] form_list = {'1': Hydropost1CategoryForm, '2': Hydropost2CategoryFrom} @login_required(login_url = '/login/') def HydropostCategoryRecord(request): if request.method == 'POST': h_type = str(request.POST.get('h_type')) form = form_list[h_type](request.POST) if form.is_valid(): return redirect('/') elif request.method == 'GET': h_type = str(request.GET.get('h_type')) form_ref = form_list[h_type]() context = { 'key' : value, } return render(request, 'hydrology/record.html', context) ,因为我使用的是一个字典,该字典将输入作为表单编号(例如,if elif中的1Hydropost1CategoryForm),并提供给我输出作为表单名称。