django forms and ModelMultipleChoiceField when working with existing records

前端 未结 1 1688
温柔的废话
温柔的废话 2021-01-13 17:39

I\'m trying to do something which I would think is quite common, but I\'m just really unsure how to tackle this.

What I currently do: Currently I pr

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-13 18:06

    I'm guessing that you are leaving some stuff out of your Project model. Your view is also calling project.members.all() and project.summary with out getting a project in the else statement.

    Assuming that you have a summary field in the projects model, if you want to use a form and not a model form, then:

    forms.py

    class ProjectSettings(forms.Form):
        summary = forms.CharField(max_length=200)
    
        def __init__(self, qs=None, *args, **kwargs):
            super(ProjectSettings, self).__init__(*args, **kwargs)
            if qs:
                self.fields['members'] = forms.ModelMultipleChoiceField(queryset=qs, widget=forms.CheckboxSelectMultiple())
    

    and in your views.py you would pass in the qs to the form:

    def update_project(request, project_slug):
        project = None
        if project_slug:
            project = get_object_or_404(Project, name=project_slug) # somehow get your project object  
    
        qs = project.members.all()
    
        if request.method == 'POST':
            form = ProjectSettings(qs, request.POST)
            if form.is_valid(): # All validation rules pass
                # Process the data in form.cleaned_data
                project.summary = form.cleaned_data['summary']
                project.members = form.cleaned_data['members']
                project.save()
                return HttpResponseRedirect('/projects/' + project.slug + '/')
        else:
            form = ProjectSettings(qs)
    
        return render_to_response('update_project.html', {'form': form}, context_instance=RequestContext(request))
    

    Using a ModelForm makes sense here if you do indeed have your summary field in your Project model.

    forms.py:

    class ProjectSettings(forms.ModelForm):
        def __init__(self, qs=None, *args, **kwargs):
            super(ProjectSettings, self).__init__(*args, **kwargs)
            self.fields['members'].widget = forms.CheckboxSelectMultiple()
        class Meta:
            model = Project
            fields = ('summary', 'members')
    

    views.py:

    def update_project(request, project_slug):
        project = None
        if project_slug:
            project = get_object_or_404(Project, name=project_slug) # somehow get your project object  
    
        if request.method == 'POST':
            form = ProjectSettings(request.POST, instance=project)
            if form.is_valid(): # All validation rules pass
                # Process the data in form.cleaned_data
                project.save()
                return HttpResponseRedirect('/projects/' + project.slug + '/')
        else:
            form = ProjectSettings(instance=project)
    
        return render_to_response('update_project.html', {'form': form}, context_instance=RequestContext(request))
    

    0 讨论(0)
提交回复
热议问题