Pergunta

When I use FileField in one of my three classes in one template file and make the form enctype multipart/form-data, all of three form get invalid in is_valid method.

When I see form.errors all the field become invalid.

When I remove enctype from template code, all forms all valid but no file attach to request.

form.py:

    class buyerForm(ModelForm):
    name=forms.CharField(max_length=100,label='',
        widget=BootstrapTextInput(attrs={
                'title': 'نام خود را وارد نمایید',
                'placeholder': 'نام ',
            }),)
    family=forms.CharField(max_length=100,label='',
        widget=BootstrapTextInput(attrs={
                'title': 'نام  خانودارگی خود را وارد نمایید',
                'placeholder': 'نام خانوادگی ',
            }),)
    email=forms.EmailField(max_length=100,label='',
        widget=BootstrapTextInput(attrs={
                'title': 'آدرس پست الکترونیکی شما ، جهت برقراری ارتباط با شما استفاده خواهد شد.',
                'placeholder': 'آدرس پست الکترونیکی',
            }),)
    cellphone=forms.CharField(max_length=100,label='',
        widget=BootstrapTextInput(attrs={
                'title': 'شماره موبایل شما جهت تایید سفارش شما استفاده خواهد شد.',
                'placeholder': 'شماره موبایل ',
            }),)
    class Meta:
        model=Person
        exclude=['image','user']
class orderForm(ModelForm):
    seller=forms.HiddenInput()
    service=forms.HiddenInput()
    description=forms.CharField(max_length=5000,label='',
        widget=forms.Textarea(attrs={
                'title': 'توضیحات خواسته شده در انتهای شرخ خدمات را وارد نمایید',
                'placeholder': 'اطلاعات درخواستی در انتهای  شرح خدمات ',
            }),)
    class Meta:
        model=Order
        exclude=['buyer','seller','service','datetime']

class attachmentForm(forms.Form):
    file = forms.FileField(
        label='Select a file',
        help_text='max. 42 megabytes'
    )

view.py:

def onlineOrder(request,serviceId):
    request.encoding = 'utf-8'
    message=''
    service=Service.objects.get(pk=serviceId)
    seller = Company_Position_Person.objects.filter(company_position=service.company_position)[0]
    if(request.method=='POST'):
        buyer_ins=buyerForm(request.POST)
        order_ins=orderForm(request.POST)
        #attchment_ins=attachmentForm(request.POST, request.FILES)
        attchment_ins=attachmentForm(request.POST, request.FILES)
        file_validation = attchment_ins.is_valid()
        if (not file_validation):
            print attchment_ins.errors
        a_valid = buyer_ins.is_valid()
        if not a_valid:
            print buyer_ins.errors
        t_order_valid = order_ins.is_valid()
        if not t_order_valid:
            print order_ins.errors
    # we do this since 'and' short circuits and we want to check to whole page for form errors
        if a_valid and  t_order_valid:
            print 'valid forms'
            a = buyer_ins.save()

            mailinfo=MailContact(person=a,email=buyer_ins.cleaned_data['email'],valid='y')
            mailinfo.save()
            cellphoneinfo=PhoneContact(person=a,phone=buyer_ins.cleaned_data['cellphone'],valid='y')
            cellphoneinfo.save()
            t_order = order_ins.save(commit=False)
            t_order.buyer = a
            t_order.seller=seller
            t_order.service=service
            t_order.datetime=datetime.datetime.now()
            t_order.save()
            sendOrderReceipt(t_order)
            message='اطلاعات ایستگاه ثبت شد.'
            return render_to_response('payment/orderReceipt.xad',{'order':t_order,'service':service,'seller':seller,'attachment':attchment_ins},context_instance=RequestContext(request))
        else:
            print order_ins.errors
            message='اطلاعات معتبر نمی باشد.'

    else:
        attchment_ins=attachmentForm(request.POST, request.FILES)
        buyer_ins=buyerForm()
        order_ins=orderForm()
        order_ins.seller=seller
        order_ins.service=service
        return render_to_response('payment/onlineOrder.xad',{'buyerform':buyer_ins,'orderform':order_ins,'service':service,'seller':seller,'attachment':attchment_ins},context_instance=RequestContext(request))

template page:

<form  action="/payment/{{service.pk}}/" method="post" class="form" role="form" enctype="multipart/form-data">
    <div class="form-group">
        {% csrf_token %}

        {% for field in buyerform %}
            <div style="margin-bottom:1px">
            {{ field }}
        </div>
        {% endfor %}

        {% for field in orderform %}
            <div style="margin-bottom:1px">
            {{ field }}
        </div>
        {% endfor %}

        {% for field in attachment %}
        <div style="margin-bottom:1px">
                {{ field }}
        </div>
        {% endfor %}

        <button type="submit" class="btn btn-primary btn-lg btn-block">ثبت سفارش</button>
    </div>

Foi útil?

Solução

this line:

request.encoding = 'utf-8'

clear requets data.remove it.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top