尝试使输入文件不是必需的,但在Django Python中仍然是必需的

pinkon5k  于 2023-03-09  发布在  Go
关注(0)|答案(1)|浏览(103)

嗨,我还在学习django和python,我做了函数上传文件,但我想文件是不需要的。
验证码:
model.py

class Ticket(models.Model):
   status = models.CharField(max_length=20, default="Pending")
   created = models.DateTimeField(auto_now_add=True)
   updated = models.DateTimeField(auto_now=True)
   docfile = models.FileField(upload_to='attachments/file/%Y/%m/%d/%P', blank=True, null=True)

views.py

def new_ticket(request):

form = TicketForm()
if request.method == 'POST':
    
    form = TicketForm(request.POST, request.FILES)
    if form.is_valid() :
        form = form.save(commit=False)
        form.owner = request.user
        form.save()

        if form.docfile == 'docfile' :
            newdoc = TicketForm(docfile=request.FILES['docfile'])
            newdoc.save()

        return redirect('helpdesk:dashboard')
documents = Ticket.objects.all()
return render(request, 'helpdesk/new_ticket.html', {'form':form,'documents':documents})

forms.py

class TicketForm(forms.ModelForm):
   status = forms.CharField(required=True)
   docfile = forms.FileField(required=False)
   class Meta:
       model = Ticket
       fields = ('status', 'docfile')

new_ticket.html

<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
    <label for="status">Status</label>
    {% render_field form.status class="form-control"%}
</div>
<div class="form-group">
    <label for="docfile">File Upload: </label>
    {% render_field form.docfile required=false class="form-control"  %}
    
</div>
<hr>
<input class="form-group button_main btn-lg" type="submit" value="Send" style="border: 0px;"></form>

我已经尝试了一些解决方案,从这个链接:
Django ModelChoice field is set to required=False but is still required in the browser
Django Make ContentType Not Required
Django form always shows error "This field is required"
Django TextField always is required, despite blank=True,Null=True
Django - Form template throws "This field is required" for Imagefield
但输入字段仍然是必需的,我试图从javascript和jquery也假它,但它仍然是必需的。我试图不呈现它,只是添加到原始html,它仍然是必需的。
Image from console.log
先谢谢你

kpbpu008

kpbpu0081#

您是否尝试过以下选项:
表格数量.py

from django.forms import TextInput, ClearableFileInput

class TicketForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['docfile'].required = False

    class Meta:
        model = Ticket
        fields = ('status', 'docfile')

        widgets = {
            'status': TextInput(attrs={'class': 'form-control',},),
            'docfile':ClearableFileInput(attrs={'class': 'form-control',},),
        }

新票证.html

<form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.status.label }}
    {{ form.status}
    {{ form.docfile.label}}
    {{ form.docfile}}
   <input type="submit" value="Submit">
</form>

注意:这里我使用的是www.example.com中的Bootsrap CSS类forms.py来设计样式,你也可以使用自定义的CSS类。

相关问题