Skip to content
Advertisement

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

I am using the Yelp API to search bars in a any location. This uses a template called results.html that has a button. Clicking this button should save the Yelp API unique ID of a Bar into my models. In my results dictionary that I loop over I call this ‘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. This will not save to my database, I believe the main problem is my logic in add_list.

I get the following error. The long string is the id from the loop. 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 template

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

Advertisement

Answer

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')
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement