简体   繁体   中英

How can I pass a parameter from the view into a modelForm in django?

My goal here is to have the user upload a document but my program names the document automatically. Essentially, from the view I pass the name into the form, where that name is placed in the 'descriptions' field of my Document model. Thanks!

Views.py

def testing(request):
if request.method == 'POST':
    name = 'testing'
    form = DocumentForm(request.POST, request.FILES, description=name)
    if form.is_valid():
        form.save()
        return redirect('landing')
else:
    form = DocumentForm()
return render(request, 'testing.html', {
    'form': form
})

forms.py

class DocumentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
    description = kwargs.pop('description')
    super(DocumentForm,self).__init__(*args, **kwargs)
    self.fields['description'].initial = description

class Meta:
    model = Document
    fields = ('description', 'document', )

models.py

class Document(models.Model):
    description = models.CharField(max_length=255, blank=True)
    document = models.FileField(upload_to='documents/')
    uploaded_at = models.DateTimeField(auto_now_add=True)

Updating a new instance from a ModelForm just requires modifying your save in the view. Let me know if this isn't what you meant I should be able to help further.

def testing(request):
    if request.method == 'POST':
        name = 'testing'
        form = DocumentForm(request.POST, request.FILES, description=name)
        if form.is_valid():
            # get instance but don't commit to database
            doc = form.save(commit=False)
            # do modifications to the instance here.
            doc.description = name
            # save the instance with all modifications
            doc.save()
            return redirect('landing')
    else:
        form = DocumentForm()
    return render(request, 'testing.html', {
        'form': form
    })

Update 1 On your kwargs.pop("description") you need to do the following. What is happening is that in your else you create the form without the description keyword.

class DocumentForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(DocumentForm,self).__init__(*args, **kwargs)
        if 'description' in kwargs:
            description = kwargs.pop('description')
            self.fields['description'].initial = description

    class Meta:
        model = Document
        fields = ('description', 'document', )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM