Hi! I am trying to create a webapp in Django and just started learning today. I am confused as to why my path isn’t correctly set-up. If more information is needed, let me know!
Any help and explaination would be awesome thank you!
syllink/urls.py
from django.conf import settings
from django.conf.urls.static import static
from . import views
from django.urls import path
app_name = "syllink"
urlpatterns = [
path("", views.IndexView.as_view(), name="index"),
path('upload/', views.upload_file, name='upload'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
from django.shortcuts import render
from django.views import generic
from django.core.files.storage import FileSystemStorage
from .models import Syllabus_Uploader
class IndexView(generic.ListView):
template_name = "syllink/index.html"
def get_queryset(self):
"""Return the last five published questions."""
return None
def upload_file(request):
if request.method == 'POST':
myfile = request.FILES['myfile']
fs = FileSystemStorage()
# Generate a unique filename to avoid conflicts
from django.utils.text import unique_slugify
filename = unique_slugify(myfile.name)
filename = f"{filename}.{myfile.name.split('.')[-1]}" # Preserve extension
uploaded_file = fs.save(filename, myfile)
uploaded_file_url = fs.url(uploaded_file)
# Save the uploaded file to the model instance
new_syllabus = Syllabus_Uploader(syllabus=uploaded_file)
new_syllabus.save()
return render(request, 'upload_file.html', {'uploaded_file_url': uploaded_file_url})
else:
return render(request, 'upload_file.html')
upload_file.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile">
<button type="submit">Upload</button>
</form>
<p><a href="{% url 'index' %}">Return to home</a></p>
{% endblock %}
index.html
{% load static %}
<!-- <link rel="stylesheet" href="{% static 'polls/style.css' %}"> -->
<ul>
<!-- url 'namespace:name of path'-->
<li><a href="{% url 'syllink:upload' %}">Click here to upload a file</a></li>
</ul>
models.py
from django.db import models
# Create your models here.
class Syllabus_Uploader(models.Model):
syllabus = models.FileField(upload_to='syllabi/')