简体   繁体   English

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

[英]How to inject variable from html to views.py in Django 2?

I tried some ways but none worked. 我试过一些方法,但都没有用。 The button should scrape weather from city typed in the text box. 该按钮应该从文本框中键入的城市中刮取天气。 All scraping works when I hardcode city name but I don't know how to get that city name from HTML form to views.py . 当我对城市名称进行硬编码时,所有抓取工作都有效,但我不知道如何将该城市名称从HTML表单转换为views.py

html : 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 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 : 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!')

This has nothing to do with scraping or injecting. 这与刮擦或注射无关。 For a browser to send a value from an input field, the field element needs to have a name attribute. 对于浏览器从输入字段发送值,field元素需要具有name属性。

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

and then get it in the view: 然后在视图中获取它:

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

Note, I'm not at all sure why you have the CityForm, you aren't using it. 注意,我不确定为什么你有CityForm,你没有使用它。

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. 这将管理窗口小部件的所有业务(在本例中为文本输入)属性,例如您的name

Read this for more detail. 阅读本文了解更多详情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM