时间:2023-02-09 10:42:01 | 来源:建站知识
时间:2023-02-09 10:42:01 来源:建站知识
最近收到很多读者的鼓励,非常开心,这给了我更多将公众号持续更新下去的动力。今天还收到微信公众号开通以来的第一份赞赏,在这里要特别感谢橘子同学。如果你学习的是Python Web开发和Django,本公众号绝对不会让你失望,我会争取所有文章做到清晰易懂,原创免费。如果你是老鸟,本公众号的内容也可以作为系统性的参考资料。from django.urls import path, re_pathfrom . import views# namespaceapp_name = 'blog'urlpatterns = [ # 展示所有文章 path('/index/', views.ArticleListView.as_view(), name='article_list'), # 展示文章详情 re_path(r'^article/(?P<pk>/d+)/(?P<slug1>[-/w]+)/$', views.ArticleDetailView.as_view(), name='article_detail'), # 添加文章 re_path(r'^article/create/$', views.ArticleCreateView.as_view(), name='article_create'),]
from .models import Article, from django.http import HttpResponseRedirectfrom django.shortcuts import renderfrom .forms import ArticleFormdef article_create(request): if request.method == 'POST': form = ArticleForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect("/index/") else: form = ArticleForm() return render(request, 'blog/article_create_form.html', {'form': form})
如果/index/页面有分页功能, 你还可以通过使用HttpResponseRedirect('/index/?page=2')直接获取第2页的文章列表。......from django.http import HttpResponseRedirectfrom django.urls import reverse.....def article_create(request): if request.method == 'POST': form = ArticleForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('blog:article_list')) ....
from .models import Articlefrom django.http import HttpResponseRedirectfrom django.urls import reversefrom django.shortcuts import renderfrom .forms import ArticleFormdef article_create(request): if request.method == 'POST': form = ArticleForm(request.POST) if form.is_valid(): article = form.save() return HttpResponseRedirect(reverse('blog:article_detail', args=[str(article.pk), article.slug])) else: form = ArticleForm() return render(request, 'blog/article_create_form.html', {'form': form})
reverse('blog:article_detail', args=[str(article.pk), article.slug]
from django.shortcuts import redirectfrom django.urls import reverse# 案例1def my_view(request): ... return redirect('/index/')# 案例2def my_view(request): ... return redirect('https://www.baidu.com/')# 案例3def my_view(request): ... return redirect(reverse('blog:article_list'))
redirect真正NB的地方在于,它不仅能根据URL重定向,还可以根据对象Object重定向和根据视图view重定向,根据视图重定向的时候还可以传递额外的参数。from django.shortcuts import redirectdef my_view(request): ... obj = MyModel.objects.get(...) return redirect(obj)
def my_view(request): ... return redirect('some-view-name', foo='bar')
def get_absolute_url(self): return reverse('blog:article_detail', args=[str(self.pk), self.slug])
from django.urls import reversefrom django.shortcuts import redirectdef my_view(request): ... return redirect(reverse('admin:app_list', kwargs={'app_label': 'auth'}))
from django.urls import reversefrom blog import viewsreverse(views.index)
关键词:方法