如何修复:无法将关键字“用户”解析为字段。选项有:description、end_time、id、start_time、title Django 错误

Posted

技术标签:

【中文标题】如何修复:无法将关键字“用户”解析为字段。选项有:description、end_time、id、start_time、title Django 错误【英文标题】:How to Fix: Cannot resolve keyword 'user' into field. Choices are: description, end_time, id, start_time, title Django Error 【发布时间】:2019-08-16 07:07:54 【问题描述】:

大家好,我是 Django 的初学者,我正在尝试在我的 django 规划器中实现一个登录系统。

错误:

/login_user/ 处的字段错误 无法将关键字“用户”解析为字段。选项有:description、end_time、id、start_time、title

我尝试在 model.py 上将用户字段添加到我的事件模型中并迁移它,但它只会使整个应用程序崩溃。


views.py

def event(request, event_id=None):
    instance = Event()
    if event_id:
        instance = get_object_or_404(Event, pk=event_id)
    else:
        instance = Event()

    form = EventForm(request.POST or None, instance=instance)
    if request.POST and form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse('cal:calendar'))
    return render(request, 'cal/event.html', 'form': form)

def login_user(request):

    if request.method == "POST":
        
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)

        if user is not None:
            if user.is_active:
                events = Event.objects.filter(user=request.user)
                login(request, user)
                return render(request, 'cal/calendar.html', 'calendar': calendar)
            else:
                return render(request, 'cal/login.html', 'error_message': 'Your account has been disabled')
        else:
            return render(request, 'cal/login.html', 'error_message': 'Invalid login')
    return render(request, 'cal/login.html')

forms.py

class UserForm(forms.ModelForm):
  password = forms.CharField(widget=forms.PasswordInput)

  class Meta:
    model = User
    fields = ['username', 'email', 'password',]

models.py

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

class Event(models.Model):
    #user = models.ForeignKey(User, default=1)
    title = models.CharField(max_length=200)
    description = models.TextField()
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()

    @property
    def get_html_url(self):
        url = reverse('cal:event_edit', args=(self.id,))
        return f'<a href="url"> self.title </a>'

日历.html

% extends 'cal/base.html' %

% block title %
Calendar
% endblock %

% block content %
<div class="clearfix">
    <a class="btn btn-info left" href="% url 'cal:calendar' %? prev_month "> Previous Month </a>
    <a class="btn btn-info right" href="% url 'cal:calendar' %? next_month "> Next Month </a>
    <a class="btn btn-info right" href="% url 'cal:event_new' %"> New Event </a>
</div>

 calendar 
% endblock %

login.html

% extends 'cal/base_visitor.html' %
% block title %Log In% endblock %
% block login_active %active% endblock %

% block body %
<div class="container-fluid">

    <div class="row">
        <div class="col-sm-12 col-md-6">
            <div class="panel panel-default">
                <div class="panel-body">
                    <h3>Log In</h3>
                    % if error_message %
                        <p><strong> error_message </strong></p>
                    % endif %
                    <form class="form-horizontal" role="form" action="% url 'cal:login_user'%" method="post" enctype="multipart/form-data">
                        % csrf_token %
                        <div class="form-group">
                            <label class="control-label col-sm-2" for="id_username">
                                Username:
                            </label>
                            <div class="col-sm-10">
                                <input id="id_username" maxlength="30" name="username" type="text">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-sm-2" for="id_password">
                                Password:
                            </label>
                            <div class="col-sm-10">
                                <input id="id_password" maxlength="30" name="password" type="password">
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <button type="submit" class="btn btn-success">Submit</button>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="panel-footer">
                    Don't have an account? <a href="% url 'cal:register' %">Click here</a> to register.
                </div>
            </div>
        </div>
    </div>

</div>

% endblock %

【问题讨论】:

【参考方案1】:

在您看来,您正在使用关键字 user 过滤事件对象,但您的事件模型没有名为 user 的字段。如果您希望您的事件与用户相关联,您可以在事件模型中添加外键:

class Event(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    title = models.CharField(max_length=200)
    description = models.TextField()
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()

    @property
    def get_html_url(self):
        url = reverse('cal:event_edit', args=(self.id,))
        return f'<a href="url"> self.title </a>'

或者,在您看来,您可以简单地通过另一个关键字过滤您的事件对象,您的错误为您提供了选择,而这些选择正是您在模型中指定的字段。所以在你看来你可以这样做:

def login_user(request):

    if request.method == "POST":

        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)

        if user is not None:
            if user.is_active:
                events = Event.objects.filter(title='Title you want to filter by') # This line seems to be the source of your error. You just need to filter by a keyword that exists in your model.
                login(request, user)
                return render(request, 'cal/calendar.html', 'calendar': calendar)
            else:
                return render(request, 'cal/login.html', 'error_message': 'Your account has been disabled')
        else:
            return render(request, 'cal/login.html', 'error_message': 'Invalid login')
    return render(request, 'cal/login.html')

【讨论】:

【参考方案2】:

在您的 models.py 中,您错过了为用户表添加关系。添加用户并做一个

python manage.py makemigrations myapp

python manage.py migrate myapp

from django.contrib.auth import get_user_model

class Event(models.Model):
    user = models.ForeignKey(get_user_model(), null=True)
    title = models.CharField(max_length=200)
    description = models.TextField()
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()

    @property
    def get_html_url(self):
        url = reverse('cal:event_edit', args=(self.id,))
        return f'<a href="url"> self.title </a>'

【讨论】:

以上是关于如何修复:无法将关键字“用户”解析为字段。选项有:description、end_time、id、start_time、title Django 错误的主要内容,如果未能解决你的问题,请参考以下文章

无法将关键字“用户”解析为字段。选项有:create_account、email、full_name

无法将关键字“用户”解析为字段 - django 错误

字段错误在/。无法将关键字“textField”解析为字段

无法将关键字'user'解析为字段-Django错误

无法将关键字 u'slug' 解析为 Django 中的字段错误?

如何修复文本字段中错误的键盘布局导致的错误