Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Caddy server: Running a Django app behind a reverse proxy with docker-compose
I just discovered CaddyServer, and it looks super promising for running multiple applications on the same VPS with Docker. But I'm struggling to set my docker-compose.yml file(s) to work with external domains. I'll use gunicorn later in production, for now I'd just be happy to get the Django runserver to work. Here's my directory structure: caddy/ Caddyfile docker-compose.yml djangoApp/ docker-compose.yml Dockerfile config/ ... manage.py requirements.txt myghostapp/ This is caddy/Caddyfile { email john@gmail.com acme_ca https://acme-staging-v02.api.letsencrypt.org/directory } app1.example.com { reverse_proxy django:8000 } # app2.example.com { # reverse_proxy ghost:2368 # } app2.example.com is my intended second domain, which points to a ghost application. This one works when uncommented (I'm including it for reference). This is caddy/docker-compose (the reverse proxy) version: "3" networks: web: external: true services: caddy: image: caddy:2-alpine restart: unless-stopped ports: - "80:80" - "443:443" volumes: - /data/caddy/Caddyfile:/etc/caddy/Caddyfile networks: - web django: build: context: /data/djangoApp/ dockerfile: /data/djangoApp/Dockerfile restart: unless-stopped environment: - url=app1.example.com volumes: - /data/djangoApp:/app/ networks: - web # ghost: # image: ghost:3.22-alpine # restart: unless-stopped # environment: # - url=app2.example.com # volumes: # - /data/myghostapp:/var/lib/ghost/content # networks: # - web For now, it would be great to get the Django app working. In the djangoApp folder, I have a Dockerfile like … -
Is it possible to automatically run a function on django app thru settings.py?
I have this function on my views.py, I need to automatically runs it after I run python manage.py runserver a guy said that I must run that function it on settings.py. I tried it but I can't import the views & models to my settings.py (maybe because im noob?) so I can't do what he suggested. This is the process, I have a toggle button for enabling and disabling auto_sms function on my frontend javascript(vuejs). if I pick enable it will call the API endpoint of auto_sms thru axios. like do this in a while loop, check in every 30 mins then repeat until get executed then reset. wait for another condition to be valid. responses.count() if I pick disable it will call the API endpoint of disable_sms thru axios (I haven't started coding this yet). like if its detects that auto_sms is true then make it false. I want to ask, is my imagination for my application is possible to happen? @models.py class Rainfall(models.Model): level = models.CharField(max_length=10, blank=True, default='') amount = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True) def update_level(self): if 0.1 <= self.amount < 2.5: return 'Light' elif 2.5 <= self.amount < 7.5: return 'Moderate' elif 7.5 < self.amount < 15: … -
Many to Many duplicate when saving entity with multiples words (ex. The government)
I got a question. I've a models with some M2M fields. My goal is to classify the text. After saving my text, my M2M starts classifying: create a new entry if it does not exist, add the entry if it already exists, But I got an issue: For simple word there is no duplicate but for multiple word (ex. Mr President or Christophe Colomb) I got an error with duplicate entry. class Categories(models.Model): name = models.CharField(max_length=20, unique=True) image_url = models.URLField(max_length=200,blank=True) slug = models.SlugField(editable=False) def save(self, *args,**kwargs): if not self.slug: self.slug = unique_slugify(self, slugify(self.name)) super(Categories, self).save(*args, **kwargs) def __str__(self): return self.name ... catego = models.ManyToManyField('Categories',blank=True, related_name='post_catego') In the save method I got this: for category in response.categories: current_category = Categories.objects.filter(name=category.name) current_post = get_object_or_404(Post, slug=self.slug) if current_category.count()<1: create_category = self.catego.create(name=category.name) current_post.catego.add(create_category) else: existed_category = Categories.objects.get(name=category.name) current_post.catego.add(existed_category) -
Why is my test function not activating the user?
I have a django email verification app that sends email with activation url that contains encoded user pk and a token, then when app recieves the correct data in a url it sets user.is_active boolean value to True. I've written a test that is supposed to create a user and send a get request with it's encoded pk and a token, but it fails to activate my user even though the url is correct (as you will be able to see below) views.py contains signup function and verification class based view. def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): user = form.save(commit=False) raw_password = form.cleaned_data.get('password1') name = form.cleaned_data['name'] gender = form.cleaned_data['gender'] user.is_active = False user = User.objects.create(email=user.email, password=raw_password, name=name, gender=gender) user.set_password(raw_password) user.save() # Verification email_subject = 'Activate your followerr account' domain = get_current_site(request).domain user_id = urlsafe_base64_encode(force_bytes(user.pk)) link = reverse('activate', kwargs={ 'user_id': user_id, 'token': token_generator.make_token(user), }) activate_url = 'http://' + domain + link email_body = 'Hello ' + user.name + ' please use this link to verify your account\n' + activate_url email = EmailMessage( email_subject, email_body, 'noreply@domain.com', [user.email], ) email.send() return redirect('login') else: form = SignupForm() return render(request, 'signup.html', {'form': form}) class VerificationView(View): def get(self, request, user_id, token): … -
Django and React always Bad Request when submitting
I am developing a E-Prescription Web App using Django Rest Framework and Bootstrap-React. But I'm facing an error saying that POST http://127.0.0.1:8000/api/prescription-view/ 400 (Bad Request) How to fix this? Btw here's my codes: settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'prescribe_app', ] CORS_ORIGIN_ALLOW_ALL = True MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] views.py @api_view(['GET', 'POST']) def prescription_view(request): if request.method == 'GET': prescription = Prescription.objects.all() serializer = PrescriptionSerializerView(prescription, many=True) return Response(serializer.data) elif request.method == 'POST' : serializer = PrescriptionSerializerView(data=request.data) if serializer.is_valid(): serializer.save() else: content = {'Error': 'Invalid data'} return Response(content,status=status.HTTP_400_BAD_REQUEST) return Response(serializer.data) serializers.py class PrescriptionSerializerView(serializers.ModelSerializer): class Meta: model = Prescription fields = ['drug_name' , 'dosage' , 'route', 'frequency', 'amount_dispensed', 'no_of_refills'] Form.js import React from 'react'; import { Row, Card, Col, Table, Form, Button} from 'react-bootstrap'; class FormPage extends React.Component{ constructor(props){ super(props); this.state = { prescriptionList: [], activeItem: { id:null, drug_name:'', dosage:'', route:'', frequency:'', amount_dispensed:'', no_of_refills:'' }, editing:false, } this.viewPrescription = this.viewPrescription.bind(this) this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) this.getCookie = this.getCookie.bind(this) // this.deleteItem = this.deleteItem.bind(this) // this.startEdit = this.startEdit.bind(this) // this.strikeUnstrike = this.strikeUnstrike.bind(this) }; getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for … -
How do I add Django to path
When I try the following command: django-admin startproject pyshop . It says this django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 django-admin startproject pyshop . What can I do to get this to work? -
MS Azure Oryx Pre Build Command
Trying to add a Oryx Pre Build Command for apt-get package as per the documentation found here I added the command as an App Setting in the Azure App Service Portal, but when the project builds, it doesn't run the command. Did I place the command in the correct location? -
Django using pre_save to assign username to user if username was empty due to an error
I am trying to use pre_save signal to assign random username to any user if due to an error their username was empty (Social login or edit profile error). Currently, I have: @receiver(pre_save, sender=Profile) def set_username(sender, instance, **kwargs): if not instance.username: rand = random.getrandbits(64) username = "user" + str(rand) while Profile.objects.filter(username=username): rand = random.getrandbits(64) username = "user" + str(rand) instance.username = username Now I was wondering to be safer, how can I generally filter out profiles in my ProfileManager? Can I change the get_queryset() method? Since I read that isn't safe to do so. Or is my pre_save signal enough to make sure users will always have a username no matter what? -
Django Operational Error - problem with UserProfiles in All auth
I am trying to added extra User Profiles within all auth module. However I am still getting the error no such column: profiles_userprofile.default_house FORMS.PY from django import forms from .models import UserProfile class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile exclude = ('user',) def __init__(self, *args, **kwargs): """ Add placeholders and classes, remove auto-generated labels and set autofocus on first field """ super().__init__(*args, **kwargs) placeholders = { 'default_phone_number': 'Phone Number', 'default_postcode': 'Postal Code', 'default_town_or_city': 'Town or City', 'default_street_address1': 'Street Address 1', 'default_house': 'Street Address 2', 'default_home': 'Nr mieszkania', } self.fields['default_phone_number'].widget.attrs['autofocus'] = True for field in self.fields: if field != 'default_country': if self.fields[field].required: placeholder = f'{placeholders[field]} *' else: placeholder = placeholders[field] self.fields[field].widget.attrs['placeholder'] = placeholder self.fields[field].widget.attrs['class'] = 'border-black rounded-0 profile-form-input' self.fields[field].label = False MODELS.PY from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class UserProfile(models.Model): """ A user profile model for maintaining default delivery information and order history """ user = models.OneToOneField(User, on_delete=models.CASCADE) default_phone_number = models.CharField(max_length=20, null=True, blank=True) default_postcode = models.CharField(max_length=20, null=True, blank=True) default_town_or_city = models.CharField(max_length=40, null=True, blank=True) default_street_address1 = models.CharField(max_length=80, null=True, blank=True) default_house = models.IntegerField(null=True, blank=True) default_home = models.IntegerField(null=True, blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): """ Create or update … -
Unusual Behaviour of template on passing parameter via url in Django
I am developing a fitness website in django, and in my project I have 2 different apps, one is main_app and other is user_app And I have 2 templates in user_app: one is calorie-tracker.html, other one is profile_page.html Now I am extending these 2 templates from base.html present in main_app. The calorie-tracker.html works fine as expected but for profile_page.html the css files (included in base.html) are not working. The only difference is that for profile view I take username as argument via url, but not for calorie-tracker view. main_app/templates/main_app/base.html {% load static %} <!-- I've cleaned the unneccesary html from page --> <!DOCTYPE html> <html lang="en"> <head> <!-- CSS --> <link rel="stylesheet" href="../../static/main_app/css/style.css"> <link rel="stylesheet" href="../../static/main_app/css/login_register_style.css"> <link rel="stylesheet" href="../../static/main_app/css/calorie-tracker_style.css"> <link rel="stylesheet" href="../../static/main_app/css/profile_style.css"> </head> <body> {% block content %} {% endblock content %} </body> </html> user_app/urls.py from django.urls import path from . import views urlpatterns = [ path('profile/<un>/', views.profile, name='profile'), path('calorie-tracker/', views.calorieTracker, name='calorie-tracker'), ] user_app/views.py from django.shortcuts import render, redirect def profile(request,un): return render(request,'user_app/profile_page.html',{"username":un}) def calorieTracker(request): return render(request,'user_app/calorie-tracker.html') user_app/templates/user_app/calorie-tracker.html (works fine - renders proper css) {% extends 'main_app/base.html' %} {% load static %} {% block content %} <!-- Messages --> {% include 'main_app/show_messages.html' %} <!-- Navbar --> {% include 'main_app/navbar.html' %} … -
Error with read JSON file lines in Django app
I have this code but I have some lines in my JSON file with empty lines. And I get this error. This is a Custom Command and I get this error. I want to create a list of jobs in The database of my Django app, I am using a For loop. Thank a lot for your help raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 2) from django.core.management.base import BaseCommand from jobs.models import Job import json class Command(BaseCommand): help = 'Set up the database' def handle(self, *args: str, **options: str): with open('static/joblist03112020.json', 'r') as handle: for line in handle.readlines(): print(line) line = json.loads(line) existing_job = Job.objects.filter( job_title = line['job_title'], company = line['company'], company_url = line['company_url'], description = line['description'], salary = line['salary'], city = line['city'], district = line['district'], url = line['url'], job_type = line['job_type'], ) if existing_job.exists() is False: Job.objects.create( job_title = line['job_title'], company = line['company'], company_url = line['company_url'], description = line['description'], salary = line['salary'], city = line['city'], district = line['district'], url = line['url'], job_type = line['job_type'], ) Job.save() self.stdout.write(self.style.SUCCES('added jobs!add')) -
Adding Migrations to Source Control and Merging Conflicting Migrations in Django
I took over a Django project and discovered that migrations for various apps were not being tracked by Git. That seemed a bit problematic since my understanding was that one should always track the migrations. Is that pretty much the consensus or are there reasons not to do it? The second part of the question has to do with the fact that I have done some work involving tweaking some migrations locally. I would now like to push the changes to production. However, I am unsure as to what the best way to combine the possible conflicts would be. For instance, in production, I have the following: Untracked files: (use "git add <file>..." to include in what will be committed) mysite/aldryn_forms/migrations/0019_auto_20200730_1455.py mysite/apps/common/migrations/0016_auto_20200624_2028.py mysite/apps/common/migrations/0016_auto_20200625_1125.py mysite/apps/common/migrations/0017_merge_20200625_1129.py mysite/apps/common/migrations/0018_auto_20200720_1743.py mysite/apps/payment/migrations/0005_auto_20200624_2028.py mysite/apps/payment/migrations/0005_auto_20200625_1125.py mysite/apps/payment/migrations/0006_merge_20200625_1129.py mysite/apps/payment/migrations/0007_auto_20200720_1743.py mysite/apps/payment/migrations/0008_paymentmodel_course.py mysite/apps/payment/migrations/0009_paymentmodel_user.py mysite/apps/plugins/migrations/0016_auto_20200624_2028.py mysite/apps/plugins/migrations/0016_auto_20200625_1125.py mysite/apps/plugins/migrations/0017_merge_20200625_1129.py mysite/apps/xyz/migrations/0005_auto_20200730_1455.py Locally, I have the following: Untracked files: (use "git add <file>..." to include in what will be committed) mysite/aldryn_forms/migrations/0019_auto_20201108_1623.py mysite/apps/common/migrations/0016_auto_20201108_1623.py mysite/apps/common/migrations/0017_auto_20201108_1806.py mysite/apps/payment/migrations/0005_auto_20201108_1623.py mysite/apps/plugins/migrations/0016_auto_20201108_1623.py mysite/apps/xyz/migrations/0005_auto_20201108_1623.py These are the files with custom work: mysite/apps/common/migrations/0016_auto_20201108_1623.py mysite/apps/common/migrations/0017_auto_20201108_1806.py It appears that all the migrations existing on the production server have been applied to the production database. Hence, I have concluded that they correctly describe the state of the production DB. … -
Not getting request.POST back to view when multiple bootstrap models on same page
I'm learning some javascript and hopefully Ajax to make my django more interactive. I was able to get a single modal to work fine, but when I tried to have two separate modals, it doesn't seem that I get a post request back to the view I was using. I'm trying to take things step by step. What I had tried before also had the issue of not hangling the CRSF_Token correctly, but I made View function CRSF exempt to get around that temporarily and was going to figure that out later. My View is: @csrf_exempt def home(request): obj=Item.objects.all() form=ItemForm(request.POST) print(request.POST) if form.is_valid(): form.save() return render(request,'mainapp/home.html',{'obj':obj,'form':form}) My html that connects to the modals is: <div class="d-inline text-center"> <small class="text-muted" data-toggle="modal" data-target="#exampleModal_comment" data-whatever="{{ my_obj.id }}">Add Comment</small> <small class="text-muted">&nbsp &nbsp </small> <small class="text-muted" data-toggle="modal" data-target="#exampleModal" data-whatever="{{ my_obj.id }}">Change Rank</small> <small class="text-muted">&nbsp &nbsp </small> <a href="javascript:{document.getElementById('delete{{ my_obj.id }}').submit()}">Delete</a> </div> My html and the javascript is: <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Enter New Rank</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="{% url 'mainapp:home' %}" method="post"> {% csrf_token %} {{ form.new_rank }} <button type="button" … -
course registration system in django
I'm trying to do course registration system for a school app with django. the idea of here a program is contain multiple courses, so student can choice one program then will have courses related to that program, and they can register course for future exam. what would be the way I can handle this with django, i really need this system so bad, really would be so much appreciate for your help/suggetions..is this i can do with django? should i create separate model and views also forms for program and course? if so how can I show the form for related program's students ? thank you so much . model.py class CurrentStatus(models.Model): student = models.ForeignKey( Student, on_delete=models.SET_NULL, null=True) current_status = models.CharField(max_length=10, choices=Current_STATUS) faculty = models.ForeignKey('Faculty', related_name='student_curent_faculty', on_delete=models.SET_NULL, blank=True, null=True) dept = models.ForeignKey('Department', related_name='student_curent_department', on_delete=models.SET_NULL, blank=True, null=True) program = models.ForeignKey('Program', related_name='student_curent_program', on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return self.current_status class Program1_course_name(models.Model): # Program1 courses... faculty = models.ForeignKey(Faculty, on_delete=models.CASCADE, blank=True, null=True) dept = models.ForeignKey(Department, on_delete=models.CASCADE, blank=True, null=True) program = models.ForeignKey(Program, on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=100) code = models.CharField(max_length=10) credit = models.IntegerField() def __str__(self): return (f'{self.faculty},{self.dept},{self.program},{self.name}') class Course1(models.Model): # Course1 Registration..... student = models.ForeignKey(Student, on_delete=models.CASCADE, blank=True, null=True) course = models.ManyToManyField(Program1_course_name, blank=True) def __str__(self): … -
How to filter objects with LineString field by distance to a Point?
I have a model with a LineStringField, which represents a path, as such: class Link(models.Model): # Non-relevant fields omitted geometry = models.LineStringField(srid=3067) Now, I'd like to query for objects where the distance of any point in the line string is less than a given distance (say, 100 meters). I've tried this query: lat = float(self.request.query_params['lat']) lon = float(self.request.query_params['lon']) point = Point(lat, lon, srid=4326) return Link.objects.filter(geometry__distance_lt=point, 100) However, this yields zero results, even if I increase the distance limit to hundreds of kilometers (all the test data is within about 50 km from the given lat/lon point). Is there something wrong in my query? -
How can I implement search bar in a form in Django-rest framework?
I'm new to Django-rest. I want to implement a search bar in a form to search username and location, with history and suggestions when the user starts to write. for example when the user writes "@jam" the search bar suggests "@jamesbond or @jame or ... ". can anyone tell me what should I do step by step? ps:my db is sqlit3. thank you in advance. -
populating drop down using database Django
I followed the instruction from another stackoverflow, but somehow it end up the same, the list didn't drop. so what did I do wrong to be exact? Here's my model : class Fakultas(models.Model): fakul = models.CharField(max_length=50,unique=True) def __str__(self): return self.fakul class Userdata(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE) faculty = models.ForeignKey(Fakultas,on_delete=models.CASCADE,default= 1) is_voted = models.BooleanField(default=False) def __str__(self):return self.user.username Here is my Form : class UserFakultas(forms.ModelForm): faculty = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control'})) class Meta: model = Userdata fields =['faculty'] def __init__(self,*args,**kwargs): super().__init__(*args, **kwargs) self.fields['faculty'].choices = [(faculty) for faculty in Fakultas.objects.all()] -
Imagefield in Django HTML Variable
I'm new to Django and trying to create a website with uploading image via Django Admin. I'm trying to view image uploaded in Imagefield in my HTML. But i just can't get the image working right. Banner.objects.all() doesn't seems able to get all the image file located in media folder. urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py from django.db import models from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver from django.utils import timezone from django.contrib.auth.models import User from PIL import Image class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) #auto_now=True //auto date author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class Banner(models.Model): title = models.CharField(max_length=100) images = models.ImageField(upload_to='images',null=True,blank=True) def __str__(self): return self.title views.py from django.shortcuts import render from django.views.generic import( ListView, DetailView ) from .models import * # Create your views here. class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] #arrange date posted with latest on top paginate_by = 6 def Banner_view(request): banner = Banner.objects.all() return render(request, 'blog/home.html',{'banner':banner}) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] … -
Django animated fade in of content
I have a blog website built with django and I want the user to see the posts fade in and then out as he scrolls on top of them. My code in the HTML template where the posts are looks like this: {% for post in posts %} <div> { post content ... } </div> {% endfor %} -
django-crispy-forms ImageField Design
django-crispy-forms nice tools for rendering beautiful forms faster. Problem is in imagefield. Its looks like below. Is there any prettier layout? Please help me to customize -
how to give auto sizing to images in django?
i want to build E-Commerce website And Generly it takes so many images and as you know that it's not good way to give width and height to every image so for this problem i need some one to help me to solve it in django .. -
How to implement Google, Facebook and Email login functionality in Django using firebase?
I am developing a mobile app that allows the user to login via Google, Facebook, and email. I am trying to implement it using firebase and firebase admin SDK. What is the proper way to implement this? I need to know more about the implementation login and need clarity about the following questions. How to create the user. Create the user directly from the app by using functions like signInWithCredential() and createUserWithEmailAndPassword() or user create the user with create_user() in the server using Django and firebase-admin SDK. Do we need to keep the uid in any tables in the Django database? Do we need to create the default User model provided by Django for authentication. -
How to save the social token with Django allauth?
I managed to login with Discord, everything works fine, but to do api calls for retrieving more informations (in my case the connections, also edited the scopes for it), I need the oauth2 social token. In the database there is a table called socialaccount_socialtoken, so i think allauth is able to ask for it automatically. The documentation doesn't write anything about it. Do I have to make a custom callback view which retrieves the social token and saves it to the database? -
Ecommerce books for Django junior developer
I like to follow written tutorials and learning by doing alongside with reading online documentation to get the context. I am now passionate "junior Django web developer" and i would like to build some dropshipping eshop in Django bcs it is platform that i trust and like to learn. Nevertheles i would like to know your recommendation for the books in terms of SEO, eshop UI and maybe even Django itself eventhough after bunch of online videos and books i fell in love of series of William Vincets books: "Django for Beginners" and "Django for Professionals". For SEO i heard good review for "The Art of SEO" so maybe that could be good pick. Also thinking about the dropshiping. Since i dont own any product and i want to learn how to build eshop and test it by market, i dont even know what dropshiping products could be good or not. Or what commision in % should be for me. Is there any good practical book about dropshipping too? In short i need books for like: Comprehensive guide for eshop SEO Modern UI designbook for variety of eshops Comprehensive guide for dropshipping Any recommendation please? Thank you -
django admin overriding delete_model not working with bulk delete
I want to disable deleting for a specific model instance I overrided delete_model in the ModelAdmin as follows : def delete_model(self, request, client): if client.schema_name == 'public': messages.set_level(request, messages.ERROR) messages.error(request, 'Suppression interdite pour la racine') else: super().delete_model(request, client) It works when I click the delete button on change view But not with bulk delete as the instance is deleted without preventing How can I fix this ? I also realized that delete_model is not called with bulk delete which makes a bit weird.