Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF djoser. token is invalid error when i try to login
I use token authorization with djoser in DRF. I save token in httpOnly cookies: class TokenCreateView(TokenCreateView): def _action(self, serializer): token = utils.login_user(self.request, serializer.user) token_serializer_class = settings.SERIALIZERS.token response = Response() data = token_serializer_class(token).data response.set_cookie( key = 'access_token', value = data['auth_token'], secure = False, httponly = True, samesite = 'Lax' ) response.data = {"Success" : "Login successfully","data":data} return response When I login in two devices, I get the same token. But when I logout in one of device, token becomes not valid. But the second device still has token in cookies. And now it is not authorized,but can't login again, because get "Invalid token". I know that the token is invalid, but I can't login. How to solve this problem? And why it gives the same token to all diveces? -
Why is my submit button for a simple mortgage calculator website built using Django and PostgreSQL not working?
I am trying to create a simple mortgage calculator for my first Django project, but seem to have run into a problem right towards the end because my server when run isn't displaying properly. This is how it displays Here is my file structure: File Directory Image 1, File Directory Image 2 I have used chat_gpt and bard to try and help build as well as trouble shoot this issue but they haven't been able to help. Here is all of my code, starting with the html code: base.html: <!DOCTYPE html> <html> <head> <title>Mortgage Calculator</title> {% load static %} <!-- Include your CSS and JS files here --> <!-- For example: --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <script src="{% static 'js/script.js' %"></script> </head> <body> <header> <!-- Header content here --> <h1>Mortgage Calculator</h1> <nav> <ul> <li><a href="/">Home</a></li> <!-- Add other navigation links here --> </ul> </nav> </header> <main> <div class="container"> <!-- Content from other templates will be placed here --> {% block content %} {% endblock %} </div> </main> <footer> <!-- Footer content here --> <p>&copy; 2023 Your Mortgage Calculator. All rights reserved.</p> </footer> </body> </html> mortgage_calculator.html: {% extends 'base.html' %} {% block content %} <h1>Mortgage Calculator</h1> <form action=“/mortgage_calculator” method="post"> … -
When using UploadedFile in the PUT method of ninja Router? I get ["detail": \[{"loc": \["body", "profile_in"\], "msg": "field required"]
I'm trying to add an UploadedFile parameter to the PUT method in my Ninja router. The same parameter works perfectly fine with the POST method, but when I try to use it with the PUT method, Ninja returns the error: Code 422 Details Error: Unprocessable Entity Response body { "detail": [ { "loc": [ "body", "profile_in" ], "msg": "field required", "type": "value_error.missing" } ] } which doesn't make sense to me, because I'm passing all the required parameters in the profile_in. here's the curl command that the swagger is providing: curl -X 'PUT' \ 'http://127.0.0.1:8000/api/profile/edit_profile' \ -H 'accept: application/json' \ -H 'Authorization: Bearer <my token>' \ -H 'Content-Type: multipart/form-data' \ -F 'profile_in={ "name": "Hassan", "title": "Web Developer", "bio": "string", "skills": [ { "name": "Django" } ] }' here's my post method: @profile_controller.post("create_profile", response={200: ProfileSchemaOut, 404: MessageOut, 400: MessageOut, }, auth=CustomAuth(), ) def create_profile(request, profile_in:ProfileSchemaIn, img:UploadedFile=None): and the put method: @profile_controller.put("edit_profile", response={200: ProfileSchemaOut, 404: MessageOut, 400: MessageOut, }, auth=CustomAuth(), ) def edit_profile(request, profile_in: ProfileSchemaIn, img:Optional[UploadedFile]=File(None)): I don't know if this is relevant but this is my ProfileSchemaIn class ProfileSchemaIn(ProfileSchema): name: str title: str bio: Optional[str] = None skills: Optional[List[SkillSchema]] I know I can use bas64 for storing the img but I … -
Django Error 403 Forbidden - CSRF verification failed. Request aborted
I want to use group and users native from Django to authenticate and get access to features in my website. I created a view called login_vew, configured a login.html page and configured settings.py just like this doc (https://docs.djangoproject.com/en/3.2/ref/csrf/) says. But the error persist and I dont know what is the problem. When I run local with python manage.py runserver works fine with debug=True works. views.py: from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from store.models import Product from store.forms import ProductForm def login_view(request): if request.user.is_authenticated: return redirect('painel') if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: try: login(request, user) except Exception as e: messages.error(request, 'Ocorreu um erro ao fazer login. Tente novamente.') return redirect('painel') else: messages.error(request, 'Usuário ou senha incorretos') return render(request, 'login.html') login.html: <div class="card-body text-center"> <h2>Login</h2> <form method="post"> {% csrf_token %} <div class="form-group"> <label for="username">Usuário:</label> <input type="text" class="form-control" id="username" name="username" required> </div> <div class="form-group"> <label for="password">Senha:</label> <input type="password" class="form-control" id="password" name="password" required> </div> <br> <button type="submit" class="btn btn-primary">Entrar</button> </form> </div> settings.py: DEBUG = False CSRF_COOKIE_SECURE = True AUTHENTICATION_BACKENDS = \[ 'django.contrib.auth.backends.ModelBackend', \] LOGIN_URL = '/login/' LOGIN_REDIRECT_URL … -
Django ORM fetching
i want to fetch data from Django model using Q(). what i want is obj = models.Products.objects(Q(description=[a list of descriptions])) I want all the objects matching the descriptions with the elements of the list -
bootstrap and css together is not working in django
I am working on a project where in the timeline.html file users can see their username, bio, url, profile picture and uploaded book photos. I am using bootstrap for navbar and I am using html, css for designing the uploaded book photos and user information. However, navbar design look okay before adding the html css codes of the uploaded book photos and user information. But when I added the codes of the uploaded books and user information, the navbar looks stretched. Can anyone help me solving this problem? base.html {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> <link rel="icon" href="{% static 'books/images/logo.png' %}"> {% block link %}{% endblock %} <title>Bookstagram</title> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-steel" style="background-color: #1DA1F2"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'timeline' %}"><strong><i>Bookstagram</i></strong></a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-info my-2 my-sm-0" type="submit">Search</button> </form> <ul class="navbar-nav ml-auto"> <li> <a class="nav-link" href="">Create Post</a> </li> <li> <a class="nav-link" href="">Profile</a> </li> <li> <a class="nav-link" href="">Logout</a> </li> … -
Submit form using Django views and redirect to React path
I have a form that on submit goes to http://127.0.0.1:8000/all/new/ in order to trigger a view function that creates a new object. booking.js form action="http://127.0.0.1:8000/all/new/" method="POST"> ... /form After creating the object, I want to go back to the homepage that's rendered by React ("http://localhost:3000/"). How can I do this? views.py @api_view(["POST"]) def create_object(request): ... return Response(serializer.data) urls.py urlpatterns = [ path("new/", views.create_booking, name="create_booking"), ] -
Getting task statuses in celery
I have a need to get task statuses in celery, but for some reason I can always get only the "PENDING" and "SUCCESS" statuses, but if I look through flower, I can also see the "STARTED" status Now I'm trying to get the status like this AsyncResult(task_uuid).status python 3.8.10 celery 5.2.7 -
Why can't my blog post be displayed in pythonanywhere.com
I am a beginner of Django, just followed the tutorial to create a blog of my own, but the posts of my blog cannot be displayed normally in pythonanywhere.com These are my files: base.html {% load static %} <!DOCTYPE html> <html> <head> <title>Kington's blog</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> </head> <body> <header class="page-header"> <div class="container"> <h1><a href="/">Kington's Blog</a></h1> </div> </header> <main class="container"> <div class="row"> <div class="col"> {% block content %} {% endblock %} </div> </div> </main> </body> </html> post_list.html {% extends 'blog/base.html' %} {% block content %} {% for post in posts %} <article class="post"> <time class="date"> {{ post.published_date }} </time> <h2><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h2> <p>{{ post.text|linebreaksbr }}</p> </article> {% endfor %} {% endblock %} post_detail.html {% extends 'blog/base.html' %} {% block content %} <article class="post"> {% if post.published_date %} <time class="date"> {{ post.published_date }} </time> {% endif %} <h2>{{ post.title }}</h2> <p>{{ post.text|linebreaksbr }}</p> </article> {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path('', views.post_list, name='post_list'), path('post/<int:pk>/', views.post_detail, name='post_detail'), ] views.py from django.shortcuts import render from .models import Post from django.utils import timezone from django.shortcuts import render, get_object_or_404 … -
Hi. I already set up payment for site, but i cant set up Order status and Basket history in admin panel
'''views.py @csrf_exempt def stripe_webhook_view(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, settings.STRIPE_WEBHOOK_SECRET ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: return HttpResponse(status=400) if event['type'] == 'checkout.session.completed': # Retrieve the session. If you require line items in the response, you may include them by expanding line_items. session = stripe.checkout.Session.retrieve( event['data']['object'] ) line_items = session.line_items fulfill_order(line_items) return HttpResponse(status=200) def fulfill_order(line_items): order_id = int(line_items.metadata.order_id) order = Order.objects.get(id=order_id) order.update_after_payment() ''' When i purchase smthng i expect to change Order status and Basket history in admin panel. Now after payment in admin panel Order status doesn't change (i need to get Paid) and Basket history inside order is empty. I took this Webhook from Stripe documentation -
django how can I sort by user field
How can I make sure that when creating a task, a list of models created only by the author who is currently creating the task is displayed Code: class Tasks(models.Model): title = models.CharField(max_length=75) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="creator", editable=False) class Category(models.Model): title = models.CharField(max_length=30, db_index=True, verbose_name="category_name") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="category_creator", editable=False) class TaskCreateView(CreateView): form_class = TaskForm template_name = 'main/add_task.html' def form_valid(self, form): form.instance.user = self.request.user return super(TaskCreateView, self).form_valid(form) def get_queryset(self): return Tasks.objects.filter(user=self.request.user) I tried to do it with this code, but i couldn't: class TaskForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['category'].queryset = Tasks.objects.filter(category__category__user=self.request.user) self.fields['category'].empty_label = "Not selected" class Meta: model = Tasks fields = ['title', 'category'] -
UpdateView wont databind the from properties
class NewPostForm(forms.Form): post = forms.ChoiceField(choices = POSTTYPE_CHOICES) title = forms.CharField(max_length=100) content = forms.CharField(widget=SummernoteWidget()) # instead of forms.Textarea pic = forms.ImageField(required=False) tags = forms.CharField(max_length=200,required=False) @login_required def update_post(request,pk): user = request.user postToSave = get_object_or_404(PostForNewsFeed, pk=pk) form = NewPostForm(request.POST, request.FILES) if user.is_authenticated: if request.method == "POST": if form.is_valid(): post = request.POST['post'] title = request.POST['title'] content = request.POST['content'] tags = request.POST['tags'] postToSave.post = post postToSave.title = title postToSave.content = content postToSave.tags = tags if 'pic' in request.FILES: pic = request.FILES['pic'] postToSave.pic = pic postToSave.save() else: postToSave.save() return redirect('home3') else: form = NewPostForm() return render(request, 'feed/create_post.html', {'form':form,'page_title': 'Share a Post' }) <form class="form-signin" method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <br /> {{ form |crispy }} </fieldset> <div class="form-group"> <button class="btn btn-lg btn-info btn-block text-uppercase" type="submit" > Post</button ><br /> </div> </form> -
UpdateView with modelform object wont render summernotewidget
from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget class NewUpdateForm(forms.ModelForm): class Meta: model = PostForNewsFeed fields = ['title','content','pic','tags'] widgets = { 'content': SummernoteWidget(), } class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = PostForNewsFeed fields = ['title','content','pic','tags'] template_name = 'feed/create_post.html' def form_valid(self, form): if form.is_valid(): data = form.save(commit=False) data.user_name = self.request.user data.save() messages.success(self.request, f'Posted Successfully') return redirect('home3') <form class="form-signin" method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <br /> {{ form.media |crispy }} </fieldset> <div class="form-group"> <button class="btn btn-lg btn-info btn-block text-uppercase" type="submit" > Post</button ><br /> </div> </form> -
Change the location of a file uploaded via HTML form on submit
I have a form that asks for various inputs one of which is a file input. I want the uploaded files to be stored inside /media/images which is the case when I upload files from the admin console since I specified the upload location in models.py. How can I do the same and store the files that are uploaded via HTML forms in /media/images instead of /media? games.html: {% block body %} <div id="new_game_form" style="display:none; margin: 20px;"> <form class="row g-3" action="{% url 'new_game'%}" method="post"> {% csrf_token %} <div class="col-md-6"> <label class="form-label"><strong>Title</strong></label> <input type="text" class="form-control" id="title" name="title"> </div> <div class="col-md-6"> <label class="form-label"><strong>Sub Title</strong></label> <input type="text" class="form-control" id="sub_title" name="sub_title"> </div> <div class="col-12"> <label class="form-label"><strong>Description</strong></label> <input type="textarea" class="form-control" id="description" name="description"> </div> <div class="col-12"> <label class="form-label"><strong>Thumbnail</strong></label> <input type="file" class="form-control" id="thumbnail" name="thumbnail"> </div> <div class="col-12"> <label class="form-label"><strong>Platform</strong></label> <input type="text" class="form-control" id="platform" name="platform"> </div> <div class="col-12"> <label class="form-label"><strong>Game Link</strong></label> <input type="url" class="form-control" id="game_link" name="game_link"> </div> <div class="col-12"> <label class="form-label"><strong>Launch Date</strong></label> <input type="date" class="form-control" id="launch_date" name="launch_date"> </div> <div class="col-12"> <input type="submit" class="btn btn-dark" id="submit" value="Submit" style="margin-top: 10px;"> </div> </form> </div> views.py: def new_game(request): if request.method == "POST": title = request.POST["title"] sub_title = request.POST["sub_title"] description = request.POST["description"] image = request.POST["thumbnail"] platform = request.POST["platform"] game_link = request.POST["game_link"] launch_date = … -
ImportError: cannot import name 'force_text' from 'django.utils.encoding'
I'm working on a Django GraphQL-JWT project and everything seems working until I pip install django-graphql-auth and then add graphene_django in my INSTALLED APPS that's when I get this error when I try python manage.py migrate or runserver. -
Django Templates - How to display parent object when child is null within a forloop on the child
I am looking to list child model objects that have a foreign key to the parent and are related to request.user. This is working fine. The problem I have is when, I want to list the parent model object when there is no child attached to request.user. And I want to do this in my django template. In my case, I am using a boolean field (completed in the model to identify whether the child exists. I am stuck on how to pull out the parent object alone. I suppose there is two questions: How do I express in my nestedfor loop that if the child object is null then only show parent object. When child object is null and only show parent object - how do I get the parent object to be rendered only once? I thought maybe something like {%if modela.modela_related_name == None%} (if there is no child object) then do something else would work. Unfortunately, it looks like I already need to be in the forloop to find out whether modela.modela_related_name == None A header Another header Another header Parent_1 Parent_Child_1 Parent_Child_1 Parent_2 Parent_2Child_1 Parent_2Child_1 Parent_3 Parent_3Child_1 Parent_3Child_1 Parent_4 (empty) Parent_4 views def list_quests(request): q = … -
Django - Order by Ascending with None Last with second level order for Nones
As per the title I'd like to order the Fastest Lap values in ascending times with any Nones at the end sorted by Laps Complete descending. My first attempt was .order_by(F('best_lap_time').desc(nulls_last=True), "-laps_complete") which returns the correct order except that Fastest Lap times are descending: So on the basis of Model Meta options - Ordering we attempt to change the Fastest Lap order by swapping desc/asc to .order_by(F('best_lap_time').asc(nulls_last=True), "-laps_complete") and this returns where the None values are now at the top: Its almost like asc exists before the second order by is completed. -
how can I redirect user to public profile in django
I have a model called Product that has a user field, and a Profile model that also has a user field. What i want is: When user A post something from a Product model, and user B also post something from the Product model, I want to redirect visitors or others user to the public_profile page of the user who created that Product model object. For Example: In Stack Overflow, when the user ask a question, you can see their username on that question and anyone in the world can go to that profile page of that user that created that question. urls: path('/<slug:slug>/', views.public_profile, name='Public-Profile'), views: def public_profile(request, slug): return render(request, 'public_profile.html') my template: {% for product in products %} <div class="col-md-3"> <div class="card my-2 shadow-sm bg-body"> <div class="card-head"> I want add the url to this `a` tag <a href="{% url 'Public-Profile' %}"> <span class="material-symbols-outlined"> account_circle </span> {{ user.username }} </a> </div> {% endfor %} my models: class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) description = models.TextField(max_length=1000) image = models.ImageField(upload_to='product-image') price = models.FloatField(max_length=11) category = models.ForeignKey(Category, on_delete=models.CASCADE) phone_number = PhoneNumberField() created_at = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=100, unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) def … -
Not able to divide forloop.counter in django template?
I am using django 4.1.5, and i am trying to divide the current forloop counter with 3. Problem is, i tried so many different syntax, but nothing is working <h3> {{ forloop.counter|div:3 }} </h3> Exception Value: Invalid filter: 'div' <h3> {{ forloop.counter|div:"3" }} </h3> Exception Value: Invalid filter: 'div' <h3> {{ forloop.counter//3 }} </h3> Exception Value: Could not parse the remainder: '//3' from 'forloop.counter//3' <h3> {{ forloop.counter/3 }} </h3> Exception Value: Could not parse the remainder: '/3' from 'forloop.counter//3'\ how can i get the divided value? -
How to use mysql database with django_tenants?
When i run migrations for tenant i got error **Error : ** if connection.schema_name == public_schema_name: AttributeError: 'DatabaseWrapper' object has no attribute 'schema_name' I have tried to use below settings for database engine but it did not work DATABASES = { 'default': { 'ENGINE': 'django_tenants.mysql_backend', # .. } } it was working fine for PostgreSQL db I used below setting i was getting error. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'portals', 'USER':'root', 'PASSWORD':'root', 'HOST': '127.0.0.1', 'PORT': '3306' } } MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', ] DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) TENANT_MODEL = "client.Client" TENANT_DOMAIN_MODEL = "client.Domain" -
Hello I ran into a problem when I was coding a store site with Django
I have the Reverse error for 'single_product' with no arguments not found. 1 pattern(s) tried: ['product/product/(?P<pk_latin_name_product>[-a-zA-Z0-9_]+)\Z'] I got it when I was doing my store project when I wanted to exit the page Be my single product html: <a class="product-thumb" href="{% url 'single_product' category_list.pk_latin_name_product %}"> <img src="{% static 'assets/img/products/07.jpg' %}" alt="Product Thumbnail"> </a> view: def single_product(request, pk_latin_name_product): pk_latin_name_product = get_object_or_404(Products, pk=pk_latin_name_product) product_spicials = Specials.objects.all().filter(pk_latin_name=pk_latin_name_product) print(product_spicials) context = { 'category_titles': Category_Titles, 'menus': Menus, 'category_subheadings': Category_Subheadings, 'product_pks': pk_latin_name_product, 'product_spicials': product_spicials, } return render(request, 'product/single-product.html', context=context) urls: path('product/<slug:pk_latin_name_product>', single_product, name='single_product'), I also read some things, but I did not get the right answer Like this question Reverse for 'product' with no arguments not found. 1 pattern(s) tried: ['product\\/(?P<slug>[^/]+)\\/$'] -
Django Modelform DateTime Picker
I would like to get a date AND time picker for my django model form. model: class ServiceBooker(models.Model): regnr = models.CharField(max_length=255) namn = models.CharField(max_length=255, null=True, blank=True) telnr = models.CharField(max_length=255) email = models.EmailField(max_length=255) service_date = models.DateTimeField() booked_date = models.DateTimeField(auto_now=True) kommentar = models.TextField() service_name = models.ForeignKey(ServiceType, on_delete=models.CASCADE) noteringar = models.TextField(default='') forms.py: class ServiceBookerForm(forms.ModelForm): service_date = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M'], widget=forms.DateTimeInput( format='%d/%m/%Y %H:%M', attrs={'class': 'form-control'})) class Meta: model = ServiceBooker fields = '__all__' exclude = ('noteringar',) But on the website it doesn't show the datetimepicker. I know how to fix the date picker with: 'service_date': widgets.DateInput(attrs={'type': 'date'}) but I would like to get a date AND time picker. Can anyone help me? :-) Thanks! -
best name for class of types (options)
i have app in my project for types that user can define or change types. for example: it hold gender types, education types to use in HTML options for more versatility. i don't want to name it options or types (conflict with language keyword). what is another names you can suggest -
Best approach of storing files with a django model
I'm trying to figure out how which approach will be a more suitable way of storing files for the model described below: def user_directory_path(instance, filename): return f"books/{instance.slug}/{filename}" class Book(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=150, verbose_name="Title") slug = models.SlugField(unique=True, max_length=100, verbose_name="URL") cover = models.FileField( upload_to=user_directory_path, null=True, blank=True, verbose_name="Cover" ) epub = models.FileField( upload_to=user_directory_path, null=True, blank=True, verbose_name="EPUB" ) pdf = models.FileField( upload_to=user_directory_path, null=True, blank=True, verbose_name="PDF" ) The folder structure of this approach looks like this: mediafiles/ books/ <instanse.slug>/ <cover> <epub> <pdf> And the only problem I have here is that when I delete the entity of a book in the database, the <instanse.slug> folder is still there. I don't know what other issues could be here if there are any. So I'd like to know what could be a more practical solution for this particular model. -
How to add dynamic content using django
I am developing a web app using Django. This can be used by teachers to keep track of all their classes. When a teacher creates a new class using this app, the teacher can specify the details of the class like semester, students enrolled, etc. I need to create a success page for this that will show the details using Django