Django - Unable to upload PDF file despite having the correct file path

Has anyone encountered an issue with uploading a PDF file to a database using forms, where the file fails to be sent to the server?

models.py

class Presse(models.Model):
    pdf = models.FileField()

forms.py

class PresseForm(forms.ModelForm):
    class Meta:
        model = Presse
        fields = '__all__'

I have tried following the same approach I use for uploading images, which works without any problems. However, it seems like there might be an error or something that I am missing.

views.py

def presse(request):
    article = Presse.objects.get(id=1)
    if request.method == 'POST':
        form = PresseForm(request.POST, request.FILES, instance=article)
        if form.is_valid():
            form.save
            redirect('main:presse')
    else:
        form = PresseForm(instance=article)
    return render(request, 'main/presse.html', {
        'article': article,
        'form': form
    })

presse.html

<form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button class="btn btn-success">Ersetzen & speichern</button>
    </form>

After attempting to upload a file and getting redirected, I encounter a 404 error:

GET http://localhost:8000/media/Untitled.pdf 404 (Not Found)

Even though the path is correct, the file does not seem to be served. Any suggestions on what could be causing this issue?

Answer №1

def fetch_news(request):
    news_article = News.objects.get(id=1)
    if request.method == 'POST':
        form_data = NewsForm(request.POST, request.FILES, instance=news_article)
        if form_data.is_valid():
            form_data.save
            return redirect('main:news')
    else:
        form_data = NewsForm(instance=news_article)
        return render(request, 'main/news.html', {
                      'news_article': news_article,
                      'form_data': form_data
                     })
    return render(request, 'main/news.html', {
        'news_article': news_article,
        'form_data': form_data
    })

In my opinion, the issue lies in the incorrect redirection being done in two out of three scenarios. The revised code above should address this problem.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Selenium Visualiser with Offset Coordinates

After mastering the move_by_offset(x, y).perform() command, I find myself questioning the significance of x and y. Are these coordinates that we plot on an axis where x and y represent their respective positions? ...

Addition in numpy can be thought of as operating in a matrix

In my numpy code, I have a row vector represented as a and a column vector represented as b. If I were to perform matrix multiplication on these vectors, the resulting matrix m would have values calculated using the formula m[i,j] = a[i]*b[j]. Now, I am ...

Having difficulty providing input (Date) in a web application using Selenium Webdriver with Python

I'm having difficulty inputting a date into a datefield on a web application using Selenium Webdriver with Python. I have attempted the following code: driver.find_elements_by_name("invDate")[0].click() This code successfully places the cursor in th ...

What is the best way to format a string containing prices using Python?

In my database, there is a field in the record table that contains prices in string format. The prices are unformatted and may vary: $12,000.50 $3.50 From $3.50 to $12,000.50 My goal is to extract the numerical value from these strings by removing all "$ ...

Using Python to Determine MariaDB Connection Status

Is there a method in the MariaDB connector for Python that checks the connection state, similar to is_connected in python-mysql? Or is there another way to determine the connection status? ...

Rendering HTML with jQuery using AJAX: Step-by-step guide

Within my webpage, I have implemented a select box that contains a list of various books. The purpose of this select box is to allow the user to choose a book and then click a submit button in order to view the chapters of that book on a separate page. Ho ...

``We can showcase API data using various endpoints and then present it on a web page using

Hello from Argentina! I'm new to programming and recently started a Flask project. I've successfully displayed information from an API using one endpoint and rendered it with Flask. However, I'm now facing the challenge of displaying informa ...

Why does the output still show [1, 2] even after deleting list2 from list1 and printing list1?

Running this code: list2=[1,2] list1=list2 del list2 print(list1) I am curious why the output is [1,2]. In my understanding, when a list is deleted like in the case of list2, the memory location should no longer exist, so I expected list1 to be undefined ...

Error Message: 'keras' module does not have a '__version__' attribute

import keras keras.__version__ While working in a .ipynb notebook in VSCode, I attempt to import Keras. To check if Keras is imported correctly, I inquire about the version of Keras that is currently "running". However, I encounter the following error mes ...

Taking a Break in Pandas with DataFrame Conditions

In the table below, you will find a Data Frame (df) containing information about different shops and their corresponding date times from January to August. | datetime | shop | val | |------------------|---------|-----| | 04-07-2020 13:32 | AS ...

What is the process for importing `displayHTML` in DataBricks?

I developed a python package that utilizes IPython to render HTML content in notebooks across various environments such as Jupyter or Google Collab. Upon testing it in DataBricks, I discovered that it does not function properly. Here is an example of t ...

Maximizing the potential of Vue with brunch

I'm having issues while attempting to integrate Vue with Django using brunch. Whenever I try to debug my JavaScript code, I notice that it fails at the following line: import Vue from 'vue/dist/vue.js' The error message displayed is ' ...

`In Selenium using Python, the browser window opens a URL but abruptly closes``

On opening the Facebook page in the browser, I am encountering an issue where it fails to click on the "Create New Account" button as expected. I have used the following XPATH for locating the Create New Account button: //a[text()='Create New Account& ...

Utilizing re.sub for modifying a pandas dataframe column while incorporating predefined restrictions - **Highly Beneficial**

This particular problem took some time for me to solve, as there were only bits and pieces of information on stack overflow. I wanted to share my solution in case anyone else is facing the same issue. Objective: 1- Modify strings in a entire pandas DataF ...

Exploring the Discrepancies in Augmented Dickey-Fuller Test Outputs between R and Python

What could explain the significant difference in results between the ADF test in R and Python? Dataset: The R test indicates that the time series is stationary, while the Python test suggests it is non-stationary. Python df = pd.read_csv("../data/ai ...

How can I nicely display a SQLAlchemy database with models and relationships in an organized manner?

Looking to visualize the structure of my database in a more comprehensive way. Using Flask-SQLAlchemy as an example, with various models and relationships sourced from SQLAlchemy Docs. class IDModel(db.Model): __abstract__ = True id = db.Column(db.Int ...

The action of clicking on the dropdown menu does not yield any results

see image description hereI am new to Python with Selenium and I am practicing. I am attempting to click on a dropdown element, it appears highlighted but does not respond to clicks. Below you will find the code I have used along with a screenshot and th ...

Transform a list containing repeated values into a dataframe

I am facing a challenge with two lists, where one contains duplicate values: list1 = ['1','2','3','1','2','3','1','2','3'] list2 = ['a','b',' ...

Extracting data from SVG files using Python

Is there a way to extract coordinates/paths from an SVG file using python (I think it's located under the "path" ID, specifically the d="..."/>) for use in controlling a 2 axis CNC machine? I've looked on various platforms like SO and Google for ...

What is the best way to combine two strings together?

Here's the issue at hand: I have a random string and a random pattern, and I need to find all possible combinations of that pattern within the string. These combinations should be marked with [target] at the beginning and [endtarget] at the end. For ...