如何继承父文件来填写表单字段?

时间:2019-07-15 12:06:39

标签: python django django-forms

我做了一些从填充数据到表单之一的继承。该字段是字符串和文件。当继承字符串字段工作正常,但文件为空且未显示在模板中时。

我的观点虽然是主要问题。我真的被困在这里。 我的代码有解决方案吗?或关于我必须做什么的任何想法?

views.py

@login_required
def forward(request, message_id, form_class=ComposeForm,
        template_name='mails/compose.html', success_url=None,
        recipient_filter=None, quote_helper=format_quote,
        subject_template=_(u"Re: %(subject)s"),):
    """
    Prepares the ``form_class`` form for writing a reply to a given message
    (specified via ``message_id``). Uses the ``format_quote`` helper from
    ``messages.utils`` to pre-format the quote. To change the quote format
    assign a different ``quote_helper`` kwarg in your url-conf.

    """
    parent = get_object_or_404(Message, id=message_id)

    if parent.sender != request.user and parent.recipient != request.user:
        raise Http404

    if request.method == "POST":
        sender = request.user
        form = form_class(request.POST, request.FILES, recipient_filter=recipient_filter)
        if form.is_valid():
            form.save(sender=request.user, parent_msg=parent)
            messages.info(request, _(u"Message successfully sent."))
            if success_url is None:
                success_url = reverse('mails:messages_inbox')
            return HttpResponseRedirect(success_url)
    else:
        form = form_class(initial={
            'body': quote_helper(parent.sender, parent.body),
            'subject': parent.subject,


            #HERE
            #this two are filefield, but strings other worked fine and showed on template
            'file_surat': [parent.file_surat.url],
            'lampiran': [parent.lampiran.url],




            'nomor_surat': parent.nomor_surat,
            'jenis_surat' : parent.jenis_surat,
            'sifat_surat' : parent.sifat_surat,

            })

    return render(request, template_name, {
        'form': form,
    })

forms.py

class ComposeForm(forms.Form):


    recipient = CommaSeparatedUserField(label=_(u"Penerima"), widget=forms.TextInput(attrs={'class': 'form-control'}))
    jenis_surat = forms.ModelChoiceField(queryset=JenisJenisSurat.objects.all(), widget=forms.Select(attrs={'class': 'form-control'}))
    sifat_surat = forms.ModelChoiceField(queryset=SifatSurat.objects.all(), widget=forms.Select(attrs={'class': 'form-control'}))
    subject = forms.CharField(label=_(u"Perihal"), max_length=140, widget=forms.TextInput(attrs={'class': 'form-control'}))
    nomor_surat = forms.CharField(label=_(u"Nomor Surat"), max_length=140, widget=forms.TextInput(attrs={'class': 'form-control'}))
    file_surat = forms.FileField(label=_(u"File Surat"), required=False, widget=forms.FileInput(attrs={'class': 'custom-file'}))
    lampiran = forms.FileField(label=_(u"File Lampiran"), required=False, widget=forms.FileInput(attrs={'class': 'custom-file'}))
    body = forms.CharField(label=_(u"Keterangan"),
        widget=forms.Textarea(attrs={'rows': '12', 'cols':'55', 'class':'form-control'}))


    def __init__(self, *args, **kwargs):
        recipient_filter = kwargs.pop('recipient_filter', None)
        super(ComposeForm, self).__init__(*args, **kwargs)
        if recipient_filter is not None:
            self.fields['recipient']._recipient_filter = recipient_filter


    def save(self, sender, parent_msg=None):
        recipients = self.cleaned_data['recipient']
        jenis_surat = self.cleaned_data['jenis_surat']
        sifat_surat = self.cleaned_data['sifat_surat']
        subject = self.cleaned_data['subject']
        nomor_surat = self.cleaned_data['nomor_surat']
        file_surat = self.cleaned_data['file_surat']
        lampiran = self.cleaned_data['lampiran']
        body = self.cleaned_data['body']

        message_list = []
        for r in recipients:
            msg = Message(
                sender = sender,
                recipient = r,
                jenis_surat = jenis_surat,
                sifat_surat = sifat_surat,
                subject = subject,
                nomor_surat = nomor_surat,
                file_surat = file_surat,
                lampiran = lampiran,
                body = body,
            )
            if parent_msg is not None:
                msg.parent_msg = parent_msg
                parent_msg.replied_at = timezone.now()
                parent_msg.forwarded_at = timezone.now()
                parent_msg.save()
            msg.save()

compose.html

{% extends "base.html" %} {% load i18n %}

{% block content %} <h1>{% trans "Tulis Baru"%}</h1> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" class="btn btn-primary" value="{% trans "Kirim" %} &raquo;"/> </form>

{% endblock %}

无错误信息。之前谢谢

0 个答案:

没有答案