You are not logged in.

Change Language:

Freelancer? Consultant? Check out: WorkTrail - Time Tracking made easy
Board » General Category » General Discussion » Want To Make This Update Work

Page: 1 2 3 Next

I want to make the below codes let users update their status in the Django . And their update should display on the same template. But it’s not working. E.g when a user type in “To be a hacker is not a day’s job” in the status textarea and click on update button below the form. The update should display on the same template for his or her friends to see. Just like how we post status update on fb.

Model

class mob (models.Model):
username=models.ForeignKey(User, unique=True)
state_province=models.CharField(max_length=50)
body=models.TextField(max_length=10000)
date=models.DateTimeField()

def __unicode__(self):
return u"%s - %s - %s - %s" % (self.username, self.state_province, self.body, self.date)

def get_absolute_url(self):
return "/post/%s/" % unicode(self.id)
def get_author_url(self):
return "/u/%s/p/0" % (self.username)

Form

class mobForm(ModelForm):
class Meta:
model=mob
fields=('body','username','state_province','date')
widgets={
'body':Textarea(attrs={"rows":2, "cols":40}),
'username': (HiddenInput),
'state_province': (HiddenInput),
'date':(HiddenInput),
}

View

def homey(request):
#if there’s nothing in the field do nothing.
if request. method != "":
return HttpResponseRedirect('/homi/')

newmob=mob()
newmob.username=request.user
newmob.date=datetime.datetime.now()
newmob.body=request.POST['body']
if request.POST['body'] <> '':
newmob.body=body.objects.get(id=request.POST['body'])
newmob.save()
return HttpResponseRedirect('/homi/')
else:
return render_to_response('meek_home.html', {'mobForm': mobForm },context_instance=RequestContext(request))

Template

{% extends "base_meek.html" %}

{% block body %}
<div class="form">
<form action="." method="post" enctype="multipart/form-data">
<table>
{{ mobForm }}
</table>
<input type="submit" value="Update" />
</form>
{% endblock %}

Please help me out!
Hi,
some considerations...
if you use hidden fields you give to the client the ability to force values, so change form in this way:
class mobForm(ModelForm):
    class Meta:
        model=mob
        fields=('body')
        widgets={
            'body':Textarea(attrs={"rows":2, "cols":40})
        }

The really big changes is in your view. The big problem is in your form usage: you dont' put request in the form class and you don't validate it. Link of form usage: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method

def homey(request):
  #if there’s nothing in the field do nothing.
   if request. method == "POST":
    form=mobForm(request) # this is your problem!
    if form.is_valid():
      data = form.cleaned_data # if you use data you can access to cleaned_data
      newmob = mob(
        username=request.user,
        state_province=None,
        body=data['body'],
        date=datetime.datetime.now())
      newmob.save()
      return HttpResponseRedirect('/homi/') # if all ok redirect to home
    else: # if data is not valid reload page with validated modelform
        return render_to_response('meek_home.html', {'mobForm': newmob },context_instance=RequestContext(request))
  else:
#    newmob = mobForm(initial={initial={'subject': }}) # you can use this if you want to put initial data
    newmob = mobForm()
  return render_to_response('meek_home.html', {'mobForm': mobForm },context_instance=RequestContext(request))


I suggest to put .as_table in your Template:
{% extends "base_meek.html" %}
{% block body %}
<div class="form">
    <form action=""  method="post" enctype="multipart/form-data">
    <table>
    {{ mobForm.as_table }}
    </table>
        <input type="submit" value="Update" />
    </form>
{% endblock %}


Make me know if "request" in "form" solve your problem.
I tested it bro, but I'm facing two problems:
1. All the fields are displayed on the page instead of 'body' field alone. because that's what is needed. so that users will only enter their status update and post it.
2. After clicking on update, i'm getting -
AttributeError at /homi/
'WSGIRequest' object has no attribute 'get'
Below are my codes:
Model:
class mob(models.Model):
user=models.ForeignKey(User, unique=True)
state_province=models.CharField(max_length=50)
body=models.TextField(max_length=10000)
date=models.DateTimeField()


def __unicode__(self):
return u"%s - %s - %s - %s" % (self.username, self.state_province, self.body, self.date)

def get_absolute_url(self):
return "/post/%s/" % unicode(self.id)
def get_user_url(self):
return "/u/%s/p/0" % (self.username)



class mobForm(ModelForm):
class Meta:
model=mob
field=('body')
widgets={
'body':Textarea(attrs={"rows":2, "cols":40}),
}
Views:
def homey(request):
#if there's nothing in the field do nothing.
if request. method=="POST":
form =mobForm(request)
if form.is_valid():
data=form.cleaned_data
newmob=mob(
username=request.user,
state_province=None,
body=data['body'],
date=datetime.datetime.now())
newmob.save()
return HttpResponseRedirect('/homi/')
else: #if data is not valid, reload page with validated modelform
return render_to_response('home.html', {'mobForm': newmob },context_instance=RequestContext(request))
else:
#newmob = mobForm(initial={initial={'subject': }}) # you can use this if you want to put initial data
newmob = mobForm()
return render_to_response('home.html', {'mobForm': mobForm },context_instance=RequestContext(request))

Template:
{% block body %}
<div class="form">
<form action="" method="post" enctype="multipart/form-data">
<table>
{{ mobForm.as_table }}
</table>
<input type="submit" value="Update" />
</form>
{% endblock %}
What am I missing? Thanks so much!
I'm sorry... :-)
When you test if request is POST you must to insert in form request.POST and not only request:
form =mobForm(request.POST) 
If you want to show some other values you can put this in template:
<p><b>User: </b>{{user}}</p>
<p><b>Date: </b>{% now "jS F Y H:i" %}</p>
<p><b>State province: </b>I don't know where you have this data</p>

obviusly you can personalize the HTML.
Make me know if you want another solution.
Bro, I tested it but I'm getting "UnboundLocalError at /homi/ " local variable 'newmob' referenced before assignment.

Views:

def homey(request):
#if theres nothing in the field
if request.method=="POST":
form=mobForm(request.POST)
if form.is_valid():
data=form.cleaned.data
newmob=mob(
user=request.user,
state_province=None,
body=data['body'],
date=datetime.datetime.now())
newmob.save()
return HttpResponseRedirect('/homi/')
else:
return render_to_response('home.html',{'mobForm':newmob},context_instance=RequestContext(request)) #this is the line that's giving me problem.
else:
newmob=mobForm()
return render_to_response('home.html',{'mobForm':mobForm}, context_instance=RequestContext(request))
What I'm I missing?

If you have another way to solve this, kindly write it and lets try it. I hope you get the problem I want to solve?

Let me expalain again bro. I want users to be able to update their status by entering what they want in the body form only. and after they click on update button, their username, staus['body'], date and state_province should be displayed on the same template.

so that their friends will be able to see it and comment or share if they like. You know how we do update our status on FB? Hope to hear from you soon. Thanks so much!
def homey(request):
    #if theres nothing in the field
    if request.method=="POST":
        form=mobForm(request.POST)
        if form.is_valid():
            data=form.cleaned.data
            newmob=mob(
                user=request.user,
                state_province=None,
                body=data['body'],
                date=datetime.datetime.now())
            newmob.save()
            return HttpResponseRedirect('/homi/')
        else:
            return render_to_response('home.html',{'mobForm':form},context_instance=RequestContext(request)) # here you must to set 'mobForm':form and not newmob that is an instance
    else:
        form=mobForm() # here put form=  and not newmob=
        return render_to_response('home.html',{'mobForm':form}, context_instance=RequestContext(request))# same problem
--- Last Edited by arwa at 2012-02-09 03:32:25 ---
Thanks bro. So no need for me to change the template? I should leave it like this?

<div class="form">
<form action="" method="post" enctype="multipart/form-data">
<table>
{{ mobForm.as_table }}
</table>
<input type="submit" value="Update" />
</form>
If in render_to_response put this in context {'mobForm':form} in template you can use mobForm.as_table, so there are no problems.
I think that is all ok now.

--- Last Edited by arwa at 2012-02-09 04:19:09 ---
I guess it will work bro. But I'm getting- "Mob with this User already exists" When I input my username in the user fields.

What I really want to do is this, display only the body of the mobForm on the template, so when the user inputs whatever he or she wants to write, it will now display the user's username, the body(what the user wrote) , date and province on the template. below the body mobform. I hope you get my point?

Page: 1 2 3 Next





Powered by Sphene Community Tools