John Dawson
John Dawson

Reputation: 465

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

I am using Django Framework for the first time and am also building on a someone else's code who stopped working here, so I am having some trouble...

I am trying to create a web form to submit data to a database but am getting the error message '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 [email protected] 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)

Looking at similar posts here I see that it's mentioned if you override post then you need to assign object to the view, but I tried adding object = self.get_object() in views.py and just got a QuerySet error...

This also seems to be highlighted in the Traceback, that the form I have submitted is not valid? I entered "valid" data so maybe I need to implement some kind of validation process?:

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>

Upvotes: 2

Views: 591

Answers (1)

Bastian
Bastian

Reputation: 10433

this is the post function from BaseCreateView in django/views/generic/edit.py:

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

if you overwrite the function you should call super .. or include the self.object = None in your code.

Upvotes: 3

Related Questions