Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to import and display csv file in django project
I have two different project and one of them is a django project . I want to import the csv file and display it in html template . but since I'm a beginner I read a lot of articles and none of them helped me ? -
Deploy Django website to alias on ubuntu 18.04
I have a django application that I need to deploy. The hosting server runs on Ubuntu 18.04. My problem is that I don't have a dedicated domain, but I need to "append" the app to a domain already in use (i.e. I have www.mydomain.com that contains my not-django reseach group website, and I need my django app to be available at www.mydomain.com/new-content). Now my problem is how to write/modify the file on /etc/apache2/sites-available/. For a normal site I would do: Alias /face-perception /var/www/new-content/ <Directory /var/www/new-content> Order allow,deny Allow from all Options -Indexes </Directory> But online guides suggest me to have a structure like the following: <VirtualHost *:80> ServerAdmin webmaster@mydomain.com ServerName mydomain.com ServerAlias www.mydomain.com WSGIScriptAlias / var/www/mydomain.com/index.wsgi Alias /static/ /var/www/mydomain.com/static/ <Location "/static/"> Options -Indexes </Location > </VirtualHost > Is there any way I can achieve this? I tried combining the two in different ways but always ended up with being unable to restart apache or with a 404 error. Ps: for now I am not considering the option to use a dedicated domain as trough my institution it requires time and we need the app online as soon as possible to work remotely. -
Using Boot Strap To Insert New Rows In Comment Section (Python - Django)
I tried to use <div class="row">after looking at the Bootstrap material but the comments still appeared to be rendering in a series of columns and not rows. <article class="media content-section"> <!-- comments --> <h2>{{ comments.count }} Comments</h2> {% for comment in comments %} <div class="row"> <div class="media-body "> <a class="mr-2" href="#">{{ comment.name }}</a> <small class="text-muted">{{ comment.created_on|date:"F d, Y" }}</small> </div> <p class="article-content">{{ comment.body }}</p> </div> {% endfor %} -
How to make a video chat in DJango?
I want to make an app in django to make video calls with it. I have searched a lot, but I didn't find any good source or any example for it. Is there any api that we can use for making video calls? Or how we can do this simply? I read about webRTC and 0MQ but I didn't get the whole idea how I can do this? Thank you in advance. -
Django view isn't called while performing an AJAX call
I'm trying to setup an AJAX call in order to call a Django view, perform some calculations and then return the ouput into my html page. Unfortunately, the view doesn't seem to be reached. Not sure what is wrong but I have very limited AJAX experience. The idea is that when my slider sees a change in value, it triggers the AJAX call. The trigger seems to work as it displays my alert pop-up. But that's it, nothing else happens. Could you please help? Here is my html/AJAX code: <div class="slider-wrapper"> <span>Option 1 Imp. Vol.</span> <input class="toChange" id="rangeInput" name="rangeInput" type="range" value="{{Sigma}}" min="0" max="150" step="0.1" oninput="amount.value=rangeInput.value" /> <input class="toChange" id="amount" type="number" value="{{Sigma}}" min="0" max="150" step="0.1"oninput="rangeInput.value=amount.value" /> </div> <label>Ajax Test:</label> <span id="Atest"> <script type="text/javascript"> function inputChange () { var Sigma = document.getElementById("rangeInput").value; alert(); $.ajax({ url: '/finance/templates/optionstrategies/', type: 'POST', data: {'Sigma': Sigma, }, //dataType: "json", success: function(optionVal) { document.getElementById("Atest").innerHTML = optionVal; } }); } $(".toChange").change(inputChange); </script> And here is my view.py: def optionStrategies(request): errors='' if request.method == 'POST' and request.is_ajax(): print('ok') Type = request.POST.get('Type') V = request.POST.get('V') Q = request.POST.get('Q') S = request.POST.get('S') K = request.POST.get('K') r = request.POST.get('r') t = request.POST.get('t') Sigma = request.POST.get('rangeInput') BS = BlackScholes(Type = 'Vanilla', S = float(S), … -
Django redirect does nothing
I am currently try to redirect from one view to another view. However, nothing happens, the token gets printed and that's it. class SocialLoginInvUserAPIView(APIView): permission_classes = [AllowAny] @staticmethod def post(request): print(request.data["token"]) return redirect("login/") Here is the login url: url(r'login/$', LoginInvUserAPIView.as_view(), name='auth_user_login'), -
Django - Filtering Field In DeailView
Hi all, I've been building a Django app that allows users to stream and download music. However, there is one issue that I'm having with the artists profile pages; I'm trying to request the songs by the artist only in a DetailView as I'm treating it like a blog system. Is this possible in a DetailView? Or do I need to make a filter? I've been searching the web for days now and didn't really understand what I can do or how to get the specific data field from the model. Any help or guidance would be highly appreciated! class musicartist(DetailView): model = MusicArtist template_name = 'RS_MUSIC/artist.html' # override context data def get_context_data(self, *args, **kwargs): context = super(musicartist, self).get_context_data(*args, **kwargs) # add extra field current_band = MusicItems.objects.all().filter(artist=MusicArtist.title)[:1] context["songs"] = MusicItems.objects.filter(artist=MusicArtist.objects.all().filter(title=current_band)[:1]) return context -
Django form submission without reloading page
I have a django register form .On the event of an invalid form submission, page is reloading.I need to stay on that same page if the data entered is invalid. -
making dynamic template of the dictionary passed to the django
I'm working on coc api in which i want to display player information on the webpage and there are lot's of field in the response i want to display the result dynamically when any dictionary passed to the template it should arrange itself views.py: token = 'token' timeout = 1 api = CocApi(token, timeout) data = api.labels_clans() def index(request): data = api.players("#PJVVUCCJG") return render(request,"index.html", data) tried to print hierarchically: code: from cocapi import CocApi def getall(dictn, lvl=0): sep = " " for key, item in dictn.items(): if isinstance(item, list): print(lvl * sep + key + ":") for it in item: getall(it, lvl=lvl+1) print("") continue if isinstance(item, dict): print(lvl * sep + key + ":") getall(item, lvl=lvl + 1) continue print(lvl * sep + str(key) + ":" + str(item)) token = 'token' timeout = 1 api = CocApi(token, timeout) data = api.players("#PJVVUCCJG") getall(dict(data)) print(len(data)) print(data) Output: tag:#2U2RCLYLL name:killer townHallLevel:10 expLevel:115 trophies:1165 bestTrophies:2826 warStars:178 attackWins:72 defenseWins:10 builderHallLevel:7 versusTrophies:2422 bestVersusTrophies:2444 versusBattleWins:509 role:coLeader donations:70 donationsReceived:953 clan: tag:#LLQ0CULQ name:Thê BèäTlës clanLevel:11 badgeUrls: small:https://api-assets.clashofclans.com/badges/70/exHkY8LEWfWyugWdyfVDCvns2J7TgIoUgurt6DUFg4Q.png large:https://api-assets.clashofclans.com/badges/512/exHkY8LEWfWyugWdyfVDCvns2J7TgIoUgurt6DUFg4Q.png medium:https://api-assets.clashofclans.com/badges/200/exHkY8LEWfWyugWdyfVDCvns2J7TgIoUgurt6DUFg4Q.png league: id:29000006 name:Silver League I iconUrls: small:https://api-assets.clashofclans.com/leagues/72/nvrBLvCK10elRHmD1g9w5UU1flDRMhYAojMB2UbYfPs.png tiny:https://api-assets.clashofclans.com/leagues/36/nvrBLvCK10elRHmD1g9w5UU1flDRMhYAojMB2UbYfPs.png medium:https://api-assets.clashofclans.com/leagues/288/nvrBLvCK10elRHmD1g9w5UU1flDRMhYAojMB2UbYfPs.png achievements: name:Bigger Coffers stars:3 value:11 target:10 info:Upgrade a Gold Storage to level 10 completionInfo:Highest Gold Storage level: 11 village:home name:Get those … -
After comand ACTIVATE django activates but shows only half name of the folder
My Django project is in folder Django-projects. When I activate it the folder name becomes in round bracket, but only in one in the begining please look at printscrin. enter image description here -
Django channels function gets stuck
I created a simple Consumer in Django channels that receives some JSON data from an external source and whenever it receives the data, the consumer will broadcast it to some groups. Here is my code: def websocket_receive(self, event): data = event['text'] print(data) def broadcast_data(event): channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)( 'MYGROUP', { "type": 'TEST', "content": event['text'], }) broadcast_data(event) print('received') The problem with this code is that, for some reason, after receiving the first record it will freeze and do nothing, sometimes it will print the first two. It's very weird because this same code worked until some days ago; also, none of these is a blocking operation (receive the data, print it and broadcast it), there are no connections pending or nothing else. If i remove broadcast_data(event), the code will work and it will keep printing every record every time a new one arrives, so i'm thinking that the problem is inside broadcast_data. Can anyone help me find what is happening here? -
How do I get a value from a database of an element that is linked to another one with foreign key?
I have these models that are linked with a foreign key class Student(models.Model): id_student = models.AutoField(primary_key=True) first_name = models.CharField(max_length=45) last_name = models.CharField(max_length=45) date_of_birth = models.DateField() nationality = models.CharField(max_length=45) gender = models.CharField(max_length=1) street_name = models.CharField(max_length=45) street_number = models.CharField(max_length=45) postal_code = models.CharField(max_length=45) city = models.CharField(max_length=45) phone = models.CharField(max_length=45) email = models.CharField(max_length=45) study_id_study = models.ForeignKey('Study', models.DO_NOTHING, db_column='study_id_study') start_year = models.CharField(max_length=45) teacher_id_teacher = models.ForeignKey('Teacher', models.DO_NOTHING, db_column='teacher_id_teacher', related_name = 'tcr_id') class Meta: managed = False db_table = 'Student' class Teacher(models.Model): id_teacher = models.AutoField(primary_key=True) first_name = models.CharField(max_length=45, blank=True, null=True) last_name = models.CharField(max_length=45, blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) nationality = models.CharField(max_length=45, blank=True, null=True) street_name = models.CharField(max_length=45, blank=True, null=True) street_number = models.CharField(max_length=45, blank=True, null=True) postal_code = models.CharField(max_length=45, blank=True, null=True) city = models.CharField(max_length=45, blank=True, null=True) phone = models.CharField(max_length=45, blank=True, null=True) gender = models.CharField(max_length=1, blank=True, null=True) salary = models.CharField(max_length=45, blank=True, null=True) study_counselor = models.CharField(max_length=45, blank=True, null=True) picture_url = models.CharField(max_length=45, blank=True, null=True) class Meta: managed = True db_table = 'Teacher' I wanted to get the name of the teacher depending on teacher_id_teacher that we have in Student model, and which is foreign key as well seems easy but I have been trying to do this for two days with no success, Thanks you so much :) -
Django REST framework Ajax call only works on the first call
The tutorial I am following has this code which works when the page is first loaded, and then it does not. I have read all other questions on "ajax call works the first time only", but could not find a relevant cause. Given that the code works when the page loads, I think there is a binding problem in the jQuery portion that prevents the button to act once it is changed on the first call, but I cannot pinpoint what that is. I also tried visiting the url end-point (REST framework end-point) and every time I refresh the page, the count does update correctly. So, the problem must be somewhere in the front-end since it can clearly find the URL and update the count once but fails to call ajax on subsequent clicks. <li> <a class="like-btn" data-href="{{ obj.get_api_like_url }}" data-likes='{{obj.likes.count}}' href="{{ obj.get_api_like_url }}"> {{obj.likes.count }} | {% for person in obj.likes.all %} {{ person.userprofile.first_name }} {% endfor %}<i class="fab fa-gratipay"></i> </a> </li> In my jQuery code: $(function(){ $(".like-btn").click(function(e) { e.preventDefault(); var this_ = $(this); var likeUrl = this_.attr("data-href"); console.log("likeUrl: ", likeUrl); var likeCount = parseInt(this_.attr("data-likes")) | 0 ; var addLike = likeCount; var removeLike = likeCount; if (likeUrl) { … -
Django rest framework handle duplicates
I am building an app where I use django as backend and react native as front end. Right now I am building a login component which provides Facebook and Google login and the data returned from their API's is stored in my local database trough DRF. The problem is that when a user signs out and log in again DRF creates another record with exactly the same info. Now, the question is should I handle this in the backend (and if yes how) or in the front end (here I know how, but I think its not a good idea) Here are my django model, view and serializer: class RegisteredUsers(models.Model): userId = models.CharField(max_length=256) user_name = models.CharField(max_length=256) user_mail = models.CharField(max_length=256) photo = models.CharField(max_length=256) def __str__(self): return self.user_name class RegisteredUsersViewSet(viewsets.ModelViewSet): queryset = RegisteredUsers.objects.all() serializer_class = RegisteredUsersSerializer def get_queryset(self): mail = self.request.query_params.get('user_mail', None) if mail: qs = RegisteredUsers.objects.all().filter(user_mail=mail) else: qs = super().get_queryset() return qs class RegisteredUsersSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = RegisteredUsers fields = ('userId', 'user_name', 'user_mail', 'photo') lookup_field='user_mail' extra_kwargs = { 'url': {'lookup_field': 'user_mail'} } how can I validate that this account already exists and just log in the user? -
How to enforce using a char(n) datatype instead of nvarchar in Django queries with django-mssql-backend
I am using, python 3.7, django 2.2 and django-mssql-backend with a legacy Microsoft SQL Server 2012 database. I have generated a model using inspectdb. The model has a field called “ord_no” which is a CHAR(8) datatype in the database. Django correctly creates it as a CharField(max_length=8). Note – There is an index for this table on the ord_no column. Here is the simplified table definition: CREATE TABLE [dbo].[imordbld_sql]( [ord_no] [char](8) NOT NULL, [item_no] [char](30) NOT NULL, [qty] [decimal](13, 4) NULL, [qty_per] [decimal](15, 6) NULL, [ID] [numeric](9, 0) IDENTITY(1,1) NOT NULL ) ON [PRIMARY] GO Here is my models.py with a simplified version of the model in question with fields auto-generated through inspectdb I've also created a custom model manager that converts the ord_no parameter into a CHAR(8) field for demonstration purposes. models.py from django.db import models class OrderBuildManager(models.Manager): """ Django automatically use nvarchar(16) instead of char(8) when using the ORM to filter by work order. This method casts the ord_no parameter to a char(8) so SQL can use an index on the ord_no column more efficiently (index seek vs index scan) """ def get_order(self, ord_no): qs = super(OrderBuildManager, self).get_queryset().extra( where=('ord_no = CAST(%s as CHAR(8))',), params=(ord_no,)) return qs class OrderBuild(models.Model): ord_no … -
'MultiValueDict' object has no attribute 'name'
I am using jQuery - Filer.js for file upload, when I upload any file it returns Error like "'MultiValueDict' object has no attribute 'name'" settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') fileupload.html <div class="card-block"> {% csrf_token %} <input type="file" name="files[]" id="filer_input1"> </div> views.py from django.shortcuts import render,redirect from django.http import HttpResponse, HttpResponseRedirect from django.core.files.storage import FileSystemStorage def StorePartyMappingIndex(request): return render(request,'storepartymapping.html') def StorePartyMappingfileupload(request): if (request.method == 'POST'): file = request.FILES fs = FileSystemStorage() fs.save(file.name,file) # Error line return HttpResponseRedirect('/mapping/fileupload') else: return render(request,'fileupload.html') jquery: $(document).ready(function(){ 'use-strict'; $("#filer_input1").filer({ limit: 2, maxSize: 3, extensions: ['csv', 'xlsx', 'xls'], changeInput: '<div class="jFiler-input-dragDrop"><div class="jFiler-input-inner"><div class="jFiler-input-icon"><i class="icon-jfi-cloud-up-o"></i></div><div class="jFiler-input-text"><h3>Drag & Drop files here</h3> <span style="display:inline-block; margin: 15px 0">or</span></div><a class="jFiler-input-choose-btn btn btn-primary waves-effect waves-light">Browse Files</a></div></div>', showThumbs: true, theme: "dragdropbox", templates: { box: '<ul class="jFiler-items-list jFiler-items-grid"></ul>', item: '<li class="jFiler-item">\ <div class="jFiler-item-container">\ <div class="jFiler-item-inner">\ <div class="jFiler-item-thumb">\ <div class="jFiler-item-status"></div>\ <div class="jFiler-item-info">\ <span class="jFiler-item-title"><b title="{{fi-name}}">{{fi-name | limitTo: 25}}</b></span>\ <span class="jFiler-item-others">{{fi-size2}}</span>\ </div>\ {{fi-image}}\ </div>\ <div class="jFiler-item-assets jFiler-row">\ <ul class="list-inline pull-left">\ <li>{{fi-progressBar}}</li>\ </ul>\ <ul class="list-inline pull-right">\ <li><a class="icon-jfi-trash jFiler-item-trash-action"></a></li>\ </ul>\ </div>\ </div>\ </div>\ </li>', itemAppend: '<li class="jFiler-item">\ <div class="jFiler-item-container">\ <div class="jFiler-item-inner">\ <div class="jFiler-item-thumb">\ <div class="jFiler-item-status"></div>\ <div class="jFiler-item-info">\ <span class="jFiler-item-title"><b title="{{fi-name}}">{{fi-name | limitTo: 25}}</b></span>\ <span class="jFiler-item-others">{{fi-size2}}</span>\ </div>\ {{fi-image}}\ </div>\ <div class="jFiler-item-assets jFiler-row">\ <ul class="list-inline pull-left">\ <li><span … -
Django load html snippet template from js on input change
I have a Django template that loads a list of objects, for each of the object I load a template. Here are the HTMLs client-home.html: {% extends 'base.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-md-2"> <div class="col"> <label for="city">City</label> <input name="city" type="text" class="form-control" id="city" value="{{ app_user.city }}"> </div> <div class="col mb-3"> <label for="category">Category</label> <select name="category" class="custom-select" id="category"> <option value="" selected>All</option> {% for category in categories %} <option value="{{ category.0 }}">{{ category.1 }}</option> {% endfor %} </select> </div> </div> <div class="col-md-10"> <ul class="list-group list-group-horizontal" id="offers-list"> {% for o in city_offers %} {% include "offer-snippet.html" with offer=o %} {% endfor %} </ul> </div> </div> {% endblock %} offer-snippet.html: <div class="row offer-box m-2"> <div class="col-5 p-0"> <img src="{{ o.owner.image.url }}" width="120" height="120" class="img-grey-bg"> </div> <div class="col-7"> {{ o.owner.name }} {{ o.city }}, {{ o.delivery_date }} <span class="badge badge-primary badge-pill">{{ o.current_subscribers }} / {{ o.min_subscribers }}</span> </div> </div> Here's the model.py: class BusinessOffer(models.Model): owner = models.ForeignKey(AppUser, related_name='offers', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) city = models.CharField("City", max_length=50, ) delivery_date = models.DateField() min_subscribers = models.IntegerField() subscribers = models.ManyToManyField(AppUser, related_name='offers_subscribed_to') @property def current_subscribers(self): return len(self.subscribers.all()) As you can see, in the client-home.html there are 2 input fields. I would like to update … -
Images disappers while converting html to pdf with weasyprint
I am working on a django project, Sending data to html template which also contains a logo at the top, which is present in static folder and using template tagging to load it from static folder, when coverting that html template to pdf with weasyprint (using render_to_string) then i cant see the logo instead alternate text appears.I am deploying that project through docker so kindly can anyone solve my issue on both local machine and server. -
unable to solve : TypeError: expected str, bytes or os.PathLike object, not NoneType
(venv) C:\Users\user\Desktop\PJ\DiscussionForum\src>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "E:\PythonProjects\venv\lib\site-packages\django\core\management__init__.py", line 350, in execute_from_command_line utility.execute() File "E:\PythonProjects\venv\lib\site-packages\django\core\management__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\PythonProjects\venv\lib\site-packages\django\core\management\base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "E:\PythonProjects\venv\lib\site-packages\django\core\management\base.py", line 399, in execute output = self.handle(*args, **options) File "E:\PythonProjects\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 65, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "E:\PythonProjects\venv\lib\site-packages\django\db\migrations\loader.py", line 49, in init self.build_graph() File "E:\PythonProjects\venv\lib\site-packages\django\db\migrations\loader.py", line 170, in build_graph self.load_disk() File "E:\PythonProjects\venv\lib\site-packages\django\db\migrations\loader.py", line 95, in load_disk directory = os.path.dirname(module.file) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\ntpath.py", line 215, in dirname return split(p)[0] File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\ntpath.py", line 177, in split p = os.fspath(p) TypeError: expected str, bytes or os.PathLike object, not NoneType -
Django-Heroku Deployment Procfile
I've created a basic Django app and I wanted to deploy it with Heroku. I have followed all the instructions given on Heroku but there was one error I made which was naming the file "procfile" instead of "Procfile". Now the website has been deployed but it only opens up to an application error. Upon checking the log, I have found the error code to be H14. I have since renamed the "procfile" to "Procfile" but the change doesnt seem to be integrated. How do I fix this? -
Cannot get model in Cron job Django
I'm working on Django Project in Which I have created an cron_job which does some work, but the problem I'm facing is I can't fetch my model in cron job function , I have never faced such issue before , Cron job function: def cron_job(): print("Function Executed") obj = Mymodel.objects.all() print("all objects ",obj) how I add cron job: python manage.py crontab add my cronjob executes but it only prints following in log file: Function Executed all objects #it should print all objects here and my models has data in it ,so it should work , I'm using workon virtualenv and python2.7 please help I don't know what to do, thanks in advance -
django: Issue with testing a view possibly caused by django-concurrency
I'm trying to create a test for an update view. I'm using django-concurrency and this specific view uses django-bootstrap-modal-forms. login = self.client.login(username='testuser', password='123456') #fails here response = self.client.post( reverse('edit_batch', kwargs={'pk': self.batch.id}), {'project': self.project.project_id, 'container': self.container.id, 'comment': 'Updated'}) self.assertEqual(response.status_code, 302) There exists a one-to-many between Container-Batch. So container is the parent of batch. The container itself also has several required related fields which need to be generated in setUp of the test. The issue I'm facing is that an exception is thrown from django concurrency when calling client.post: raise RecordModifiedError(_('Record has been modified'), target=target) concurrency.exceptions.RecordModifiedError: Record has been modified I've no idea why this is happening. Wasted hours now on this. Notably this works perfectly fine in the application itself. I can update correctly with no probelm. Only in test framework it fails. really puzzling. With debugging I can see that django.concurrency tells me that target has version 0 and saved one has version 1. Any idea what is causing this behavior? -
In django-cms Why preview button of page not able to load web page?
I have started to learn django-cms recently and got one project from one of my friends. I have created two pages in django-cms. When I click on preview(eye-icon) from pages, my second page preview does not show & instead showing below error. Page not found (404) Request Method: GET Request URL: http://localhost:8000/event-page/?edit&language=en Raised by: aldryn_newsblog.views.ArticleDetail No News / Blog Article found matching the query, tried languages: en You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I tried to find solution online but not able to find any. It will be great help if someone can suggest me solution. -
Some parts of Bootstrap 4 doesn't work with Django when served from static folder
I'm using Django with Bootstrap 4 without CDN. I'm using django_compressor and django-libsass for SASS and modify & extend with a separate sass file by importing the main bootstrap file. Most of the Bootstrap works but some don't. So far I discovered stretched-link and shadow don't work (I already enabled shadows in my sass). If I stop serving Bootstrap from static folder and use CDN instead, everything works fine. Does anyone know why this is happening? -
Converting a model to its base model
Consider this file : from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) Now, let's say that I have a Restaurant, named restaurant. But this place is no longer a restaurant, so I want to transform it to a Place. For that, I do : p = Place.objects.get(pk=place_id) p.restaurant.delete() p.save() It works well, p is no longer a restaurant, but something strange happens : The primary key (ID) of p in the Place table change, like if the Place was deleted and then recreated. Why is this happening ? And how can I transform my restaurant to a place without changing the place ID ?