Django入门项目实践(中)
生活随笔
收集整理的這篇文章主要介紹了
Django入门项目实践(中)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
4.用戶賬戶
4.1 讓用戶能夠輸入數據
添加新主題
# untitled/learning_logs/forms.py from django import formsfrom .models import Topic, Entryclass TopicForm(forms.ModelForm):class Meta:model = Topicfields = ['text']labels = {'text':''} """定義learning_logs的URL模式""" # untitled/learning_logs/urls.py from django.conf.urls import urlfrom . import viewsapp_name = 'learning_logs'urlpatterns = [# 主頁url(r'^$', views.index, name='index'),url(r'^topics/$', views.topics, name='topics'),url(r'^topics/(?P<topic_id>\d+)/$', views.topic, name='topic'),url(r'^new_topic/$', views.new_topic, name='new_topic'), ] # untitled/learning_logs/views.py from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reversefrom learning_logs.forms import TopicForm from learning_logs.models import Topic#···def new_topic(request):"""添加新主題"""if request.method != 'POST':form = TopicForm()else:form = TopicForm(request.POST)if form.is_valid():form.save()return HttpResponseRedirect(reverse('learning_logs:topics'))context = {'form':form}return render(request, 'learning_logs/new_topic.html', context)#··· <!-- untitled/templates/learning_logs/new_topic.html --> {% extends "learning_logs/base.html" %}{% block content %}<p>Add a new topic:</p><form action="{% url 'learning_logs:new_topic' %}" method='post'>{% csrf_token %}{{ form.as_p }}<button name="submit">add topic</button></form>{% endblock content %}添加新條目
(略)
編輯新條目
(略)
4.2 創建用戶賬戶
應用程序users
# untitled/untitled/settings.py # ··· INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',# 我的應用程序'learning_logs','users' ]# ··· # untitled/untitled/urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include, urlurlpatterns = [path('admin/', admin.site.urls),url(r'^users/', include('users.urls', namespace='users')),url(r'', include('learning_logs.urls', namespace='learning_logs')), ]4.2.1 登錄
由于Django版本的問題,下面的URL模式跟《Python編程從入門到實踐》的示例有點不一樣。
"""為應用程序users定義URL模式""" # untitled/users/urls.py from django.contrib.auth.views import LoginView from django.urls import pathapp_name = 'users'urlpatterns = [path('login/', LoginView.as_view(template_name='users/login.html'), name="login"), ] <!-- untitled/templates/users/login.html --> {% extends "learning_logs/base.html" %}{% block content %}{% if form.errors %}<p>Your username and password didn't match. Please try again.</p>{% endif %}<form method="post" action="{% url 'users:login' %}">{% csrf_token %}{{ form.as_p }}<button name="submit">log in</button><input type="hidden" name="next" value="{% url 'learning_logs:index' %}" /></form>{% endblock content %} <!-- untitled/templates/learning_logs/base.html --> <p><a href="{% url 'learning_logs:index' %}">Learning Log</a> -<a href="{% url 'learning_logs:topics' %}">Topics</a> - {% if user.is_authenticated %}Hello, {{ user.username }}.{% else %}<a href="{% url 'users:login' %}">log in</a>{% endif %} </p>{% block content %}{% endblock %}4.2.2 注銷
# untitled/users/urls.py from django.contrib.auth.views import LoginView from django.urls import path from django.conf.urls import urlfrom . import viewsapp_name = 'users'urlpatterns = [path('login/', LoginView.as_view(template_name='users/login.html'), name="login"),url(r'^logout/$', views.logout_view, name='logout'), ]注意下面導入的是from django.urls import reverse,而不是from django.core.urlresolvers import reverse。
# untitled/users/views.py from django.http import HttpResponseRedirect from django.urls import reverse from django.contrib.auth import logoutdef logout_view(request):"""Log the user out."""logout(request)return HttpResponseRedirect(reverse('learning_logs:index'))4.2.3 注冊
# untitled/users/views.py from django.contrib.auth.forms import UserCreationForm from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.contrib.auth import logout, authenticate, login# ···def register(request):if request.method != 'POST':form = UserCreationForm()else:form = UserCreationForm(data=request.POST)if form.is_valid():new_user = form.save()authenticated_user = authenticate(username=new_user.username, password=request.POST['password1'])login(request, authenticated_user)return HttpResponseRedirect(reverse('learning_logs:index'))context = {'form':form}return render(request, "users/register.html", context) <!-- untitled/templates/users/register.html --> {% extends "learning_logs/base.html" %}{% block content %}<form method="post" action="{% url 'users:register' %}">{% csrf_token %}{{ form.as_p }}<button name="submit">register</button><input type="hidden" name="next" value="{% url 'learning_logs:index' %}" /></form>{% endblock content %}4.3 讓用戶擁有自己的數據
使用@login_required限制訪問
# untitled/learning_logs/views.py from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render# ···@login_required def topics(request):topics = Topic.objects.order_by('date_added')context = {'topics' : topics}return render(request, 'learning_logs/topics.html', context)# ··· # untitled/untitled/settings.py# ···LOGIN_URL = '/users/login/'將數據關聯到用戶
注意這行代碼owner = models.ForeignKey('auth.User', on_delete=models.CASCADE)的寫法。
我們遷移數據庫時,Django將對數據庫進行修改,使其能夠存儲主題和用戶之間的關聯。
執行python manage.py makemigrations learning_logs時,我們為外鍵值指定默認值。
只允許用戶訪問自己的主題
# untitled/learning_logs/views.py# ···@login_required def topics(request):topics = Topic.objects.filter(owner=request.user).order_by('date_added')context = {'topics' : topics}return render(request, 'learning_logs/topics.html', context)# ···保護用戶的主題
# untitled/learning_logs/views.py# ···@login_required def topic(request, topic_id):topic = Topic.objects.get(id=topic_id)if topic.owner != request.user:raise Http404entries = topic.entry_set.order_by('-date_added')context = {'topic': topic, 'entries': entries}return render(request, 'learning_logs/topic.html', context)# ···保護頁面edit_entry
# untitled/learning_logs/views.py# ···@login_required def edit_entry(request, entry_id):"""Edit an existing entry."""entry = Entry.objects.get(id=entry_id)topic = entry.topicif topic.owner != request.user:raise Http404if request.method != 'POST':# Initial request; pre-fill form with the current entry.form = EntryForm(instance=entry)else:# POST data submitted; process data.form = EntryForm(instance=entry, data=request.POST)if form.is_valid():form.save()return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id]))context = {'entry': entry, 'topic': topic, 'form': form}return render(request, 'learning_logs/edit_entry.html', context)將新主題關聯到當前用戶
# untitled/learning_logs/views.py# ···@login_required def new_topic(request):"""添加新主題"""if request.method != 'POST':form = TopicForm()else:form = TopicForm(request.POST)if form.is_valid():new_topic = form.save(commit=False)new_topic.owner = request.usernew_topic.save()return HttpResponseRedirect(reverse('learning_logs:topics'))context = {'form':form}return render(request, 'learning_logs/new_topic.html', context)# ···參考資料:《Python編程從入門到實踐》—【美】Eric Matthes 著
轉載于:https://www.cnblogs.com/gzhjj/p/10591249.html
總結
以上是生活随笔為你收集整理的Django入门项目实践(中)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 优秀知识博文地址
- 下一篇: React ----- 路由懒加载的几种