简体   繁体   中英

Change choice field of model in django view

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:

  1. create another model
  2. 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM