基于django的服装商场制作代码
时间: 2023-09-03 22:06:54 浏览: 124
以下是一个基于 Django 的简单服装商场的示例代码:
首先,创建一个 Django 项目和应用:
```
$ django-admin startproject clothing_store
$ cd clothing_store
$ python manage.py startapp store
```
在 `clothing_store/store/models.py` 文件中定义商品模型:
```python
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=50)
description = models.TextField()
price = models.DecimalField(max_digits=6, decimal_places=2)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
def __str__(self):
return self.name
```
在 `clothing_store/store/views.py` 文件中定义商品列表视图:
```python
from django.shortcuts import render
from .models import Product
def product_list(request):
products = Product.objects.all()
context = {'products': products}
return render(request, 'store/product_list.html', context)
```
在 `clothing_store/store/templates/store/product_list.html` 文件中定义商品列表模板:
```html
{% extends 'base.html' %}
{% block content %}
<h1>Products</h1>
<ul>
{% for product in products %}
<li>{{ product.name }} - {{ product.price }}</li>
{% endfor %}
</ul>
{% endblock %}
```
在 `clothing_store/urls.py` 文件中定义路由:
```python
from django.urls import path
from store.views import product_list
urlpatterns = [
path('products/', product_list, name='product_list'),
]
```
最后,运行开发服务器:
```
$ python manage.py runserver
```
现在,你可以在浏览器中访问 `http://127.0.0.1:8000/products/` 来查看商品列表了。
阅读全文