如何在模型中正确保存此视图

时间:2016-03-01 13:21:34

标签: python django django-views

美好的一天我想在我的模特中保存这个,但它不起作用。

def my_view(request)
   data = data['my_data']

    if request.method == 'POST':
        data_a = request.POST.get(data["data_a"])
        high_temp = request.POST.get(data["data_b"])
        date = request.POST.get(data["data_c"])
        wind_speed = request.POST.get(data["data_d"])
        obj = WeatherData.objects.create(
            data_a=data_a, data_b=data_b,
            data_c=data_c, data_d=data_d,)
        obj.save()

    return render(request, 'data.html', obj)

2 个答案:

答案 0 :(得分:3)

假设您在?=中有参数,您的代码应如下所示:

POST

答案 1 :(得分:1)

您可以使用ModelForm:https://docs.djangoproject.com/es/1.9/topics/forms/modelforms/#modelform

forms.py:
class WeatherForm(ModelForm):
     class Meta:
         model = Weather
         fields = ['data_a', 'data_b', 'data_c', 'data_d']
views:
def my_view(request)
   data = data['my_data']
   form = WeatherForm(request.POST or None)
   if form.is_valid():
        obj = form.save()
   else: 
       obj = None
   return render(request, 'data.html', {'form': form, 'obj': obj})