如何在Django 2中将变量从html注入到views.py中?

时间:2019-04-16 20:32:26

标签: python html django django-forms django-views

我尝试了一些方法,但没有任何效果。该按钮应从文本框中键入城市刮下天气。当我对城市名称进行硬编码时,所有抓取均有效,但我不知道如何从HTML表单中将城市名称转换为views.py

html

<form method="POST "action="{% url 'weather' %}">
{% csrf_token %}
    <input  type="text" value="{{ city }}">
    <button type="submit" class="btn btn-info">Get my weather</button>
</form>

views.py

def scrape_weather(request):
    old_weather = Weather.objects.all()
    old_weather.delete()
    api_adress = "http://api.openweathermap.org/data/2.5/weather?q="
    api_key = "&appid=3a99cf24b53d85f4afad6cafe99d3a34"
    city = input()
    #city = "warsaw"
    url = api_adress + city + api_key

    json_data = requests.get(url).json()
    new_weather = json_data['weather'][0]['main']
    degree_kelvin = int(json_data['main']['temp'])
    degree = degree_kelvin-273
    pressure = json_data['main']['pressure']

    new_weather = Weather()
    new_weather.degree = degree
    new_weather.pressure = pressure

    new_weather.weather = new_weather
    new_weather.save()
    if request.method == 'POST':
        form = CityForm(request.POST)
        if form.is_valid():
            pass
    else:
        form = CityForm() 
    return render(request, "news/home.html", {'form': form})

forms.py

from django import forms

class CityForm(forms.Form):
    city = forms.CharField(max_length=30)

    if not city:
        raise forms.ValidationError('You have to write something!')

2 个答案:

答案 0 :(得分:0)

这与刮擦或注入无关。为了使浏览器从输入字段发送值,field元素需要具有name属性。

<input  type="text" name="city">

,然后在视图中获取它:

city = request.POST.get("city")

注意,我完全不确定为什么要使用CityForm,而没有使用它。

答案 1 :(得分:0)

In your template you can:

<form method="POST "action="{% url 'weather' %}">
{% csrf_token %}
    {{ form }}
    <button type="submit" class="btn btn-info">Get my weather</button>
</form>

That will manage all the business of widget( text input in this case) attributes such as name for you.

Read this for more detail.