表单提交多对多,一对多,组,工作小技巧



models.py
from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Userprofile(models.Model):
    user=models.OneToOneField(User)
    nick_name=models.CharField(max_length=50)
class Host(models.Model):
    host_name=models.CharField(max_length=50)
    host_user=models.ManyToManyField(Userprofile)



finish.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
欢迎:{{ request.user.userprofile.nick_name }}用户
{% for foo in request.user.userprofile.host_set.all %}
{{ foo.host_name }}

{% endfor %}
</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>title</title>
</head>
<body>
<form action="/logins" method="get">
    <table>

           <tr><td>用户:</td><td><input type="text" name="username"></td></tr>

            <tr><td>密码:</td><td><input type="password" name="password"></td></tr>

            <tr><td><input type="submit" value="提交"></td></tr>

    </table>
</form>
</body>
</html>



views.py
#encoding:utf8
from django.shortcuts import render,HttpResponseRedirect
from django.contrib.auth import login,authenticate
from django.contrib.auth.decorators import login_required
from son1.models import *
# Create your views here.
def index(request):
    user=Userprofile.objects.get(nick_name="小红帽")
    list=user.host_set.all()
    return render(request,'index.html',locals())
def logins(request):
    username=request.GET.get('username')
    password=request.GET.get('password')
    user=authenticate(username=username,password=password)
    if user is not None:
        if user.is_active:
            login(request,user)
            return HttpResponseRedirect('/')
    return render(request,'index.html',locals())

def finish(request):
    return render(request,'finish.html',locals())



urls.py
from django.conf.urls import url
from django.contrib import admin
from son1.views import *
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/',index),
    url(r'^$',finish),
    url(r'^logins/',logins),
]



创建用户,,,
导入数据库
_set为反向查找

















































posted @ 2017-01-17 15:04  二梦非凡  阅读(565)  评论(0编辑  收藏  举报