Django 框架:'UserView' 对象没有属性 'object'

Django Framework: 'UserView' object has no attribute 'object'

我是第一次使用 Django Framework 并且我也在构建一个停止在这里工作的其他人的代码,所以我遇到了一些麻烦...

我正在尝试创建 Web 表单以将数据提交到数据库,但收到错误消息 'UserView' object has no attribute 'object'

models.py:

from django.db import models

class UserInfo(models.Model):
    first_name = models.CharField(max_length=20, verbose_name='First Name', help_text='Your given name. *REQUIRED**')
    last_name = models.CharField(max_length=100, verbose_name='Last Name', help_text='Your family name. *REQUIRED*.')
    office_address = models.CharField(max_length=200 ,verbose_name='Office address', help_text='The address where you can be reached rather than your institution’s head office. *REQUIRED*')
    research_interest = models.CharField(max_length=1000 ,verbose_name='Short summary of your research interests',help_text='In one or two sentences please describe your research interests and how access to the RD-Connect platform is relevant for you. *REQUIRED*' )
    institution = models.CharField(max_length=50, verbose_name='Name of institution', help_text='The institution (university, hospital etc.) with which you have your primary affiliation. *REQUIRED*')
    institute_website = models.URLField(max_length=100, null=True, blank=True, default="", verbose_name='Institute website', help_text='Your institution’s main website.')
    job_title = models.CharField(max_length=100, null=True, blank=True, verbose_name='Position within institution', help_text='Your job title within your institution.')
    email = models.EmailField(max_length=100, verbose_name='Institutional email address', help_text='Use of an institutional email address issued by your place of work is part of our validation procedure. If you do not have one please contact help@rd-connect.eu to explain your circumstances')
    department = models.CharField(max_length=50, null=True, blank=True, verbose_name='Name of your department', help_text='Your department within your institution (e.g. Neurology, Genetics, etc.')
    orcid_profile = models.URLField(max_length=100,null=True, blank=True, verbose_name='ORCID profile', help_text='If you have an ORCID profile, please paste the link here.')
    linkedin_profile = models.URLField(max_length=100,null=True, blank=True, verbose_name='LinkedIn profile', help_text='If you have a LinkedIn profile, please paste the link here.')
    publications = models.URLField(max_length=100,null=True, blank=True, verbose_name='Three recent publications', help_text='Please paste links to three recent representative publications of which you are an author (link to the article on the journal website or to the PubMed page).')
    researchgate_profile = models.URLField(max_length=100,null=True, blank=True, verbose_name='ResearchGate profile', help_text='If you have a ResearchGate profile, please paste the link here.')
    departmentweb_profile = models.URLField(max_length=100,null=True, blank=True, verbose_name='Department web profile', help_text='If you or your group has a profile on your university or departmental website please paste the link here.')
    adherence_agreement = models.FileField(verbose_name='Adherence Agreement', help_text='I confirm that I have read the Code of Conduct and signed the Adherence Agreement and agree to abide by the rules therein. In confirmation of this I upload a signed copy of the Adherence Agreement here.')
    photo_scan = models.FileField(verbose_name='Photo ID scan', help_text = 'As part of our verification procedure we require a recognised form of ID such as your passport, national ID card or driving licence. Please scan, save and upload here as a JPEG or PDF.')
    confirm_listing = models.BooleanField(verbose_name='I agree that my name can be listed as a user of the platform on the RD-Connect official website (https://rd-connect.eu)', help_text='All users will be stored in internal RD-Connect records for internal purposes and may be presented in reports to the European Commission as our funding organisation. We would also like to list users in a dedicated section of the platform website. If you do not wish your name to be listed publicly, do not tick the box.')
    newsletter_subscribed= models.BooleanField(verbose_name='I would like to be subscribed to the RD-Connect Newsletter', help_text='We would like to register all users for our monthly newsletter in order to keep you updated about news of interest to rare disease researchers and platform updates. If you do not wish to receive the newsletter, please tick the box.')
    created = models.BooleanField(default=False)
    date = models.DateTimeField(auto_now_add=True, verbose_name='Date')

    def __str__(self):
        """
        String for representing the Model object
        """
        return self.last_name

    def get_absolute_url(self):
        """
        Returns the url to access a detail record for this user
        """
        return reverse('user-detail', args=[str(self.id)])

forms.py:

from django import forms
from .models import Member, UserInfo

class UserForm(forms.ModelForm):
    # Main registration form
    def __init__(self, *args, **kwargs):
        super(UserForm, self).__init__(*args, **kwargs)

    class Meta:
        model = UserInfo
        fields = '__all__'

urls.py

from django.urls import path
from django.conf.urls import url, include
from django.views.generic import TemplateView
from .views import *

urlpatterns = [
    url(r'^$', UserView.as_view(), name='user_new'),
    url(r'^thanks/$',  TemplateView.as_view(template_name='thanks.html'), name='thanks'),
]

views.py:

from django.shortcuts import render
from .forms import UserForm
from .models import UserInfo
from django.views.generic.edit import FormView,CreateView

class UserView(CreateView):
    template_name = 'user_new.html'
    form_class = UserForm
    success_url = 'thanks/'

    def post(self, request, *args, **kwargs):
        form = UserForm(data=request.POST)
        if form.is_valid():
            form.save()
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

在这里查看类似的帖子我看到它被提到如果你覆盖 post 那么你需要将 object 分配给视图,但我尝试在 [=21] 中添加 object = self.get_object() =] 并且刚刚得到一个 QuerySet 错误...

这似乎也在Traceback中突出显示,我提交的表格无效?我输入了 "valid" 数据,所以我可能需要实施某种验证过程?:

C:\rdc-registration\rdcregistration\userregistration\views.py in post
    def post(self, request, *args, **kwargs):
        form = UserForm(data=request.POST)
        if form.is_valid():
            form.save()
            return self.form_valid(form)
        else:
            return self.form_invalid(form) ...
▼ Local vars
Variable    Value
args        ()
form        <UserForm bound=True, valid=False, fields=(first_name;last_name;office_address;research_interest;institution;institute_website;email;department;job_title;orcid_profile;linkedin_profile;publications;researchgate_profile;departmentweb_profile;adherence_agreement;photo_scan;confirm_listing;newsletter_subscribed)>
kwargs      {}
request     <WSGIRequest: POST '/userregistration/'>
self        <userregistration.views.UserView object at 0x0000000004401470>

这是 django/views/generic/edit.pyBaseCreateView 的 post 函数:

def post(self, request, *args, **kwargs):
    self.object = None
    return super(BaseCreateView, self).post(request, *args, **kwargs)

如果您覆盖函数,您应该调用 super .. 或在您的代码中包含 self.object = None