简体   繁体   中英

How can i add something to the database with a submit button in Django?

I'm making a grocery list web app in django and i have a page with your groceries list and i have a page with all the products you can add to your list.

every product has a button "add to list". The intention is that when you click on that button that that product automatically becomes added to the groceries list. Does someone know how to do that? thank you in advance.

The Groceries List page

The all products page

models.py

from django.db import models

# Create your models here.

class Brand(models.Model):
    name = models.CharField(max_length=200, null=True)

    def __str__(self):
        return self.name

class AllProducts(models.Model):
    name = models.CharField(max_length=200, null=True)

    def __str__(self):
        return self.name



class ShoppingList(models.Model):
    product = models.ForeignKey(AllProducts, null=True, on_delete= models.SET_NULL, blank=True)
    brand = models.ForeignKey(Brand, null=True, on_delete= models.SET_NULL, blank=True)
    quantity = models.CharField(max_length=200, null=True, blank=True)
    info = models.TextField(max_length=500, null=True, blank=True)


    def __str__(self):
        return self.product

The class brand is a class with all the brands of the products. The class All_Products is a class with all the products that you can add to your groceries list. And the class ShoppingList is a class with all the products in the groceries list.

Views.py

def home(request):
    products = ShoppingList.objects.all()

    context = {
        'products':products,
    }

    return render(request, 'groceries_list/home.html', context )

def all_products(request):
    all_products = AllProducts.objects.all()
    context = {
        'products':all_products,

    }
    return render(request, 'groceries_list/all_products.html', context)

The home function is the function that handels the groceries list page an the all_products function is the function that handels the page with all the product you can add to your list.

groceries list template

{% extends "groceries_list/base.html" %}
{% block content %}
<div class="card">
  <div class="card-body">
    <div class="card m-1 text-white">
      <a href="{% url 'create_grocery' %}" class="btn btn-success btn-md btn-block ">Add Grocery</a>
    </div>
    {% for product in products %}
    <div class="item-row">
        <div class="card m-1 text-white" style="background-color: #9BD6E0;">
            <div class="card-body">
            <a class="btn btn-sm btn-info" href="{% url 'update_gorcery' product.id %}">Update</a>
            <a class="btn btn-sm btn-danger" href="{% url 'delete_gorcery' product.id %}">Delete</a>
            <span class="text-dark"><strong>{{product.product}}</strong>  {{product.quantity}} </span>
            </div>
        </div>
    </div>
    {% endfor %}
  </div>

</div>
{% endblock  %} 

all products template

% extends "groceries_list/base.html" %}
{% block content %}
<div class="card">
  <div class="card-body">
    <div class="card m-1 text-white">
      <a href="{% url 'create_product' %}" class="btn btn-success btn-md btn-block ">Add Product</a>

    </div>


    {% for product in products %}
    <div class="item-row">
        <div class="card m-1 text-white" style="background-color: #9BD6E0;">
            <div class="card-body">
            <button type="submit" class="btn btn-success btn-sm ">Add To List</button>

           <span class="text-dark ml-3 text-center"><strong>{{product.name}}</strong>
             <a class="btn btn-sm btn-danger float-right" href="{% url 'delete_product' product.id %}">Delete</a>
            </div>
        </div>
    </div>
    {% endfor %}
  </div>

</div>
{% endblock  %} 

The site may have many users using it at the same time, so you should arrange for a way to identify the particular user who adds the item to the shopping list. The easiest way to do this is to create an authentication system (You can use as-is or extend the User model) from django.auth.models Looking at your views, as they are, both the home() and and all_products() view are rendering the same context, which definitely can't be what is in the cart (for the home view).

A way to handle this would be to make your ShoppingList model in a way that it includes a field for the customer . The customer would be the user making the request . In the all_products.html page, you can create a form with a hidden field that you pre-populate with the product.id and the 'add to list' button as a submit button for this form. When a user clicks 'add to list', the form gets posted to a url that invokes the responsible view. In that view, you create a ' ShoppingList object ' (an instance of the ShoppingList model that you created in models) with values of the product.id that was posted by the form and the customer as request.user (the user making the request). Just a few random tips: In your ShoppingList model , you are defining quantity as a CharField but quantity is best defined as an IntegerField . Also, there is no need to use both blank=True and null=True arguments. I personally like to use blank=True only due to safety reasons that I won't talk about here. I would also recommend that you revise the naming systems for your models and views.

In summary:

  • Add field customer to the ShoppingList model.
  • Make field product a CharField.
  • Make a form with a hidden field that posts back the product.id when a user clicks 'add to list'.
  • Handle the post request by making a ShoppingList object.
  • Consider making quantity an IntegerField.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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