时间:2023-05-29 04:33:01 | 来源:网站运营
时间:2023-05-29 04:33:01 来源:网站运营
Django实战教程: 开发餐厅在线点评网站(1):小编我最喜欢写Django的基础知识,尤其是一个一个细小的知识点。因为我相信无论你是新手还是高手,熟练地掌握基础知识才能在实际Web开发项目中游刃有余。然而我们学习Django的最终目的还是应用,今天小编我就带你用Django开发一个餐厅在线点评的APP,也算应读者的要求。如果你对本文中的代码阅读起来还感觉有点吃力,建议关注我的微信公众号,点击经典原创阅读Django基础(1)到(12)。如果对代码有任何问题或不理解,可以在评论区留言。INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django.contrib.sites', 'myrestaurants', 'users',]
因为我们要用到静态文件如css和图片,我们需要在settings.py里设置STATIC_URL和MEDIA。用户上传的图片会放在/media/文件夹里。STATIC_URL = '/static/'STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"), ]# specify media root for user uploaded files,MEDIA_ROOT = os.path.join(BASE_DIR, 'media')MEDIA_URL = '/media/'
整个项目的urls.py如下所示。我们把myrestaurants的urls.py也加进去了。别忘了在结尾部分加static配置。from django.conf.urls import url, includefrom django.contrib import adminfrom django.conf import settingsfrom django.conf.urls.static import staticurlpatterns = [ url(r'^myrestaurants/', include('myrestaurants.urls')), url(r'^admin/', admin.site.urls), url(r'^accounts/', include('users.urls')),] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.db import modelsfrom django.contrib.auth.models import Userfrom datetime import datefrom django.urls import reverseclass Restaurant(models.Model): name = models.TextField() address = models.TextField(blank=True, default='') telephone = models.TextField(blank=True, default='') url = models.URLField(blank=True, null=True) user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) date = models.DateField(default=date.today) def __str__(self): return self.name def get_absolute_url(self): return reverse('myrestaurants:restaurant_detail', args=[str(self.id)])class Dish(models.Model): name = models.TextField() description = models.TextField(blank=True, default='') price = models.DecimalField('USD amount', max_digits=8, decimal_places=2, blank=True, null=True) user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) date = models.DateField(default=date.today) image = models.ImageField(upload_to="myrestaurants", blank=True, null=True) restaurant = models.ForeignKey(Restaurant, null=True, related_name='dishes', on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('myrestaurants:dish_detail', args=[str(self.restaurant.id), str(self.id)])# This Abstract Review can be used to create RestaurantReview and DishReviewclass Review(models.Model): RATING_CHOICES = ((1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five')) rating = models.PositiveSmallIntegerField('Rating (stars)', blank=False, default=3, choices=RATING_CHOICES) comment = models.TextField(blank=True, null=True) user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) date = models.DateField(default=date.today) class Meta: abstract = Trueclass RestaurantReview(Review): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, related_name="reviews") def __str__(self): return "{} review".format(self.restaurant.name)
from django.urls import path, re_pathfrom . import views# namespaceapp_name = 'myrestaurants'urlpatterns = [# 查看餐厅列表 path('', views.RestaurantList.as_view(), name='restaurant_list'),# 查看餐厅详情, 如/myrestaurants/restaurant/1/ re_path(r'^restaurant/(?P<pk>/d+)/$', views.RestaurantDetail.as_view(), name='restaurant_detail'),# 创建餐厅, 如:/myrestaurants/restaurant/create/ re_path(r'^restaurant/create/$', views.RestaurantCreate.as_view(), name='restaurant_create'),# 编辑餐厅详情, 如: /myrestaurants/restaurant/1/edit/ re_path(r'^restaurant/(?P<pk>/d+)/edit/$', views.RestaurantEdit.as_view(), name='restaurant_edit'),]
# Create your views here.from django.http import HttpResponseRedirectfrom django.shortcuts import get_object_or_404, renderfrom django.urls import reversefrom django.views.generic import DetailView, ListView, UpdateViewfrom django.views.generic.edit import CreateViewfrom .models import RestaurantReview, Restaurant, Dishfrom .forms import RestaurantForm, DishFormclass RestaurantList(ListView): queryset = Restaurant.objects.all().order_by('-date') context_object_name = 'latest_restaurant_list' template_name = 'myrestaurants/restaurant_list.html'class RestaurantDetail(DetailView): model = Restaurant template_name = 'myrestaurants/restaurant_detail.html' def get_context_data(self, **kwargs): context = super(RestaurantDetail, self).get_context_data(**kwargs) context['RATING_CHOICES'] = RestaurantReview.RATING_CHOICES return contextclass RestaurantCreate(CreateView): model = Restaurant template_name = 'myrestaurants/form.html' form_class = RestaurantForm # Associate form.instance.user with self.request.user def form_valid(self, form): form.instance.user = self.request.user return super(RestaurantCreate, self).form_valid(form)class RestaurantEdit(UpdateView): model = Restaurant template_name = 'myrestaurants/form.html' form_class = RestaurantForm
重要知识点:from django.forms import ModelForm, TextInput, URLInput, ClearableFileInputfrom .models import Restaurant, Dishclass RestaurantForm(ModelForm): class Meta: model = Restaurant exclude = ('user', 'date',) widgets = { 'name': TextInput(attrs={'class': 'form-control'}), 'address': TextInput(attrs={'class': 'form-control'}), 'telephone': TextInput(attrs={'class': 'form-control'}), 'url': URLInput(attrs={'class': 'form-control'}), } labels = { 'name': '名称', 'address': '地址', 'telephone': '电话', 'url': '网站', }
{% extends "myrestaurants/base.html" %}{% block content %}<h3>餐厅列表</h3><ul> {% for restaurant in latest_restaurant_list %} <li><a href="{% url 'myrestaurants:restaurant_detail' restaurant.id %}"> {{ restaurant.name }}</a></li> {% empty %}<li>对不起,没有餐厅点评。</li> {% endfor %}</ul> {% if request.user.is_authenticated %}<p><span class="glyphicon glyphicon-plus"></span> <a href="{% url 'myrestaurants:restaurant_create' %}">添加餐厅</a></p> {% else %}<p>请<a href="{% url 'users:login' %}?next={% url 'myrestaurants:restaurant_create' %}">登录</a>后添加餐厅。</p> {% endif %}{% endblock %}
重要知识点:{% extends "myrestaurants/base.html" %}{% block content %}<h3> {{ restaurant.name }} {% if request.user == restaurant.user %} (<a href="{% url 'myrestaurants:restaurant_edit' restaurant.id %}">修改</a>) {% endif %}</h3><h4>地址</h4><p> {{ restaurant.address }}, <br/> {{ restaurant.telephone }}</p><h4>菜单 {% if request.user.is_authenticated %} (<a href="{% url 'myrestaurants:dish_create' restaurant.id %}">添加</a>) {% endif %}</h4><ul> {% for dish in restaurant.dishes.all %} <li><a href="{% url 'myrestaurants:dish_detail' restaurant.id dish.id %}"> {{ dish.name }}</a> - {{ dish.price }}元</li> {% empty %}<li>对不起,该餐厅还没有菜肴。</li> {% endfor %}</ul><h4>用户点评</h4>{% if restaurant.reviews.all %} {% for review in restaurant.reviews.all %} <p>{{ review.rating}}星, {{ review.user }}点评, {{ review.date | date:"Y-m-d" }}</p> <p>{{ review.comment }}</p> {% endfor %}{% else %}<p>目前还没有用户点评。</p>{% endif %}<h4>添加点评</h4>{% if request.user.is_authenticated %}<form action="{% url 'myrestaurants:review_create' restaurant.id %}" method="post"> {% csrf_token %} <p>评论</p> <textarea name="comment" id="comment"></textarea> <p>评分</p> <p> {% for rate in RATING_CHOICES %} <input type="radio" name="rating" id="rating{{ forloop.counter }}" value="{{ rate.0 }}" /> <label for="choice{{ forloop.counter }}">{{ rate.0 }}星</label> <br/> {% endfor %} </p> <input type="submit" value="提交" /></form>{% else %}<p>请先<a href="{% url 'users:login' %}?next={% firstof request.path '/' %}">登录</a>再评论。</p>{% endif %}{% endblock %}
重要知识点:{% extends "myrestaurants/base.html" %}{% block content %}<form action="" method="post" enctype="multipart/form-data" > {% csrf_token %} {% for hidden_field in form.hidden_fields %} {{ hidden_field }}{% endfor %}{% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} {{ error }} {% endfor %} </div>{% endif %}{% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} {{ field }} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} </div>{% endfor %} <input type="submit" value="提交"/></form>{% endblock %}
# base.html{% load static %}<!DOCTYPE html><html lang="en"><head><title>{% block title %} Django餐厅点评系统{% endblock %} </title><meta charset="utf-8"><meta name="keywords" content="{% block keywords %} some keywords{% endblock %} "><meta name="description" content="{% block description %} Django web application example.{% endblock %}"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"><link rel="stylesheet" href="{% static 'myrestaurants/custom.css' %}"></head><body class="bs-docs-home"><nav class="navbar navbar-inverse navbar-static-top bs-docs-nav"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#"><strong>Django餐厅点评APP</strong></a> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li class="dropdown"> <a class="dropdown-toggle btn-green" data-toggle="dropdown" href="#"><span class="glyphicon glyphicon-user"></span> {{ user.username }} <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="{% url 'users:profile' user.id %}">我的账户</a></li> <li><a href="{% url 'users:logout' %}">退出登录</a></li> </ul> </li> {% else %} <li class="dropdown"><a class="dropdown-toggle btn-green" href="{% url 'users:register' %}"><span class="glyphicon glyphicon-user"></span> 注册</a></li> <li class="dropdown"><a class="dropdown-toggle" href="{% url 'users:login' %}" ><span class="glyphicon glyphicon-log-in"></span> 登录</a></li> {% endif %} </ul> </div> </div></nav> <!-- Page content of course! --><main id="section1" class="container-fluid"><div class="container"> <div class="row"> <div class="col-sm-12"> <div class="wrapper"> <div class="newsbox"> <div class="container1"> {% block content %} {% if error_message %}<p><strong>{{ error_message}}</strong></p>{% endif %} {% endblock %} </div> </div> </div></div></div> </div> </main><footer class="footer"> {% block footer %}{% endblock %}</footer><!--End of Footer--><!-- Bootstrap core JavaScript================================================== --><script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script></body></html>
关键词:餐厅,实战,教程