Reputation: 977
I have multiple field choice in my model. I want to change the value of statue in my view. I read These article and this question.In those link, 2 way assumed:
- create another model
- MultipleChoiceField
What I must do, If I want to use MultipleChoiceField? I read these links: 1 , 2, 3 ,4, 5 ,and 6 ;but non of them cloud help me and I can't understand anything. Also this is my codes:
#models.py
STATUE_CHOICE = (
('draft', 'draft'),
('future', 'future'),
('trash', 'trash'),
('publish', 'publish'),
)
statue = models.CharField(max_length=10, choices=STATUE_CHOICE)
#views.ppy
def delete_admin_trash_post(request, slug):
post = get_object_or_404(Post, slug=slug)
if request.method =="POST":
form = AddPostForm(request.POST, instance=post)
post.statue = 'trash'
post.save()
return redirect('view_admin_post')
else:
form = AddPostForm(instance=post)
template = 'blog/admin_blog/delete_admin_trash_post.html'
context = {'form': form}
return render(request, template, context)
Is it possible to explain this method in a simple and complete way?
Upvotes: 1
Views: 6484
Reputation: 386
MultipleChoiceField is a form widget. so you should use it in forms. widgets are ready to use HTML inputs that have some validators that validates and cleans data. to create a form just make a new file named forms.py (this is a common way to add a new file. you can just do this in views.py) then create a form with that. by default, charfields model with choices has ChoiceField widget. if you want to override it you can do it in form Meta class. you have a model named Post:
# models.py
class Post(models.Model):
STATUE_CHOICE = (
('draft', 'draft'),
('future', 'future'),
('trash', 'trash'),
('publish', 'publish'),
)
statue = models.CharField(max_length=10, choices=STATUE_CHOICE)
.
.
and a form AddPostForm:
# forms.py
# or
# views.py
from .models import Post
class AddPostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('statue',...)
widgets = {'statue' : forms.MultipleChoiceField(choices=Post.STATUE_CHOICE)}
this article can be useful : https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/#overriding-the-default-fields
Upvotes: 4