Django:下载函数出现多值DictKeyError问题

2024-04-25 22:09:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想得到你的帮助,以改善我的代码,并获得下载文件的可能性感谢两种不同的方式。你知道吗

解释:

第一种方法允许检查一些文档,用户必须填写email field。一旦完成,一个modal出现,并根据以前的电子邮件地址预先填充字段,因为查询集是用email adress上的filter执行的

这是下载文档的主要过程。你知道吗

第二种方法不同。我生成了一个唯一的超链接,其中包含url中的文档id。但通过这种方式,我不需要像以前那样的电子邮件地址。你知道吗

我的代码:

这是我的型号.py文件:

class Document(models.Model):

    code = models.CharField(max_length=25, verbose_name=_('code'), unique=True, null=False, blank=False)
    language = models.CharField(max_length=2, verbose_name=_('language'), choices=LANGUAGE_CHOICES, null=False, blank=False)
    format = models.CharField(max_length=10, verbose_name=_('format'), choices=FORMAT_CHOICES, null=False, blank=False)
    title = models.CharField(max_length=512, verbose_name=_('title'), null=False, blank=False)
    publication = models.ForeignKey(Publication, verbose_name=_('publication title'), related_name='documents')
    upload = models.FileField(upload_to='media/files/', validators=[validate_file_extension], verbose_name=_('document file'), null=False, blank=False)

    class Meta:
        verbose_name = _('document')
        verbose_name_plural = _('documents')

class Customer(EdqmTable):
    email = models.EmailField(max_length=150, verbose_name=_('e-mail'), null=False)
    first_name = models.CharField(max_length=70, verbose_name=_('first name'), null=False)
    last_name = models.CharField(max_length=70, verbose_name=_('last name'), null=False)
    country = models.ForeignKey(Country, verbose_name=_('country'))
    institution = models.CharField(max_length=255, verbose_name=_('institution'), null=True)

    class Meta:
        verbose_name = _('customer')
        verbose_name_plural = _('customers')

    def __str__(self):
        return f"{self.email}"

这是我的表单.py文件:

class CustomerForm(forms.ModelForm):
    class Meta:
        model = Customer
        fields = ['email', 'first_name', 'last_name', 'country', 'institution']
        widgets = {
            'email': forms.TextInput(attrs={'placeholder': _('name@example.com')}),
            'first_name': forms.TextInput(attrs={'placeholder': _('First Name')}),
            'last_name': forms.TextInput(attrs={'placeholder': _('Last Name')}),
            'institution': forms.TextInput(attrs={'placeholder': _('Agency, company, academic or other affiliation')}),
        }

    def __init__(self, *args, **kwargs):
        customer_email = kwargs.pop('customer_email', None)

        super(CustomerForm, self).__init__(*args, **kwargs)
        self.fields['country'].empty_label = _('Select a country')
        self.fields['country'].queryset = self.fields['country'].queryset.order_by('name')
        self.fields['email'].required = True
        self.fields['first_name'].required = True
        self.fields['last_name'].required = True
        self.fields['country'].required = True
        self.fields['institution'].required = False

        query_customer_email = Customer.objects.filter(email__iexact=customer_email)

        if customer_email is not None:
            if query_customer_email.exists():
                self.fields['email'].initial = customer_email
                self.fields['first_name'].initial = query_customer_email.distinct()[0].first_name
                self.fields['last_name'].initial = query_customer_email.distinct()[0].last_name
                self.fields['country'].initial = query_customer_email.distinct()[0].country_id
                self.fields['institution'].initial = query_customer_email.distinct()[0].institution
                self.fields['email'].widget.attrs['readonly'] = True
                self.fields['first_name'].widget.attrs['readonly'] = True
                self.fields['last_name'].widget.attrs['readonly'] = True
                self.fields['country'].widget.attrs['readonly'] = True
            else:
                self.fields['email'].initial = customer_email

这是我的模板文件的一部分:

<div class="row">
    <div class=" col-md-5">
        <label for="primary">Email address</label>
        <input type="email" class="form-control" id="email-download-document" name="EmailDownloadDocument"
                 placeholder="Enter email address to get document(s)">
     </div>
 </div>
 <br>
 <div class="row">
     <div class=" col-md-5">
         <input id="document-choice-button" type="submit" class="btn btn-default" name="DocumentSelected"
                 value="{% trans 'Send to my email' %}"/>
     </div>
 </div>

现在,你可以找到我的视图.py文件:

#Part according to the first method
class HomeView(CreateView, FormView):
    ...
    def get_form_kwargs(self):
        kwargs = super(HomeView, self).get_form_kwargs()
        if "DocumentSelected" in self.request.GET:
            customer_email = self.request.GET['EmailDownloadDocument']
            kwargs['customer_email'] = customer_email
        return kwargs

# Part according to the second method
class MyRedirectView(RedirectView):

    def get_redirect_url(self, *args, **kwargs):
        q = QueryDict(mutable=True)
        q['DocumentChoice'] = self.kwargs['code']
        q['DocumentSelected'] = 'Send to my email'
        my_site = settings.MY_SITE_URL

        if my_site == 'http://localhost:8000':
            return f"{my_site}/app/home?{q.urlencode()}"
        else:
            return f"{my_site}/dev3/app/app/home?{q.urlencode()}"

最后我的网址.py文件:

urlpatterns = [
    url(r'^app/home$', HomeView.as_view(), name='app-home'),
    ...
    url(r'^app/direct/download/(?P<code>[\w\.-]+)/$',MyRedirectView.as_view(), name='go-to-direct-download'),

问题:

第一种方法很好用!这部分我没有任何问题。你知道吗

但第二种方法并没有像我想的那样有效,因为我不知道如何避免电子邮件部分。因为它是一个直接链接,我必须显示模态,但是使用一个空表单,因为所有人都可以通过这个链接访问。所以我不需要获取预加载数据。你知道吗

示例:

第一种方法:

[![在此处输入图像描述][1]][1]

第二种方法:

使用此方法,我的url为:

http://localhost:8000/app/direct/download/PUBSD-0001-FR-PDF-1714

它变成:

http://localhost:8000/app/home?DocumentChoice=PUBSD-0001-FR-PDF-1714&DocumentSelected=Send+to+my+email

但我有个问题:

Exception Type: MultiValueDictKeyError at /app/home Exception Value: "'EmailDownloadDocument'"

我不想在这个方法中使用电子邮件部分。你知道吗

非常感谢!你知道吗

编辑:

我发现了一些东西:

我修改了get_form_kwargs()方法如下:

def get_form_kwargs(self):
    kwargs = super(HomeView, self).get_form_kwargs()
    if "DocumentSelected" in self.request.GET:
        customer_email = self.request.GET.get('EmailDownloadDocument', '')
        kwargs['customer_email'] = customer_email
    return kwargs

现在看来行得通,对吗?你知道吗


Tags: 方法nameselffalsetruefieldsverbosemodels