简体   繁体   English

django - 如何从模板按钮将 api 数据保存到模型中

[英]django - how to save api data into model from template button

I am using the Yelp API to search bars in a any location.我正在使用 Yelp API 在任何位置搜索栏。 This uses a template called results.html that has a button.这使用了一个名为 results.html 的模板,它有一个按钮。 Clicking this button should save the Yelp API unique ID of a Bar into my models.单击此按钮应将 Bar 的 Yelp API 唯一 ID 保存到我的模型中。 In my results dictionary that I loop over I call this 'id'.在我循环的结果字典中,我称之为“id”。 This is where I am having issues, taking the id from the template, saving it in the add_list views to the model BarList.这是我遇到问题的地方,从模板中获取 id,将其保存在 add_list 视图中到模型 BarList。 This will not save to my database, I believe the main problem is my logic in add_list.这不会保存到我的数据库中,我相信主要问题是我在 add_list 中的逻辑。

I get the following error.我收到以下错误。 The long string is the id from the loop.长字符串是循环中的 id。 Results.id.结果.id。

IntegrityError at /add/Jlhck4bGoXaXfuoMOKGRww/

NOT NULL constraint failed: API_barlist.api_id

Views.py视图.py

def index(request):
    if request.method == 'POST':
        form = CityForm(request.POST)
        if form.is_valid():
            city = form.cleaned_data['city_name']
            API_KEY = 'MyAppKey'
            url = 'https://api.yelp.com/v3/businesses/search'
            headers = {'Authorization': 'Bearer {}'.format(API_KEY)}
            params = {'term':'bar','location':city}
            req = requests.get(url, params=params, headers=headers)
            parsed = json.loads(req.text)
            businesses = parsed["businesses"]
            final_result = []

            for business in businesses:
                results = {
                'id': business['id'],
                'business': business['name'],
                'rating': business['rating'],
                'image_url': business['image_url']
                }
                final_result.append(results)

            context = {'final_result': final_result}
            return render(request, 'API/results.html', context)
    else:
        form = CityForm()
    return render(request, 'API/home.html', {'form':form})

def add_list(request):
    if request.method == 'POST':
        api_id = request.POST.get("id")
        Bar = BarList(api_id=api_id)
        Bar.save()
    else:
        return render(request, 'API/results.html')

Models.py模型.py

class BarList(models.Model):
    api_id = models.CharField(max_length=100)

Urls.py网址.py

urlpatterns = [
    path('', views.index, name='API-home'),
    path('list', views.list, name='API-list'),
    path('add/<str:results>/', views.add_list, name='API-add') ]

results.html template结果.html 模板

{% extends "API/base.html" %}
{% block content %}

{% for results in final_result %}

<h3>{{ results.business }}</h3>

<form action="{% url 'API-add' results.id %}" method="POST">
  {% csrf_token %}
  <input type="submit" value="Add Item to List" />
</form>

{% endfor %}
{% endblock content %}

Few things I needed to do.我需要做的事情很少。 The not null constraint error is fixed by adding a constraint to the model.通过向模型添加约束来修复非空约束错误。 Furthermore I needed to finish writing my view to properly save.此外,我需要完成我的视图的编写才能正确保存。

Updated Models更新模型

class BarList(models.Model):
    api_id = models.CharField(max_length=100, null=False)
    user = models.ForeignKey(User,on_delete=models.CASCADE,null=True,related_name="user")

Updated View更新视图

def add_list(request,results):
    if request.method == 'POST':
        Bar = BarList(api_id=results,user=request.user)
        Bar.save()
        return HttpResponseRedirect('/')
    else:
        return render(request, 'API/results.html')

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

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