无法在Django中使用modelForm显示更新的模型

时间:2019-01-17 11:06:30

标签: django django-models django-forms django-views

我是django的新手。我在显示一些从Django模型到html文件的更新数据时遇到麻烦。我在html中有一个删除和添加按钮,它将添加或删除记录到Django模型。当我单击删除时,开始时它将显示所有记录,我可以删除记录。第二次单击时,列表中也显示了以前删除的项目。如何删除?我只想使用modelForm显示模型中的当前项目。以下是我的文件:

  

form.py

class deleteFileChannelForm(forms.ModelForm):
    curChannels = getAllChannel('file')
    j = 0
    channelList = []
    for item in curChannels:
        tempTuple = (j, item)
        channelList.insert(j, tempTuple)
        j += 1
    DeleteChannelName = forms.ChoiceField(widget=forms.Select(attrs={
    'class': 'form-control',
        }), choices=channelList)

    class Meta:
        model = deleteFileChannel
        fields = ('DeleteFileChannelName',)
  

model.py

class deleteFileChannel(models.Model):
    owaDeleteFileChannelName = models.CharField(max_length=25)

    def __str__(self):
        return self.owaDeleteFileChannelName
  

view.py

if request.method == "POST":
        deleteForm = deleteFileChannelForm(request.POST)   
        if  deleteForm.is_valid():
            data = request.POST.copy()
            deleteChannelid = int(data.get('DeleteFileChannelName'))
            deleteChannelName =  channelList[deleteChannelid][1]
            FileChannel.objects.get(FileChannelName=deleteChannelName).delete()
            return HttpResponseRedirect(reverse('fileChannel', ))
        else:
            print("Invalid form")
    else:
        formEditChannel = deleteFileChannelForm()
        return render(request, 'Channels/fileChannel.html',{'formAdd':formAddChannel,'formDelete': formEditChannel,
                                                               'channels':allFileChannel})
  

html文件

<div class="modal-body">
                <form method="post" >
                    {% csrf_token %}
                    <div class="form-group">
                        <h5>Select channel to delete.</h5>
                            {{formDelete.DeleteFileChannelName}}
                    </div>
                    <!-- Modal footer -->
                    <div class="modal-footer" id="modFooter2">
                        <input class="btn btn-primary" type="submit" value="Delete">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    </div>
                </form>
            </div>

1 个答案:

答案 0 :(得分:0)

我认为这里的问题是,您正在使用在DeleteChannelName的类级别上定义的代码填充deleteFileChannelForm字段的选择。在导入时,在类级别定义的代码将执行一次。这意味着选择一旦填充就不会改变。

要修复,每次创建表单实例时,都可以使用表单的__init__()方法填充选择。例如:

class deleteFileChannelForm(forms.ModelForm):

    DeleteChannelName = forms.ChoiceField(widget=forms.Select(attrs={
    'class': 'form-control',
        }), choices=())  # Empty choices here

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Retrieve the channels
        curChannels = getAllChannel('file')
        j = 0
        channelList = []
        for item in curChannels:
            tempTuple = (j, item)
            channelList.insert(j, tempTuple)
            j += 1

        # Populate the choices
        self.fields['DeleteChannelName'].choices = channelList

    class Meta:
        model = deleteFileChannel
        fields = ('DeleteFileChannelName',)