Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django logging only works when restart
I've asked a similar questions before, but having trouble getting more information on what the problem is. I have a Django app, and its running with channels. So, Django, Daphne, Channels, NGINX, Redis I have logging configured like this: # Logging LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'propagate': True, 'level': 'INFO' }, 'dashboards': { 'handlers': ['console'], 'propagate': False, 'level': 'DEBUG', }, }, } Channels: CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, "ROUTING": "app.routing.channel_routing", }, } In my view: import logging loger = logging.getLogger(__name__) def index(request): loger.debug(":dsfasdfasdfasdfasdfasdfasdfasdfasdfasdf") return render(request, 'site/index.html', context) Using supervisor to manage service: [program:Daphne] environment=PATH="/opt/site/venv/bin" command=/opt/site/venv/bin/daphne -b 0.0.0.0 -p 8000 site.asgi:channel_layer --proxy-headers -v2 directory=/opt/site/site autostart=true autorestart=true redirect_stderr=true stdout_logfile=/tmp/daphne.out.log [program:Worker] environment=PATH="/opt/site/venv/bin" command=/opt/site/venv/bin/python manage.py runworker -v2 directory=/opt/site/site process_name=%(program_name)s_%(process_num)02d numprocs=10 autostart=true autorestart=true redirect_stderr=true stdout_logfile=/tmp/workers.out.log I can see the worker logs upon request to the page, and I can also see the exceptions hit the log (/tmp/workers.out.log). 2018-12-13 21:36:22,396 - DEBUG - worker - Got message on http.request (reply daphne.response.SrXmOkzSNt!bUdAxibnQp) 2018-12-13 21:36:22,396 - DEBUG - runworker - http.request 2018-12-13 21:36:22,397 - DEBUG - worker - Dispatching message on http.request to channels.staticfiles.StaticFilesConsumer … -
How to get multiple values from joined tables
How can I get all the laws from all the courses that an specific user is subscribed? class Law(models.Model): name = models.CharField('Nome', max_length=100) slug = models.SlugField('Atalho') description = models.TextField('Description', blank = True, null=True) class Course(models.Model): name = models.CharField('Nome', max_length=100) slug = models.SlugField('Atalho') description = models.TextField('Descrição', blank = True, null=True) laws = models.ManyToManyField(Law, related_name='law_course') class Subscription(models.Model): STATUS_CHOICES=( ( (0, 'Pendente'), (1, 'Approved'), (2, 'Canceled'), ) ) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, verbose_name="Usuário", related_name="inscricao") #inscricao é criado no usuario course = models.ForeignKey(Course, on_delete=models.CASCADE, verbose_name="Course", related_name="subscription") status = models.IntegerField( 'Status', choices=STATUS_CHOICES, default = 0, blank=True ) class Meta: unique_together = (('user','course')) So, the user can be subscribed in one or more courses. Each course has one or many laws. I have a page that I need to list all the laws of each course that an specific user is subscribed if the subscription is Approved (status = 1). Example: The user John has subscribed in 2 courses: Course A and Course B. Course A laws: law1, law2, law3 Course B laws: law1, law20, law30 So, when John is logged in, I need to show the laws of the courses and the name of the course: law1 - Course A, Course B law2 - Course A … -
Deploying Django to AWS; static files for dummies
I am utterly lost on one of the last steps of this project. So far, I've been able to develop a django app that works the way I want it to on localhost; I've been able to deploy the website to AWS EC2, but I must be missing something fundamental about serving the static files. (I haven't even tried media files yet.) I've read the Django Deployment page and How-To manage static files, but I have never deployed a website from scratch before. The tutorials I've found seem to be contradicting (or outdated?). Here are the questions I think I have at this time: Do I need to host static (and/or media) files in a bucket, or is this merely a good idea? When I set up STATIC_ROOT and STATIC_URL, should I have a STATICFILE_DIRS setup? (I mean, I think I really need a tutorial on how they even go together, their settings, and how 'static' works in the templates.) I've tried to get whitenoise going; I get a message that STATIC_URL isn't set up correctly; I can't find the documentation to tell me what it should be. Is this a viable root to take? -
Django Channels windowsSelectorEventLoop object has no attribute 'create_future'
I am now using Django Channels for WebSockets and it requires the use of Redis. I download the frontend and backend from here: https://revs.runtime-revolution.com/a-simple-real-time-chat-with-django-channels-and-react-b73edc3a79f2 However, I constantly have the error of '_WindowsSelectorEventLoop' object has no attribute 'create_future'. I am using Python 3.5, Django 2.1, Windows 7, Redis 2.4. It this because the redis version compatible on Window 7 is too old or because of sth. else? -
Django plus jQuery Ajax: can't add csrf_token to form when preventing default, adding data, and resubmitting
This is the first time i post, i hope i do it correctly. I spent days on this issue and it seems i just can't find a solution. I need to add data to a form before submitting. The data i'm adding is a bit complex so it has to go into a JSON object (it includes characteristic of a previously drawn polygon on the same page). The html looks like this: <form id="form-submit-data" action="{% url 'app_name:submit-data' %}" method="POST"> {% csrf_token %} <input type="text" id="input-value" name="my-value"> <input type="submit" value="Confirm"> </form> After days of digging i settled for the below implementation (it comes from Cory Danielson's reply with 61 votes posted here: How to trigger an event after using event.preventDefault() ). The problem is that if i add the decorator @csrf_exempt in my views function my form gets submitted twice, once with the data formatted correctly and once it looks like this "csrfmiddlewaretoken=2cYsUn5m50RU1oFwOjPsGpCY5HBelIjQPOOV52KoTpQMWE2zRPzwsDA0UKrI7ZFj&my-value=35": If i do try to add the csrf_token to the post request (and commenting out the decorator in my views function) i first get a "Forbidden (CSRF token missing or incorrect.)" 403 error and when i refresh i get "code 400, message Bad request syntax (' {[my data … -
Accessing django website hosted on vm with mobile device
I run my django website with python manage.py runserver 0.0.0.0:8080 on Vagrant which is set up to forward 8080 port to 8081 on host machine. I'm able to access this website on host by going to it's local ip (192.168.X.X) but can't on mobile device (of course also by going into it's local ip). Any idea? All I could find about this is to run server with 0.0.0.0 what is already happening in my case. -
How to use Webtorrent.io to play a video in HTML?
I got a torrent link in for a movie that im trying to play on a web page but im confushed how i actually use webtorrent.io. The code below is something ive copied for testing purposes, how would i use the script/Play the video in the "Vid" Tag? <!DOCTYPE html> <html lang="en" dir="ltr"> <head> </head> <body> <div class="Vid"> #I want to use the script here </div> <script type="text/javascript"> var client = new WebTorrent() var torrentId = 'magnet:?xt=urn:btih:6268ABCCB049444BEE76813177AA46643A7ADA88&tr=udp://glotorrents.pw:6969/announce&tr=udp://tracker.opentrackr.org:1337/announce&tr=udp://torrent.gresille.org:80/announce&tr=udp://tracker.openbittorrent.com:80&tr=udp://tracker.coppersurfer.tk:6969&tr=udp://tracker.leechers-paradise.org:6969&tr=udp://p4p.arenabg.ch:1337&tr=udp://tracker.internetwarriors.net:1337&tr=wss%3A%2F%2Ftracker.webtorrent.io' client.add(torrentId, function (torrent) { var file = torrent.files[0] file.appendTo('body') // append the file to the DOM }) </script> </body> </html> -
Modeling a restaurant menu with django
I am creating a website with a collection of menus from restaurants in my town (since none of them seem to be on grubhub or the internet). I am having trouble creating a model for this. As you know every restaurant menu has sections(I.e Appetizers, Chicken, Steak) and entries under each section(I.e under Appetizers: Mozzarella Sticks, Nachos, etc.) I am trying to create a Menu model so that each section of the menu and all of its entries can automatically fill a template: <h1>{{section}}</h1> <!--I.e:"Appetizers"--> <p>{{food}} </p><!--I.e:"Mozzarella Sticks"--> <p>{{ food_details }}</p> With the above template, I can use a loop to loop through each section, then another inner loop to loop through each food and food_details belonging to that specific section, but I am not sure how to model this properly: from django.db import models class Restaurant(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) phoneNumber = models.CharField(max_length=10) def __str__(self): return "%s the place" % self.name class Menu(models.Model): restaurant = models.OneToOneField( Restaurant, on_delete=models.CASCADE, primary_key=True, ) # not sure how to build menu fields #if I do the following each menu will only have one of these fields, which will not work: section = models.CharField(max_length=50) food = models.CharField(max_length=50) food_details = models.CharField(max_length=200) How can … -
403 Forbidden CSRF verification failed. Request aborted
I got this error when i try to login in my website. I have {% csrf_token %} in my form and 'django.middleware.csrf.CsrfViewMiddleware' in my setting file. I try to run in another browser and it run without error. I was delete cache and cookies in chorm but it didn't work -
The right way to use Ajax to Update a Single field in a specific Object
Is it possible to use Ajax to Update a Single field in a Specific Object? I have an postgres table with lots of records, I want to use a jquery Ajax request to update a single field in a specific object within that table. Can that be done without replacing or reposting the entire record?. I want this (Gives me a 400 bad request error): $.ajax({ type: "POST", url: '/api/MyEndPoint/', data: { id: Specific_Record, Field_To_Update: New_Value, }, success: function(data){ console.log( 'success, server says '+data); } }); Instead of this (which works): $.ajax({ type: "POST", url: '/api/MyEndPoint/', data: { id: Specific_Record, Field_To_Update: New_Value, Field1: SameAsBefore, Field2: SameAsBefore, Field3: SameAsBefore, ... Field16: SameAsBefore, }, success: function(data){ console.log( 'success, server says '+data); } }); *Note: I'm using Django, and could easily do this update in views.py but I want to use Javascript to avoid a page refresh. Since I'm also using Django Rest Framework, would it be better for me to create a new endpoint that is specific to the field I want to update? ex: /api/DB_Table/Object_id/Field_to_Update Thanks! -
Django newbie - URL refusing to match for me..
Currently learning the ways of the Django. But stuck on the following. html <a href="{% url 'module:review' module.name area vocabs.name 'Review' %}" class="btn btn-primary btn-sm btn-block" role="button">Review</a> url.py url(r'^(?P<module_name>\w+)/(?P<area>\w+)/(?P<vocab_name>\w+)/Review$', views.review, name='review'), views.py def review(request,module_name,area,vocab_name): try: vocabObj = Vocab.objects.get(name=vocab_name) if area == 'Vocab': reviewItems = vocabObj.vocabcontent_set.all() elif area == 'Phrase': reviewItems = vocabObj.phrasecontent_set.all() except Modules.DoesNotExist: raise Http404("No Words found") return render(request, 'module/reading.html', {'reviewItems': reviewItems}) The error i'm getting NoReverseMatch at /Introduction/Vocab/ Reverse for 'review' with arguments '('Introduction', 'Vocab', 'Numbers', 'Review')' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I would appreciated getting pushed in the right direction on this Thanks -
how to add data into database in django?
I am having trouble about how to solve this problem...Please help me get out of this error...it's also printing the value and database table is already created .following is my code and error says something like Exception Value: save() missing 1 required positional argument: 'self' //This is my model.py file rom django.db import models class Reg(models.Model): name = models.CharField(max_length=20) //this is my form.py file from django import forms class RegistrationForm(forms.Form): name = forms.CharField() //this is my view.py file from django.shortcuts import render from .forms import RegistrationForm from .models import Reg def ragistration(request): if request.method == "POST": form = RegistrationForm(request.POST) if form.is_valid(): Reg.name = form.cleaned_data.get('name') Reg.save() print(Reg.name) else: form = RegistrationForm() return render(request, 'registration/reg.html', {"form": form}) //I got this error Exception Value: save() missing 1 required positional argument: 'self' -
Submitting request to https returns http
Heyo! So I'm creating and angular app that uses a django backend accessed as a Api. The link for my backend is https, and one of its main purposes is to act as a database for image storage. I am trying to grab the URLs in the backend by using http calls from my front end. It's not working because the GET calls only return Http urls not Https. This means that when the front end tries to access the url it can't be found :( Does anyone know how I can change my code so Https is returned or can suggest me some type of workaround? Here is my API call: export class ImageService { baseUrl = 'https://link.com'; constructor(private httpClient: HttpClient) { } getBebidas() { return this.httpClient.get(`${this.baseUrl}/bebidas`); } And this is an example of the return (an array of json objects): [{image_url: "http://link.com/image}] Any help would be greatly appreciated! -
Django - clean return needed or something like that
is there any way to return decorator (final line of post) as a clean return response? Otherwise the middleware im using get's sick about this and returns list index out of range. I subclassed the login_required function of django decorator build-in subsets. from myproject import settings from django.contrib.auth import REDIRECT_FIELD_NAME from django.shortcuts import resolve_url from urllib.parse import urlparse from functools import wraps def auth_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_decorator = user_passes_test( lambda u: u.is_authenticated, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator def user_passes_test(test_func, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. """ def decorator(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = request.build_absolute_uri() resolved_login_url = resolve_url(settings.AUTH_URL) # If the login url is the same scheme and net location then just # use the path as the "next" url. login_scheme, login_netloc = urlparse(resolved_login_url)[:2] current_scheme, current_netloc = urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc … -
django static files are not copied to saticfiles folder on dicker's container
I'm trying to understand what am I doing wrong when trying to copy my static/media folder to staticfiles/medialfiles on docker. This is what I have: settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "mediafiles") Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 ENV C_FORCE_ROOT true RUN mkdir /www WORKDIR /www COPY . /www/ RUN pip install -r requirements.txt RUN python3 /www/manage.py collectstatic --noinput docker-compose # use this file only for live production # docker-compose up -d web version: '3' volumes: db_psql: postgis-data: esdata: services: web: build: . restart: always container_name: django_web command: gunicorn --bind 0.0.0.0:8080 LG__CXS4.wsgi depends_on: - nginx volumes: - .:/www ports: - "8080:8080" links: - redis nginx: restart: always image: "nginx" ports: - "80:80" volumes: - ./nginx/conf.d:/etc/nginx/conf.d - ./staticfiles:/static - ./mediafiles:/media When I run my docker file I get: 5355 static files copied to '/www/staticfiles'. but when I look into the container's staticfiles -it's empty. you will note that there are 0 files and as a result the html is off. -
Django: Filtering children of children of model for use within view/template
We have the following model structure: Parent (name, slug, country, children[ManyToMany on Child]) Child (name, country, children[ManyToMany on Grandchild]) Grandchild (name, country) Now, in my view, I want to make sure we are only dealing with data for the current country (country=kwargs["country"]) at all levels. Now, I have been using the following (obfuscated code) in order to filter the children. This allows me to simply reference "children" in the template in order to access the filtered child records, however I'm having trouble determining a best-practice solution for applying this same filtering at the grandchild level. Below is an example of what is working for filtering children, but how do I perform this same filtering within the template when looping through the grandchildren? I don't want a front-end developer to have to understand the data structure - ideally, I would want them to be able to loop through children, and within that loop, loop through child.grandchildren, which will already be filtered. View class: class ParentView(DetailView): model = Parent def get_object(self): return self.model.objects.filter(slug=self.kwargs["slug"], country=self.kwargs["country"]) def get_context_data(self, **kwargs): context = super(ParentView, self).get_context_data(**kwargs) context["children"] = self.object.children.filter(country=self.country) return context Template sample: {% for child in children %} <li>{{child.name}} <ul> {# This list of grandchildren is … -
Can I just use Django admin and write functions and views there?
I would like to develop a management system in Python with Django, Django admin site satisfies part of needs almost. There are still some other functions and views need to be written, such as stock alert, sync data with third-party database etc. I really want to use admin page, just admin page, how to archive it? Really appreciate for any advice. -
Dynamically Multiple marker google map don't show with django
I have a model class name Restaurant with Latitude and Longitude and inserted many data already in this class and by these fields, I wanna show multiple markers of google map. #restaurant.html <div id="map"></div> {% for i in restaurents %} <script> var locations = [ [{{ i.restaurant }}, {{ i.latitude }}, {{ i.longitude }}, {{ i.id }}] ]; {#var locations = [#} {# ['Bondi Beach', -33.890542, 151.274856, 4],#} {# ['Coogee Beach', -33.923036, 151.259052, 5],#} {# ['Cronulla Beach', -34.028249, 151.157507, 3],#} {# ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],#} {# ['Maroubra Beach', -33.950198, 151.259302, 1]#} {#];#} // When the user clicks the marker, an info window opens. function initMap() { var myLatLng = {lat: -33.90, lng: 151.16}; var map = new google.maps.Map(document.getElementById('map'), { zoom: 10, center: myLatLng }); var count=0; for (count = 0; count < locations.length; count++) { var marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[count][1], locations[count][2]), map: map }); marker.info = new google.maps.InfoWindow({ content: locations [count][0] }); google.maps.event.addListener(marker, 'click', function() { // this = marker var marker_map = this.getMap(); this.info.open(marker_map, this); // Note: If you call open() without passing a marker, the InfoWindow will use the position specified upon construction through the InfoWindowOptions object literal. }); } } </script> <script async … -
How to create a link between two html files in local server using django
I have a project "something". In something/shop/templates/shop I have HTML files. I want to have a link between 'main' and 'about' html files, but I do not know how. I tried to do it as in usual HTML file, but it is not working. <a href="about.html"> About </a> Also I tried this way, but it is not working too. <a href="{% url 'about' %}"> About </a> It is in urls.py: urlpatterns = [ url(r'', views.main, name='main'), url(r'^$', views.about, name='about'),] views.py: def main(request): return render(request, 'shop/main.html') def about(request): return render(request, 'shop/about.html') What should I write to get a normal link between them? -
Dajnago - Sorting queryset results in a template
I have the following model: class TestCase(models.Model): tc_id = models.CharField(max_length=20) tc_title = models.CharField(max_length=500) class TestSteps(models.Model): ts_case = models.ForeignKey(TestCase, on_delete=models.CASCADE) ts_seq_no = models.IntegerField(default=1) ts_instruction = models.CharField(max_length=200) I want to display a test case together with its associated test steps in the template. For this I have written two views, one is not so nice but works: def tc_steps(request, pk): case = TestCase.objects.filter(id=pk) steps = TestSteps.objects.filter(ts_case_id=pk).order_by('ts_seq_no') context = {'case': case, 'steps': steps} return render(request, 'testman/tc_steps.html', context) Not very nice because I have to retrieve two querysets. Better to have this one: def tc_steps(request, pk): case = TestCase.objects.filter(id=pk) return render(request, 'testman/tc_steps.html', {'case': case}) because this contains all the information I need in the template. Now the problem: In the template for the second view I use the following tag to display the test steps: {% for step in case.first.teststeps_set.all %} Which works but the steps aren't in the right order. In the template for the first view I just use: {% for step in steps %} And get the correct order (sorted by ts_seq_no) because I did the sorting in the view already. I tried to use a filter but couldn't find one that does what I want. My question is, is there … -
Password required Django REST API User Serializer PUT request
I a the problem that in my Django Rest API User Serializer: The password field is necessary when making a PUT request. Within a POST request this makes sense, but with PUT is especially if PUT is performed by an administrator, the password field should allowed to be empty. How can I change my serializer so that the password is necessary for POST, but empty for PUT? class UserSerializer(serializers.ModelSerializer): """The UserSerializer""" gender = serializers.IntegerField(source='profile.gender', read_only=False) clinic = serializers.CharField( source='profile.clinic.code', read_only=False) title_prefix = serializers.CharField( source='profile.academic_title_prefix', allow_blank=True, read_only=False) title_suffix = serializers.CharField( source='profile.academic_title_suffix', allow_blank=True, read_only=False) email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())]) username = serializers.CharField( validators=[UniqueValidator(queryset=User.objects.all())]) password = serializers.CharField(min_length=8, write_only=True) class Meta: model = User fields = ('id', 'url', 'username', 'first_name', 'last_name', 'gender', 'title_prefix', 'title_suffix', 'clinic', 'email', 'is_staff', 'is_superuser', 'date_joined', 'last_login', 'password') def create(self, validated_data): """Create and return a new user and its associated profile.""" user = User.objects.create_user( validated_data['username'], validated_data['email'], validated_data['password'], ) user.set_password(validated_data['password']) user.first_name = validated_data['first_name'] user.last_name = validated_data['last_name'] user.is_staff = validated_data['is_staff'] user.is_superuser = validated_data['is_superuser'] user.save() # create associated profile profile_data = validated_data.pop('profile') profile = Profile.objects.create( user=user, gender=profile_data['gender'], clinic=Clinic.objects.get(code=profile_data['clinic']['code']), academic_title_prefix=profile_data['academic_title_prefix'], academic_title_suffix=profile_data['academic_title_suffix'], ) user.profile = profile return user def update(self, instance, validated_data): """Update and return a existing user and its associated profile.""" instance.first_name = validated_data.get('first_name', instance.first_name) … -
Django Rest Framework allow not authenticated access to a view in certain cases
I have a ViewSet which permission_classes is set to (permissions.IsAuthenticated,), but I want this view to allow not authenticated access when the method is retrieve(). This is my ViewSet: class AlbumViewSet(viewsets.ModelViewSet): permission_classes = (permissions.IsAuthenticated,) queryset = proxies.AlbumProxy.objects.all() serializer_class = serializers.AlbumSerializer filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,) search_fields = ('name', 'description', 'company__name') filter_fields = ('code', 'company') def retrieve(self, request, pk): password = request.query_params.get('password', None) instance = proxies.AlbumProxy.objects.get(code=pk) if instance.access_code != password and password != settings.MASTER_KEY: raise Exception(_("Invalid password for album {}".format(instance.code))) instance_to_return = serializers.AlbumSerializer(instance=instance, context={'request': request}).data instance_to_return.pop('access_code') return Response(instance_to_return) Is there a way I can disable permission_classes when the method retrieve() is on, but to leave it working in any other case? -
Python: What is the meaning of Django? [on hold]
I started to learn Django. From https://www.djangoproject.com/ Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source. What is the history of Django? Why the name was chosen as Django? What is the meaning of Django? Why is the significance of this name? -
Django ViewDoesNotExist when it does
I have a django app running off a Twisted service that can't resolve the views of some of the applets. I get the error Could not import apps.ai_stats.views. Error was: No module named aidb when I navigate to those applets in the browser, the only issue is that the aidb.py file is absolutely located in these applet directories. My structure is as follows. apps/ ai_stats/ aidb.py models.py urls.py views.py manage.py settings.py urls.py views.py I can't figure out why it won't load this particular module. I have a bunch of different applets in the one app and some work with this and others don't. If there is any other information needed please let me know. -
How to add "ON DELETE" rules to existing column in a PostgreSQL database table?
I'm using PostgreSQL in a Django project. Django does not support "on delete" rules at the database level. At the application level it allows this parameter when setting a ForeignKey for a model, but it's only used to emulate the behavior when deleting instances. I'm trying to run a data migration that deletes a set of rows from a table which is reference by another one. The models look something like this: class Album(models.Model): name = models.CharField(max_length=128) # ... class Track(models.Model): name = models.CharField(max_length=128) album = models.ForeignKey(Album, related_name='tracks', null=True, on_delete=models.SET_NULL) # ... I don't know if this behavior is supposed to be emulated in delete calls performed on querysets, or only model instances. For me neither is working. The cleanest solution in my mind would be to add a RunSQL that adds a "ON DELETE SET NULL" rule on the album foreign key at the database level. The problem is Django creates a foreign key constraint with a dynamic name, so if I drop that constraint by name and create another one, the migration may fail when I deploy. Isn't there a simple way to add the rule (or drop/create the constraint) by column name?