ashishk
ashishk

Reputation: 299

how to display the data from the database in a template

i have following model:

class comment(models.Model):
    userid=models.CharField(max_length=140)
    apparelid=models.IntegerField(blank=True)
    desc=models.TextField(blank=True)
    def __unicode__(self):
        return self.userid

form :

class commentForm(ModelForm):
    class Meta:
        model=comment
        exclude=('userid','apparelid',)

and view as follows:

def comment(request,title_id):
    if request.method=='POST':
        form=commentForm(request.POST)
        if form.is_valid():
            new=form.save(commit=False)
            new.userid=request.user.username
            new.apparelid=title_id
            new.save()
            return HttpResponseRedirect('/')
        else:
            form=commentForm()

    template=loader.get_template('apple3/comment.html')
    context=RequestContext(request,{
                                        'form':form,
                                       }   
                              )   
    return HttpResponse(template.render(context))

whenever i open my page containg above form it show an error as follows:

Exception Type:     AttributeError
Exception Value:     'function' object has no attribute 'objects'

Upvotes: 2

Views: 107

Answers (3)

alko
alko

Reputation: 48357

Problem at hand seems to be solved by @mariodev. Additionaly, I'd recommend two following steps as a mean of avoiding similar problems in future:

  1. Read PEP8, the Style Guide for Python Code thoroughly
  2. Use only packages and modules import.

Following those two links will make your code more pythonic and less error-prone.

Upvotes: 2

Ali Raza Bhayani
Ali Raza Bhayani

Reputation: 3145

The name of the model class and the view function is same which is resulting in the error:

Exception Value:     'function' object has no attribute 'objects'

You may use a different naming conventions for your classes and functions. As per PEP8, first letter of the class name should be capital/uppercase and the function's name should be lowercase.

So in your case, if you have to keep the names exactly same, you may rename your Model Class to Comment and let your view function's name be comment and that should solve the problem.

Upvotes: 1

mariodev
mariodev

Reputation: 15594

You probably import comment model from inside your view and then use comment again as view name. That's why the error gets thrown.

Please use different name for your view and model if you use them in the same module.

Upvotes: 3

Related Questions