AttributeError: '...' object has no attribute '***_set'

11,871

Solution 1

Tested it out seems to be working fine. I would suggest you to check you imports if your Answer class is referencing to the right Question class

>>> from demo.models import *
>>> q = Question.objects.create(created_by=User.objects.get(id=1), question='test')
>>> q
<Question: test>
>>> q.answer_set.create(answer='test answer')
<Answer: test answer>
>>> 

Update:

Your reverse call is wrong. You need to call the model name in small caps and append _set to it. Unless, you have a related_name argument in the relationship:

tmp.surveryanswer_set.create(...)

Solution 2

Note that in case of model name consists of multiple words, you need to write it together, without underscores. For example for Enterprise model has many ContactPerson models

enterprise.contactperson_set

and not

enterprise.contact_person_set

That was the reason of error in my case.

Solution 3

This is also condition for beginners

b = Book.objects.all() this is return a list of Books so b.writer_set.all() not work

Use b = Book.objects.get(id=90) //use this to get only one object and then try
b.writer_set.all()

Share:
11,871

Related videos on Youtube

Registered User
Author by

Registered User

Updated on September 14, 2022

Comments

  • Registered User
    Registered User over 1 year

    I have

    class Question(models.Model):
        created_by = models.ForeignKey(User)
        question = models.CharField(max_length=150)
        def __unicode__(self):
            return self.question
    
    class Answer(models.Model):
        rel = models.ForeignKey(Question)
        answer = models.CharField(max_length=150)
        def __unicode__(self):
            return self.answer
    

    and if i do

    answer1 = "xyz"
    tmp = Question.objects.get(pk=1)
    tmp.answer_set.create(answer=answer1)
    

    i get

    AttributeError: 'Question' object has no attribute 'answer_set'

    What is wrong?

    EDIT:

    Or what could i do next to solve this...or are there any alternatives?

    UPDATE:

    main/models.py:

    from django import forms
    from django.db import models
    from django.contrib.auth.models import User
    
    class LoginForm(forms.Form):
        username = forms.CharField(label='', widget=forms.TextInput(attrs={"placeholder":"Username"}), max_length=200)
        password = forms.CharField(label='', widget=forms.PasswordInput(render_value=False, attrs={"placeholder":"Password"}))
    
    
    class SurveyForm(forms.Form):
        question = forms.CharField(label='Question', widget=forms.Textarea(attrs={"placeholder":"Type your question", "rows":6, "cols":45}), max_length=150)
        answer1 = forms.CharField(label='Answer 1', widget=forms.Textarea(attrs={"placeholder":"Type an answer option", "rows":6, "cols":45}), max_length=150)
        answer2 = forms.CharField(label='Answer 2', widget=forms.Textarea(attrs={"placeholder":"Type an answer option", "rows":6, "cols":45}), max_length=150)
        answer3 = forms.CharField(label='Answer 3', widget=forms.Textarea(attrs={"placeholder":"Type an answer option", "rows":6, "cols":45}), max_length=150)
        answer4 = forms.CharField(label='Answer 4', widget=forms.Textarea(attrs={"placeholder":"Type an answer option", "rows":6, "cols":45}), max_length=150)
    
    
    class Survey(models.Model):
        created_by = models.ForeignKey(User)
        question = models.CharField(max_length=150)
        def __unicode__(self):
            return self.question
    
    
    class SurveyAnswer(models.Model):
    rel = models.ForeignKey(Survey)
    answer = models.CharField(max_length=150)
    def __unicode__(self):
        return self.answer
    

    Traceback (most recent call last):

    File "/usr/lib/python2.6/dist-packages/django/core/handlers/base.py", line 111, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
    
    File "/var/www/first/main/views.py", line 94, in NewSurvey
    tmp.answer_set.create(answer=answer1)
    
    AttributeError: 'Survey' object has no attribute 'answer_set'
    
    
    <WSGIRequest
    path:/new_survey/,
    GET:<QueryDict: {}>,
    POST:<QueryDict: {u'question': [u'xfgj'], u'answer4': [u'yfgn'], u'answer1': [u'ysfjmn'], u'answer3': [u'gfy'], u'answer2': [u'fygmn'], u'csrfmiddlewaretoken': [u'Z1GreYtKoCyMYpACbbz8yfqS72nKo0m8']}>,
    COOKIES:{'csrftoken': 'Z1GreYtKoCyMYpACbbz8yfqS72nKo0m8',
    'sessionid': 'cx07qf3add3c741c6f7f26b5fa5c105e'},
    META:{'CONTENT_LENGTH': '120',
    'CONTENT_TYPE': 'application/x-www-form-urlencoded',
    'CSRF_COOKIE': 'Z0GreYtKpCyMYpAUnnq8yfBt72nKo0m8',
    'DOCUMENT_ROOT': '/etc/apache2/htdocs',
    'GATEWAY_INTERFACE': 'CGI/1.1',
    'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'HTTP_ACCEPT_ENCODING': 'gzip, deflate',
    'HTTP_ACCEPT_LANGUAGE': 'de-de,de;q=0.8,en-us;q=0.5,en;q=0.3',
    'HTTP_CONNECTION': 'keep-alive',
    'HTTP_COOKIE': 'csrftoken=Z0SreYtKpDvWYpACbbz5yfBt72nKo0m8;sessionid=cf07bf3add25741c6f7f26b5fa5c105e',
    'HTTP_DNT': '1',
    'HTTP_HOST': 'domain.tld',
    'HTTP_REFERER': 'http://domain.tld/new_survey/',
    'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Linux i686; rv:10.0.7) Gecko/20100101 Firefox/10.0.7 Iceweasel/10.0.7',
    'PATH_INFO': u'/new_survey/',
    'PATH_TRANSLATED': '/var/www/first/wsgi/new_survey/',
    'QUERY_STRING': '',
    'REMOTE_ADDR': '00.000.000.000',
    'REMOTE_PORT': '00000',
    'REQUEST_METHOD': 'POST',
    'REQUEST_URI': '/new_survey/',
    'SCRIPT_FILENAME': '/var/www/first/wsgi',
    'SCRIPT_NAME': u'',
    'SERVER_ADDR': '00.000.000.000',
    'SERVER_ADMIN': '[no address given]',
    'SERVER_NAME': 'domain.tld',
    'SERVER_PORT': '80',
    'SERVER_PROTOCOL': 'HTTP/1.1',
    'SERVER_SIGNATURE': '<address>Apache/2.2.16 (Debian) Server at domain.tld Port 80</address>\n',
    'SERVER_SOFTWARE': 'Apache/2.2.16 (Debian)',
    'mod_wsgi.application_group': 'domain.tld|',
    'mod_wsgi.callable_object': 'application',
    'mod_wsgi.handler_script': '',
    'mod_wsgi.input_chunked': '0',
    'mod_wsgi.listener_host': '',
    'mod_wsgi.listener_port': '80',
    'mod_wsgi.process_group': '',
    'mod_wsgi.request_handler': 'wsgi-script',
    'mod_wsgi.script_reloading': '1',
    'mod_wsgi.version': (3, 3),
    'wsgi.errors': <mod_wsgi.Log object at 0xba725480>,
    'wsgi.file_wrapper': <built-in method file_wrapper of mod_wsgi.Adapter object at 0xba717d58>,
    'wsgi.input': <mod_wsgi.Input object at 0xba719c78>,
    'wsgi.multiprocess': True,
    'wsgi.multithread': False,
    'wsgi.run_once': False,
    'wsgi.url_scheme': 'http',
    'wsgi.version': (1, 1)}>
    
  • Registered User
    Registered User over 11 years
    If i do the same like you (in the shell) i get again the same error :(. Both classes are in main/models.py so i also do from main.models import *. The creation of q works. Do you know something more what i can look for?
  • Raunak Agarwal
    Raunak Agarwal over 11 years
    Show your complete models.py and the traceback
  • Registered User
    Registered User over 11 years
    I added models.py and the complete traceback in the question.