Use object (User and custom object) in a form

18 views
Skip to first unread message

Suprnaturall

unread,
Aug 12, 2011, 4:37:56 AM8/12/11
to Django users
Hello everyone,

I'm trying to add comment to a custom object (here Article).
This is my forms.py :

from django import forms
from django.contrib.auth.models import User
from myApp.models import Article

class CommentForms (forms.Form):
cf_comment = forms.CharField()
cf_writer = forms.User()
cf_date = forms.DateField()
cf_article = forms.article()

Here the template :
<form method="post">
<input type="text" name="commentaire" />
<input type="hidden" name="user" value={{ user }} />
<input type="hidden" name="article" value={{ article }} />
<input type="submit" value="submit" />
</form>

and here my view :

def article(request, id):
article = Article.objects.get(id=id)
commentaires =
Commentaire.objects.filter(article=article.id).order_by("-
dateComment")
# comment form
if request.method == 'POST':
form = CommentForms(request.POST)
if form.is_valid(): #validation
cf_comment = form.cleaned_data['commentaire']
cf_writer = form.cleaned_data['user']
cf_date = datetime.datetime.now()
cf_article = form.cleaned_data['article']
else :
form = CommentForms()

c = Context({
'Article' : article,
'commentaires' : commentaires,
})
return render_to_response('myApp/article.html', c,
context_instance=RequestContext(request))

When i try to go to /myapp/myArticle/id i have this message :
Tried article in module app.myApp.views. Error was: 'module' object
has no attribute 'User'

Do you have any idea ? maybe i forge an import or maybe i can t use
object in forms ...

Thx for your help !

nicolas HERSOG

unread,
Aug 12, 2011, 8:23:02 AM8/12/11
to django...@googlegroups.com
Hi everyone,

I tried few thigs more but it s still don't work.
this is my new template :
<form action="." method="post"> {% csrf_token %}
<input type="text" name="commentaire" />
<!--<input type="hidden" name="user" value={{ user }} />-->
<!--<input type="hidden" name="article" value={{ article }} />-->
<input type="submit" value="submit" />
</form>

And my view :
def vod(request, id):
article = Article.objects.get(id=id)
commentaires = Commentaire.objects.filter(article=article.id).order_by("-dateComment")

c = Context({
'article' : article,
'commentaires' : commentaires,
})
# preparation du formulaire de commentaire
if request.method == 'POST':
form = CommentForms(request.POST)
if form.is_valid(): #validation
cf_comment = form.cleaned_data['commentaire']
cf_writer = request.user
cf_date = datetime.datetime.now()
cf_article = request.article
else :
form = CommentForms()


return render_to_response('myApp/article.html', c, context_instance=RequestContext(request))

I still have this message : 

ViewDoesNotExist at /

Tried index in module app.myApp.views. Error was: 'module' object has no attribute 'User'
Request Method:GET
Request URL:http://127.0.0.1:8000/
Django Version:1.3
Exception Type:ViewDoesNotExist
Exception Value:
Tried index in module empire.empireFront.views. Error was: 'module' object has no attribute 'User'


could the problem from my forms.py ?
Thx

On Fri, Aug 12, 2011 at 10:38 AM, <django...@googlegroups.com> wrote:
I am out of office right now and will get back to you when I return. If you don't hear from me, my assistant should contact you shortly. I.m on sick leave because of some news from my Dr., please check out this diet product he recommended..Click Here

Enable images or click here

Let me know what you think after you have a chance to review.
Cheers!

If you no longer wish to receive emails, please unsubscribe

866-288-1880
5150 yarmouth ave, Encino, CA 91316
On Fri, 12 Aug 2011 01:37:56 -0700 (PDT), Suprnaturall wrote:

Daniel Roseman

unread,
Aug 12, 2011, 9:16:56 AM8/12/11
to django...@googlegroups.com
Your error has nothing to do with your form. There is an import problem in your empireFront.views module which is preventing it from being imported.

Somewhere you are trying to import something called "User" from a place that doesn't have any such class. It would help if you posted the imports in that file.
--
DR.

nicolas HERSOG

unread,
Aug 12, 2011, 10:35:19 AM8/12/11
to django...@googlegroups.com
Humm, maybe you should right, here is my views.py :

from django.template import Context, loader, RequestContext
from myApp.models import Article, Commentaire
from django.http import HttpResponse
from django.contrib import auth
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.contrib.sessions.models import Session
from django.shortcuts import get_object_or_404, render_to_response
from myApp.forms import CommentForms

and here the view which don t work :
def article(request, id):
article = Article.objects.get(id=id)
commentaires = Commentaire.objects.filter(video=video.id).order_by("-dateComment")

c = Context({
'article' : article,
'commentaires' : commentaires,
})
# preparation du formulaire de commentaire
if request.method == 'POST':
form = CommentForms(request.POST)
if form.is_valid(): #validation
cf_comment = form.cleaned_data['commentaire']
cf_writer = request.user
cf_date = datetime.datetime.now()
cf_article = request.article
#return render_to_response('myApp/article.html', c, context_instance=RequestContext(request))
else :
form = CommentForms()


return render_to_response('myApp/article.html', c, context_instance=RequestContext(request))

and finally my forms.py :

from django import forms
from django.contrib.auth.models import User
from myApp.models import Article

class CommentForms (forms.Form):
    cf_comment = forms.CharField()
    cf_writer = forms.User()
    cf_date = forms.DateField()
    cf_video = forms.Article()

This one don't work, i can't launch my webApp, when i hit it I have this error : 

ViewDoesNotExist at /

Tried index in module empire.myApp.views. Error was: 'module' object has no attribute 'User'
Request Method:GET
Request URL:http://127.0.0.1:8000/
Django Version:1.3
Exception Type:ViewDoesNotExist
Exception Value:
Tried index in module app.myApp.views. Error was: 'module' object has no attribute 'User'


Now i delete the object attribute of my form (ie : User and Article ) :
my forms.py :
from django import forms
from django.contrib.auth.models import User
from myApp.models import Article

class CommentForms (forms.Form):
    cf_comment = forms.CharField()
    #cf_writer = forms.User()
    cf_date = forms.DateField()
    #cf_video = forms.Video()

and my view (i keep the same import ) :
def article(request, id):
article = Article.objects.get(id=id)
commentaires = Commentaire.objects.filter(video=video.id).order_by("-dateComment")

c = Context({
'article' : article,
'commentaires' : commentaires,
})
# preparation du formulaire de commentaire
if request.method == 'POST':
form = CommentForms(request.POST)
if form.is_valid(): #validation
cf_comment = form.cleaned_data['commentaire']
#cf_writer = request.user
cf_date = datetime.datetime.now()
#cf_article = request.article
#return render_to_response('myApp/article.html', c, context_instance=RequestContext(request))
                        print 'IF'

else :
form = CommentForms()
                        print 'ELSE'

The application launch fine but when i submit the form (obviously) i go in the ELSE.

Any idea ?

Thx for your help :)


return render_to_response('myApp/article.html', c, context_instance=RequestContext(request))

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/OeT67jgufvoJ.

To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

bruno desthuilliers

unread,
Aug 12, 2011, 11:21:23 AM8/12/11
to Django users
On Aug 12, 10:37 am, Suprnaturall <n.her...@gmail.com> wrote:
>
> from django.contrib.auth.models import User
>
> class CommentForms (forms.Form):
>     cf_writer = forms.User()
>
> Error was: 'module' object
> has no attribute 'User'
>
> Do you have any idea ?

cf above...

Landy Chapman

unread,
Aug 12, 2011, 1:16:57 PM8/12/11
to django...@googlegroups.com
> class CommentForms (forms.Form):
>     cf_writer = forms.User()
>
> Error was: 'module' object
> has no attribute 'User'
>
> Do you have any idea ?

Normal forms don't include/automatically create 'User' as a field... 
The built-in comment app may be what you need:



Landy Chapman

unread,
Aug 12, 2011, 2:40:02 PM8/12/11
to Django users
I think you have a *namespace* problem.

> and finally my forms.py :
>
>from django import forms
>from django.contrib.auth.models import User
>
> > Error was: 'module' object
> > has no attribute 'User'
#--------------------------------------

You are importing everything in "django/forms/" into your namespace as
"forms.*", which comes from the installed files
django/forms/
widgets.py
fields.py
forms.py
models.py
None of those define 'User'

> my forms.py
>class CommentForms (forms.Form):
> cf_comment = forms.CharField()
> cf_writer = forms.User() <----- problem

That line says "make a new object called cf_writer using the User
class defined in the django forms module.

Landy Chapman

unread,
Aug 12, 2011, 8:37:44 PM8/12/11
to Django users
I apologize since I tried to reply via gmail. Reposting & expanding
part of a solution .

> I've figured a way that I think will work best for me for the model
> and form but I'm having trouble with writing the view. Here is my
> pseudo code
>
> models.py
> -------------------------
> class baseModel(models.Model):
> first_name = models.CharField( max_length=100,
> verbose_name='first')
>
> class form1Model( baseModel):
> pass
>
> class form2Model( baseModel):
> pass
> -------------------------

The problem with the above definitions is that form2Model and
form1Model would point to the *same* database table; that's what you
do_not_want.
[of course, no table is specified above.] You'd need, at a minimum,
something like this:

class BaseModel(models.Model):
class Meta:
abstract = True

class Form1Model(BaseModel):
# Specify the table to use for Form1Model
class Meta(BaseModel.Meta):
db_table = 'table1'

class Form2Model(BaseModel):
# Specify the db table to use for Form2Model
class Meta(BaseModel.Meta):
db_table = 'table2' #<--- table in db specified here


The following should then work for you (after db_sync):

> forms.py
> -------------------------
> class baseForm(ModelForm):
> ....
>
> class form1( baseForm ):
> class Meta(baseForm.Meta):
> model = models.Form1Model
>
> class form2( baseForm ):
> class Meta(baseForm.Meta):
> model = models.Form2Model
> -------------------------

> I'm not sure how to create a view that can be reused. The only
> difference is the form name and the 'thank you' page. I thought about
> a Decorators but it doesn't seem like that is the right tool to use.
>
> view.py
> -------------------------
> def form1View(request):
>
> if request.method == 'POST':
> form = form1(request.POST)
>
> if form.is_valid():
> form.save()
> return HttpResponseRedirect('/thanksForm1/')
# ---># you're missing code for NOT (form.is_valid())
> else:
> form = form1()
> return render_to_response('form_template.html', {'form': form} )
>

I'm guessing here that you want both forms to be processed with the
same view function? If the forms are submitted from different pages
there are a few ways to do this.

--Pass a variable from urls.py and rewrite the view:
def formView(request, which_form=None):
if request.method == 'POST':
if not [1, 2].__contains__(which_form):
pass # <--- iNone or nvalid form specified
else:
if which_form==1:
form = form1(request.POST)
redirect_url='/thanksForm2/'
if which_form==2:
form = form2(request.POST)
redirect_url='/thanksForm2/'
if form.is_valid():
form.save()
return HttpResponseRedirect(redirect_url)

--Pass a variable from separate views:

def Form1View(request):
formView(request, which_form=1)

def Form2View(request):
formView(request, which_form=2)

Landy Chapman

unread,
Aug 12, 2011, 11:53:48 PM8/12/11
to Django users
copy/paste typo, sorry. It should have read/been:

def formView(request, which_form=None):
if request.method == 'POST':
if not [1, 2].__contains__(which_form):
pass # <--- iNone or nvalid form specified
else:
if which_form==1:
form = form1(request.POST)
redirect_url='/thanksForm1/' #was typo

nicolas HERSOG

unread,
Aug 16, 2011, 7:39:48 AM8/16/11
to django...@googlegroups.com
Oh I see,

I've just modified my code with new import but i still have problem to submit my form. I don t have any errors but i can't pass the form.is_valid().
It's my first form so i don t know how to do it. Can you (again) help me ?

Here it's my forms.py : 

from django import forms
from django.contrib.auth.models import User
from myApp.models import Article

class CommentForms (forms.Form):
    cf_comment = forms.CharField()
    cf_writer = User()
    cf_date = forms.DateField()
    cf_video = Article()

my template :
(...)
<form action="." method="post"> {% csrf_token %}
<input type="text" name="commentaire" />
<input type="hidden" name="user" value={{ user }} />
<input type="hidden" name="article" value={{ article }} />
<input type="hidden" name="time" value={{ now }} />
<input type="submit" value="submit" />
</form>
(...)

and my view.py :

def article(request, id):
article = Article.objects.get(id=id)
commentaires = Commentaire.objects.filter(video=video.id).order_by("-dateComment")
#dateTime
date = datetime.datetime.now()

c = Context({
'article' : article,
'commentaires' : commentaires,
'now' : date,
})
# preparation du formulaire de commentaire
if request.method == 'POST':
form = CommentForms(request.POST)
if form.is_valid(): #validation
cf_comment = form.cleaned_data['commentaire']
cf_date = form.cleaned_date['time']
cf_writer = form.cleaned_data['user']
cf_article = form.cleaned_date['article']
print 'IF'
else :
form = CommentForms()
print 'ELSE'


return render_to_response('myApp/article.html', c, context_instance=RequestContext(request))


When i submit my form i can see via the python console that i m only in the ELSE of the form.is_valid, and when i inspect via firebug what i submit in my form i have :
commentaire test commentaire a2
csrfmiddlewaretoken c25f76451eba14ebb762bb4ed4795274
time 16
user username
vod Final

any idea ?
Great thx for your help :)

--
You received this message because you are subscribed to the Google Groups "Django users" group.

Tom Evans

unread,
Aug 16, 2011, 7:55:27 AM8/16/11
to django...@googlegroups.com
On Tue, Aug 16, 2011 at 12:39 PM, nicolas HERSOG <n.he...@gmail.com> wrote:
> Oh I see,
> I've just modified my code with new import but i still have problem to
> submit my form. I don t have any errors but i can't pass the
> form.is_valid().
> It's my first form so i don t know how to do it. Can you (again) help me ?
> Here it's my forms.py :
> from django import forms
> from django.contrib.auth.models import User
> from myApp.models import Article
> class CommentForms (forms.Form):
>     cf_comment = forms.CharField()
>     cf_writer = User()
>     cf_date = forms.DateField()
>     cf_video = Article()

OK

> my template :
> (...)
> <form action="." method="post"> {% csrf_token %}
> <input type="text" name="commentaire" />
> <input type="hidden" name="user" value={{ user }} />
> <input type="hidden" name="article" value={{ article }} />
> <input type="hidden" name="time" value={{ now }} />
> <input type="submit" value="submit" />
> </form>

You aren't rendering your Form, you are manually outputting a form.
For one thing, this means you won't see the validation messages from
your form.

If request.method != 'POST' then you don't create the Form object
(which might explain why you were rendering by hand).

> When i submit my form i can see via the python console that i m only in the
> ELSE of the form.is_valid, and when i inspect via firebug what i submit in
> my form i have :
> commentaire test commentaire a2
> csrfmiddlewaretoken c25f76451eba14ebb762bb4ed4795274
> time 16
> user username
> vod Final
> any idea ?
> Great thx for your help :)

Find out why the form validation fails and fix it.

Look at the how the manual describes how to create a form, use it in a
view, and render it in a template. Compare and contrast this with your
view, and how you handle and render your form.

https://docs.djangoproject.com/en/1.3/topics/forms/#using-a-form-in-a-view
https://docs.djangoproject.com/en/1.3/topics/forms/#displaying-a-form-using-a-template

Cheers

Tom

Reply all
Reply to author
Forward
0 new messages