Django 实战 | 搭一个 GitHub 用户展示网站 04

一、搜索页面跳转

在 urls.py 中添加一个 user 路径:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name="home"),
    path('user/', views.user, name="user"),
]

在 views.py 中添加一个 user 方法:

def user(request):
    return render(request,'user.html',{})

再在 templates 创建 user.html:

{% extends 'base.html' %}

{% block content %}
    <h1>Hello User!</h1>


{% endblock %}

然后启动 Django 服务,访问 http://127.0.0.1:8000/user/ 可以看到如下页面:

在 base.html 中修改如下代码:

<form class="form-inline my-2 my-lg-0" method="POST" action="{% url 'user' %}">

然后在搜索框内搜索一个用户名,发现:

因此需要设置 CSRF,在上面那行代码下面添加一行代码:

{% csrf_token %}

在 views.py 中修改 user 方法:

def user(request):
    user = request.POST['user']
    return render(request,'user.html',{'user':user})

再在 base.html 中在之前写的 csrf 下面修改 input 这行代码如下:

<input class="form-control mr-sm-2" name="user" type="search" placeholder="Search" aria-label="Search">

再在 user.html 中修改:

{% extends 'base.html' %}

{% block content %}
    <h1>Hello {{user}}!</h1>


{% endblock %}

在页面中的搜索框输入一个用户名,可以看到如下页面:

二、获取搜索数据

修改 base.html 部分代码:

<a class="navbar-brand" href="{% url 'home' %}">Wonz</a>

<a class="nav-link" href="{% url 'user' %}">查询</a>

在 views.py 中修改 user 方法:

def user(request):
    if request.method == 'POST':
        user = request.POST['user']
        user_request = requests.get("https://api.github.com/users/"+user)
        username = json.loads(user_request.content)
        
        return render(request,'user.html',{'user':user, 'username':username})
    else:
        notfound = "请在搜索框中输入您需要查询的用户..."
        return render(request,'user.html',{'notfound':notfound})

在 user.html 中修改代码:

{% extends 'base.html' %}

{% block content %}
    
    {% if notfound %}
        <h2>{{notfound}}</h2>
    {% else %}
        <h1>{{username}}</h1>
    {% endif %}

{% endblock %}

在页面中的搜索框输入一个用户名,可以看到如下页面,表示用户信息都获取到了:

三、显示所有数据

修改 user.html 代码,也做成卡片格式进行展示:

{% extends 'base.html' %}

{% block content %}
    
    {% if notfound %}
        <h2>{{notfound}}</h2>
    {% else %}
        <div class="card" style="width: 18rem;">
            <img src="{{username.avatar_url}}" class="card-img-top" alt="Card image cap">
            <div class="card-body">
                <h5 class="card-title">{{username.name}}</h5>
                <p class="card-text">location: {{username.location}}</p>
                <p class="card-text">public_repos: {{username.public_repos}}</p>
                <p class="card-text">public_gists: {{username.public_gists}}</p>
                <p class="card-text">followers: {{username.followers}}</p>
                <p class="card-text">following: {{username.following}}</p>
                <p class="card-text">created_at: {{username.created_at}}</p>
                <p class="card-text">updated_at: {{username.updated_at}}</p>
            </div>
        </div>
    {% endif %}

{% endblock %}

Bootstrap4巨幕复制示例代码,拷贝到 home.html 中,并进行相应修改:

    <div class="jumbotron jumbotron-fluid">
        <div class="container">
        <h1 class="display-4">用 Django 搭一个 GitHub 用户展示网站</h1>
        <p class="lead">快速入门 Django</p>
        </div>
    </div>

最终成果网站主页展示如下:
在这里插入图片描述

搜索用户展示如下:
在这里插入图片描述

四、代码地址

GitHub

五、参考教程

Django小白入门到实战教程(2020) P13-P15

![图片说明](https://img-ask.csdn.net/upload/201904/01/1554112752_11759.png) ![图片说明](https://img-ask.csdn.net/upload/201904/01/1554112854_18340.png) 具体代码如下 html文件应该没错 views.py: from django.shortcuts import render # Create your views here. from django.template import loader,Context from django.http import HttpResponse from blog.models import BlogPost def archive(request): posts = BlogPost.objects.all(); #@UndefinedVariable t = loader.get_template('archive.html') c = Context({'posts': posts}) return HttpResponse(t.render(c)) models.py: from django.db import models from django.contrib import admin # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length = 150) content = models.TextField() timestamp = models.DateTimeField() class BlogPostAdmin(admin.ModelAdmin): list_display = ('title', 'content', 'timestamp') admin.site.register(BlogPost, BlogPostAdmin) settings.py: TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog' ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'wangxiran.urls' WSGI_APPLICATION = 'wangxiran.wsgi.application' # Database # https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'wangxiran', 'USER':'root', 'PASSWORD':'Aa123456', 'HOST':'127.0.0.1', 'POST':'3306', } } # Internationalization # https://docs.djangoproject.com/en/dev/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/dev/howto/static-files/ STATIC_URL = '/static/' urls.py: from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() from blog.views import archive urlpatterns = patterns('', # Examples: # url(r'^$', 'wangxiran.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^blog/', archive), ) 照着网上教材做的 但是就是出不来啊 求大佬们帮帮
©️2020 CSDN 皮肤主题: 像素格子 设计师:CSDN官方博客 返回首页