Home > database >  How do you change the title of a pdf using django?
How do you change the title of a pdf using django?

Time:02-13

[![enter image description here][1]][1]So I have this app that allows you to upload pdfs then you can view them in the browser and it works fine but the only problem is that my title is a regex for some reason

urls.py

urlpatterns = [
               path("show_file/r'^(?P<file_id>\d )",v.show_file, name="show_file" ),
            ]     

views.py

def show_file(response,file_id):
    doc = Document.objects.get(id=file_id)
    pdf = open(f"media/{doc.file}", 'rb')
    return FileResponse(pdf, content_type='application/pdf')

models.py

class Document(models.Model):
    title = models.CharField(max_length=65, null=False, blank=False)
    subject = models.CharField(max_length=20)
    grade = models.IntegerField()
    file = models.FileField(upload_to="documents/")
    date_uploaded = models.DateField(null=False)

forms.py

class DocumentsForm(forms.ModelForm):
    subject = forms.ChoiceField(choices=subject_choices)
    grade = forms.ChoiceField(choices=grade_choices)
    class Meta:
        model = Document
        fields = ("title","subject","grade","file","date_uploaded")
        
        

CodePudding user response:

Your browser is showing the last segment of the URL in the absence of any other title. Just change your URL to

path("show_file/<file_id>", v.show_file, name="show_file"),

What you have now seems to be a half-baked porting of a regexp-based re_path to the <>-based paths.

CodePudding user response:

You just have to include the file title in the URL like so, but first pass it from your template.

urls.py

    urlpatterns = [
     path("show_file/<file_id>/<file_title>",v.show_file, name="show_file" ),
            ]

 

like:

    <a href=
    "{% url 'show_file' file_id=file.id file_title=file.title %}"
    >View</a>

  • Related