Reputation: 205
I have a blog and would like to add a post_type variable which will be a dropdown on the webpage.
I have added post_type to my Post model as a Charfield. And setup the dropdown in the template. (this might not be the best way to do this)
It works when I'm creating a Post and also when I edit the post, if I change the dropdown value, the new value is saved. The problem I'm having is when I'm editing a post, I can't get the value to be selected in the dropdown.
I think the html tag for the value in the dropdown needed to be market as Selected but I cant figure out how to do this. I'd really appreciate the help if someone can point me in the right direction.
Upvotes: 0
Views: 208
Reputation: 1234
The most simple way will be add list of choice to your charfield in the model.
model.py
class BlogPost(models.Model):
POST_TYPE_CHOICES = (
('cooking', 'Cooking'),
('story','Amazing Stories'),
)
#other fields here
post_type = models.CharField(choices=POST_TYPE_CHOICES, max_length=50)
Then if you create a ModelForm using this model the default layout in the template will be a dropdownlist.
from the doc :
choices
Field.choices
An iterable (e.g., a list or tuple) consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) ...]) to use as choices for this field. If choices are given, they’re enforced by model validation and the default form widget will be a select box with these choices instead of the standard text field.
EDITED the 20/02:
You need to pass the instance inside your view (I assume you are not using classbased view).
So you should have some thing like this:
def edit_post(request, post_id):
#try to get the instance of the post you need to edit
post_instance = get_object_or_404(Post, id = post_id)
#get your form and pass it the current Post instance
form = EditPostForm(request.POST or None, instance=post_instance)
#validate your form
if form.is_valid():
#if using ModelForm the database will be saved as well
form.save()
#then render your template with the form
return render(request, "edit_post.html", {'form': form})
Then you should use the {{form.field_name}} notation in your template and see the curent value with the dropdown without problem.
Upvotes: 1