M
M
maniacus262019-03-01 14:05:32
Django
maniacus26, 2019-03-01 14:05:32

How to upload a file in Django by linking it to a specific db entry?

Good afternoon!
There is a blog model with fields id, text, ... , docfile

docfile = models.FileField(upload_to='documents', blank=True)

I need to link a file to an existing blog entry.
It's just that the files are loaded, but I can't link them to a specific record, i.e. a new (empty) entry appears in the database which has an id and a docfile (with the correct binding to the uploaded file)
Did according to the manual https://docs.djangoproject.com/en/2.1/topics/http/...
forms.py
class FileUploadForm (forms.ModelForm):
    class Meta:
        model = blog
        fields = ('docfile',)
        docfile = forms.FileField()

view.py
def blog_upload (request, pk):
    if request.method == 'POST':
        form = FileUploadForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/success/url/')
    else:
        form = FileUploadForm()
    return render(request, 'upload_doc.html', {'form': form})

to the blog_upload (request, pk) function, I pass the pk (primary key) of the entry to which the file should be added.
but I don't understand how to use this information correctly.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question