I would like to fill my edit_post.html with the values already stored in the database . My edit url is http://hostname/edit_Post/960
. "960" corresponds to the item id in my database . I request with that ID to update its contents.
I wann the contents to appear here :-
edit_Post.html
<form id="category_form" method="post" action="/edit_Post/">
{% csrf_token %}
{% for field in form.visible_fields %}
{{ field.errors }}
<input type="text" placeholder='{{ field.help_text }}'>
{% endfor %}
<input type="submit" name="submit" value="Create Post" />
</form>
urls.py
url(r'^edit_Post/(?P<id>\d+)', 'blog.views.edit_Post'),
forms.py
class addPostForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="Please enter the title ")
author = forms.CharField(max_length=128, help_text="Please enter the Author ")
bodytext = forms.CharField(max_length=128,
help_text="Please enter the Body",
required=False)
# An inline class to provide additional information on the form.
class Meta:
# Provide an association between the ModelForm and a model
model=posts
fields = ('title', 'author','bodytext')
finally views.py
def edit_Post(request, id):
context = RequestContext(request)
instance=posts.objects.get(id=id)
form = addPostForm(instance=instance)
if request.method == "POST":
form = addPostForm(request.POST,instance=instance)
if form.is_valid():
form.save(commit=True)
confirmation_message = "Post information updated successfully!"
return HttpResponseRedirect('/home')
else:
print form.errors
else:
form=addPostForm(instance=instance)
return render_to_response('edit_Post.html', {'form': form}, context)
my model.py
class posts(models.Model):
author = models.CharField(max_length = 30)
title = models.CharField(max_length = 100)
bodytext = models.TextField()
timestamp = models.DateTimeField(default=datetime.now, blank=True)
Django would already do this, if you hadn't bypassed its mechanism of outputting fields. In your template you should do this:
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field }}
{% endfor %}
If you want to keep the placeholder functionality, add that in the form class itself:
class addPostForm(forms.ModelForm):
title = forms.CharField(max_length=128, widget=forms.TextInput(attrs={'placeholder': 'Please enter the title'}))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments