简体   繁体   English

如何在Django中比较表单,模型和auth_User

[英]How to compare form, model and auth_User in Django

I have a idea to create something like a admin panel. 我有一个创建类似管理面板的想法。 In that panel the user (or admin as well) for example in my case will can add a field named "website". 例如,在我的情况下,用户(或管理员)可以在该面板中添加一个名为“网站”的字段。 And in this moment I have a problem. 在这一刻,我有一个问题。 I've create in myapp model Website: 我已经在myapp模型网站中创建了:

from django.db import models
from django.contrib.auth.models import User

class Website(models.Model):
    user = models.ForeignKey(User,related_name="website_user", on_delete=models.CASCADE)
    website = models.CharField(help_text="Podaj stronę wraz z http lub https",max_length=250,verbose_name='Strona www', unique=True)

    class Meta:
        verbose_name = 'Strona www'
        verbose_name_plural = 'Strony www'

    def __str__(self):
        return self.website

after that I've create a form to display for the user when is loggin: 之后,我创建了一个表单以在登录时显示给用户:

from django import forms
from django.contrib.auth.models import User
from .models import Website

class WebsiteForm(forms.ModelForm):
    class Meta:
        model = Website
        fields = ('website',)

Next step was a creating view : 下一步是创建视图:

from django.shortcuts import render
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from .forms import LoginForm, UserRegistrationForm, WebsiteForm
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Website
...
@login_required
def add_website(request):
    if request.method == 'POST':
        website_form = WebsiteForm(data=request.POST)
        if website_form.is_valid():
            new_website = website_form.save(commit=False)
            new_website.post = add_website
            new_website.save()
    else:
        website_form = WebsiteForm()
    return render(request, 'konto/add_website.html', {'add_website': add_website, 'website_form': website_form})

and on the end I've create a html file responsible for displaying form and action 最后,我创建了一个HTML文件,负责显示表单和操作

        {% if request.user.is_authenticated %}
        {% if new_website %}
        <h2>Twója strona oczekuje na zaakceptowanie</h2>
        {% else %}
        <h4>Dodaj stronę do monitorowania</h4>
        <form action="." method="POST">
        {{website_form.as_p}}
        {% csrf_token %}
        <p><input type="submit" value="Dodaj stronę"></p>
        </form>
        {% endif %}
        <a href="{% url 'dashboard' %}">Powrót</a>
        {% endif %}

My problem is that, when I'am login as for example admin, I trying to add new record using this form. 我的问题是,当我以管理员身份登录时,我试图使用此表单添加新记录。 But the nothing is happen. 但是什么也没有发生。 I fill the form, and after click button the script redirecting me to the dashboard. 我填写表格,单击按钮后,脚本将我重定向到仪表板。 In dashboard I have a blank list of added websites. 在信息中心中,我有添加网站的空白列表。 part of code in dashboard.html dashboard.html中部分代码

...
{% if request.user.is_authenticated %}
Twoja www:
{% for website in websites %}
{{website.website}}
{% endfor %}
{% endif %}
...

and the view for displaying list of websites: 以及用于显示网站列表的视图:

@login_required
def website(request):
    websites = Website.objects.all().order_by('-User')
    context = {'websites:', websites}
    return render(request, 'konto/dashboard.html', context=context)

I want to make a list of pages, so that the user who added the page, only saw his records and not all that exist in the database. 我要列出页面,以便添加页面的用户只能看到他的记录,而看不到数据库中所有的记录。 EDIT: And sometimes when I change form link I have a error 编辑:有时当我更改表单链接时,我会遇到一个错误

IntegrityError at /konto/add-website/
NOT NULL constraint failed: konto_website.user_id

EDIT: 编辑:

Now I have something like this: 现在我有这样的事情:

@login_required
def new_website(request):
    if request.method == "POST":
        new_website = WebsiteForm(request.POST)
        if new_website.is_valid():
            new_website=new_website.save(commit=False)
            new_website.user = request.user
            new_website.save()
            messages.success(request, 'Pomyślnie dodano stronę')
            return render(request, 'konto/add_website_ok.html')
    else:
        new_website = WebsiteForm()
    return render(request, 'konto/add_website.html', {'new_website':new_website})

Everything is working ok, if I'am login as admin, I can add new website as a admin. 一切正常,如果我以管理员身份登录,则可以将新网站添加为管理员。 If I login for example as a user, I can add new website as a user. 例如,如果我以用户身份登录,则可以以用户身份添加新网站。 In Django Admin I can see every record whos was added by users. 在Django Admin中,我可以看到用户添加的每条记录whos。 But I've create also something like dashboard in my own control panel. 但我也在自己的控制面板中创建了类似仪表盘的内容。 And in that control panel I want to display the list of websites added by users. 在该控制面板中,我要显示用户添加的网站列表。 For example, if I'am login as 'user' i can see only my webpages, not all from the list. 例如,如果我以“用户”身份登录,则只能看到我的网页,而不能看到列表中的所有网页。 I want to display it in dashboard.html as: 我想在dashboard.html中将其显示为:

{% if request.user.is_authenticated %}
<b>Monitoring www:</b>
{% for website in website_list %}
{{website.website}}
{% endfor %}
{% endif %}

But now I see only a label 'Monitoring www', nothing else.. I think You understand me. 但是现在我只看到一个标签“监控www”,其他都没有。.我认为您理解我。 :) :)

2nd EDIT 第二次编辑

view @login_required 查看@login_required

def website(request):
    website_list = Website.objects.filter(user=request.user).order_by('-User')
    context = {'website_list:', website_list}
    return render(request, 'konto/dashboard.html', context=context)

html HTML

{% for website in website_list %}
{{website.website}}
{% endfor %}
{% endif %}

I'm not sure what you're doing here 我不确定你在这里做什么

    if website_form.is_valid():
        new_website = website_form.save(commit=False)
        new_website.post = add_website
        new_website.save()

But I think it should work if it is simplified to: 但我认为,如果将其简化为:

    if website_form.is_valid():
        new_website = website_form.save()


@login_required
def add_website(request):
    variables = {}
    if request.method == 'POST':
        website_form = WebsiteForm(data=request.POST)
        if website_form.is_valid():
            new_website = website_form.save(commit=False)
            new_website.post = add_website
            new_website.save()
    else:
        website_form = WebsiteForm()

    variables['add_website'] = add_website
    variables['website_form'] = website_form
    if new_website: variables['new_website'] = True

    return render(request, 'konto/add_website.html', variables)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM