2

Good evening,

I've just completed this tutorial:

https://docs.djangoproject.com/en/4.1/intro/tutorial01/

and I need to add a new directory to display a dataset (unrelated to the polls app) I've set up my new directory as I did the first steps in the tutorial.

My steps:

...\> py manage.py startapp newendpoint

newendpoint/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    urls.py
    views.py
path('newendpoint/', include('newendpoint.urls'))

**Once this is setup I've tried these tutorials: **

https://youtu.be/u1FR1nZ6Ng4 I've tried this tutorial and had no luck

https://adiramadhan17.medium.com/django-load-image-from-static-directory-27f002b1bdf1 I've also tried this one

My server goes down or nothing displays. I could really use some help getting this figured out, before I tried the static image I was trying to add a csv via SQLite3 with no luck either.

3
  • In your new app, does anything work at all? Does it have everything from the polls app in it -- if so, does that part work? We need way more information -- where did you put the static image, are you using STATIC... variables in your settings.py? Which ones? What are they set to? Commented Dec 2, 2022 at 23:21
  • When you put the url to the static image in your browser, what happens exactly (404?). Does the server print an error? What is it? Commented Dec 2, 2022 at 23:21
  • Everything works before I start to work on the /newendpoint, the polls app is up and running and doing what it needs to be doing. when I start the new app 'newendpoint' I get to setting up the URL and can access it so I see text that states 'Top Selling Nintendo Switch Games' but when I start to work with adding a static folder and trying to connect everything I seem to be missing something, I'm not sure if I'm explaining it well. Commented Dec 3, 2022 at 15:13

1 Answer 1

1

Step 1:

  • Install pillow
$ pip install pillow

Step 2:

Add the model for the image in your apps models.py


class  Imagemodel(models.Model):
    # .....
    pic = models.ImageField(upload_to='images/', null=True) # U can change to `FileField` for files

Step 3:

Make migrations and migrate:

$ py manage.py makemigrations && migrate

Step 4:

open settings.py and add the following code. This code tells Django where to store the images.

import os # at the top
# Other settings ..
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR , 'media')

Step 5:

In your project directory level, create the media folder:

$ mkdir media 

Step 6:

Open the project level urls.py and add the code below to add our media folder to the static files.

# other imports
from . import settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

# URL patterns

urlpatterns +=staticfiles_urlpatterns()
urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Step 7:

In your app directory level (newendpoint), add a forms.py file and add the code below:

from django import forms
from .models import *
 
 
class PicForm(forms.ModelForm):
 
    class Meta:
        model = Imagemodel
        fields = ['pic']

Step 8:

In your app (newendpoint), create a folder called templates and add a file called pic.html inside. In pic.html, add the code below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>image</title>
</head>
<body>
    <form method = "post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Upload</button>
    </form>
</body>
</html>

Step 9:

In your app's views.py add the code below:

from django.http import HttpResponse
from django.shortcuts import render, redirect
from .forms import *
 
# Create your views here.
 
 
def pic_view(request):
 
    if request.method == 'POST':
        form = PicForm(request.POST, request.FILES)
 
        if form.is_valid():
            form.save()
            return redirect('success')
    else:
        form = PicForm()
    return render(request, 'pic.html', {'form': form})
 
 
def success(request):
    return HttpResponse('successfully uploaded')

Step 10:

In your app's urls.py add the code below:

# .. other imports
from django.urls import path
from .views import *


urlpatterns = [
    path('image_upload', pic_view, name='image_upload'),
    path('success', success, name='success'),
]

Step 11:

Run the server:

$ python3 manage.py runserver 

Upload the image through: http://127.0.0.1:8000/image_upload

Sign up to request clarification or add additional context in comments.

4 Comments

If you get stuck, let me know it's at which step.
This was a good attempt I haven't tried yet, my urls.py in the mysite and newendpoint seem to be causing an issue and crashing the server. Quick question, once the image is uploaded through the link will it stay or do I need to upload it everytime I run the server? I need to have the static image already loaded/displayed so when I go from /polls to /newendpoint the image is there...I hope that makes sense
Are you trying to store images in the database or do you want to store a specific image in the static files for displaying in the frontend?
When you say "crash the server", it would normally print out a bunch of useful information (a stack trace), that might help us figure it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.