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

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

我正在使用 Yelp API 在任何位置搜索栏。这使用了一个名为 results.html 的模板,该模板有一个按钮。单击此按钮应将条形图的 Yelp API 唯一 ID 保存到我的模型中。在我循环的结果字典中,我称之为 'id'。这是我遇到问题的地方,从模板中获取 id,将其保存在模型 BarList 的 add_list 视图中。这不会保存到我的数据库中,我相信主要问题是我在 add_list.

中的逻辑

我收到以下错误。长字符串是循环中的 id。 Results.id.

IntegrityError at /add/Jlhck4bGoXaXfuoMOKGRww/

NOT NULL constraint failed: API_barlist.api_id

Views.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

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

Urls.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 模板

{% 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 %}

我需要做的事情很少。通过向模型添加约束来修复非空约束错误。此外,我需要完成编写视图才能正确保存。

更新模型

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")

更新视图

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')