Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run django-pytest on a project which imports settings from environment variables defined in manage.py
I'm working on a Django project in which settings such as SECRET_KEY are defined in a .env file, and manage.py sets the environment variable using python-dotenv as follows: from dotenv import load_dotenv, find_dotenv if __name__ == "__main__": load_dotenv(find_dotenv()) # usual manage.py code Then settings.py simply defines module-level settings from environment variables, for example, SECRET_KEY = os.environ['SECRET_KEY'] I'm now in the process of switching to pytest-django for unit testing. The problem, however, is that without running python manage.py first, the environment variables don't get set, so I end up with E KeyError: 'SECRET_KEY' The way I'm now thinking of working around this is to define a custom action to register with manage.py to run pytest (following https://docs.djangoproject.com/en/2.0/howto/custom-management-commands/). This seems a bit like using a sledgehammer to crack a nut, though. Any suggestions of more elegant ways to go about this problem? -
include() got an unexpected keyword argument 'app_name'
i am making a blog application for my website with django-2.0 when i run server i see the following error File "C:\Users\User\Desktop\djite\djite\djite\urls.py", line 7, in <module> url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), TypeError: include() got an unexpected keyword argument 'app_name' here is my main urls.py from django.contrib import admin from django.conf.urls import url,include urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), ] and here's my blog/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>d{2})/(?P<post> [-/w]+)/$', views.post_detail, name='post_detail'), ] my views.py: from django.shortcuts import render, HttpResponse, get_object_or_404 from blog.models import Post def post_list(request): #list posts=Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post =get_object_or_404(post, slog=post, status='published', publush__year=year, publish__month=month, publish__day=day) return render (request, 'blog/post/detail.html', {'post':post}) models.py: # -*- coding:utf-8 -*- from django.db import models from django.conf import settings from django.utils import timezone from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from django.urls import reverse class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=255,verbose_name=_('title'),help_text=_('add title')) content = models.TextField(verbose_name=_('content'),help_text=_('write here')) publish = models.DateTimeField(default=timezone.now) createtime = models.DateTimeField(_('create time'),auto_now_add=True, auto_now=False,help_text=_('create time')) updatetime = models.DateTimeField(_('update time'),auto_now_add=False, auto_now=True,help_text=_('update time')) author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('author'), on_delete=models.DO_NOTHING,help_text=_('choose author')) … -
Django request.GET Recieves Dict of Arrays
I am using Django's Restful Api 'APIView'. When I do a request.GET I get the following: {'param_A': ['things_A'], 'param_B': ['things_B']} However, I was wondering if there was a way to get the parameters not in form of an array so like this: {'param_A': 'things_A', 'param_B': 'things_B'} -
How to limit the selectable date range on UI for Crispy Form - forms.DateField?
In my form declaration, I have this field: effective_date = forms.DateField(required=False, label='Effective Date', widget=forms.TextInput(attrs={'class': 'datepicker'})) I want to limit the selectable date range on the datepicker to be [today - 30, today]. Is there a way to do it in Django crispy form? I'm using Django 1.9 with crispy form. FYI I tried the SelectDateWidget but it is not the UI I want. I'm looking for a component which can render this UI and support date range restriction: -
Django get unique manytomany
class Word(Model): word = CharField() categories = ManyToManyField('Category') class Category(Model): name = CharField() What is the best way to fetch all unique list of categories? For example, if I have apple -> General, Garden pear -> General, Garden computer -> IT I want to get the following list of lists (General, Garden) (IT, ) -
Why and how do params in annotate affect each other?
I've been reading https://docs.djangoproject.com/en/1.11/topics/db/aggregation/ a lot, but I'm still missing something. Using Django 1.11, say I have the following models: class School(models.Model): pass class Classroom(models.Model): school = models.ForeignKey(School, on_delete=models.PROTECT) active = models.BooleanField() busy = models.BooleanField() class Chalkboard(models.Model): classroom = models.ForeignKey(Classroom, on_delete=models.PROTECT) class Whiteboard(models.Model): classroom = models.ForeignKey(Classroom, on_delete=models.PROTECT) And I create a school, with a classroom, which has 2 whiteboards and 2 chalkboards: s = School() s.save() c = Classroom(school=s, active=True, busy=False) c.save() Chalkboard(classroom=c).save() Chalkboard(classroom=c).save() Whiteboard(classroom=c).save() Whiteboard(classroom=c).save() Whiteboard(classroom=c).save() I want a summary of how many chalkboards there are at each school that is active but not busy. q = School.objects.filter( Q(classroom__active=True) & Q(classroom__busy=False) ).annotate( chalkboard_count=Count('classroom__chalkboard'), ) q[0].chalkboard_count 2 # as expected Now I want to know about chalkboards and whiteboards. q = School.objects.filter( Q(classroom__active=True) & Q(classroom__busy=False) ).annotate( chalkboard_count=Count('classroom__chalkboard'), whiteboard_count=Count('classroom__whiteboard'), # added this line ) q[0].chalkboard_count 6 # expected 2 q[0].whiteboard_count 6 # expected 3 If I chain the calls to annotate, I get the same result. q = School.objects.filter( Q(classroom__active=True) & Q(classroom__busy=False) ).annotate( chalkboard_count=Count('classroom__chalkboard') ).annotate( whiteboard_count=Count('classroom__whiteboard') ) q[0].chalkboard_count 6 # expected 2 q[0].whiteboard_count 6 # expected 3 All the while, the counts are what I expect Chalkboard.objects.count() 2 Whiteboard.objects.count() 3 What am I doing wrong here? -
Showing child properties on main database object in Django admin site
i am asking a similar question to this here but the solutions presented in that question did not make sense my situation. Basically i have 3 different models set up. One for portfolio which holds a number of transactions, one for coins which is just a model holding some info on a coin and a transaction model which holds info on a purchase of a coin and is tied to a portfolio: models.py from django.db import models class Portfolio(models.Model): name = models.CharField(max_length=250) @property def coins(self): return Transaction.objects.filter(portfolio=self) def __str__(self): return self.name class Coin(models.Model): name = models.CharField(max_length=100) symbol = models.CharField(max_length=5) price = models.DecimalField(max_digits=20, decimal_places=9) info = models.TextField() website = models.TextField() rank = models.IntegerField() def __str__(self): return self.name + " - " + self.symbol class Transaction(models.Model): portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE) coin = models.ForeignKey(Coin, on_delete=models.PROTECT) purchaseDate = models.DateTimeField() soldDate = models.DateTimeField(default=None, null=True, blank=True) amount = models.DecimalField(max_digits=20, decimal_places=3) price = models.DecimalField(max_digits=20, decimal_places=9) Now my problem is I want to see a list of transactions when I click on a portfolio however currently all I see is this: without the coins property showing up and inside it its transactions. I also can see the individual coin and transaction objects but that aren't all tied together … -
How do you save a single space (" ") in a field in a django Model?
My model definition looks like this: class MyModel(models.Model): tag_separator = models.CharField(max_length=1, null=True, blank=True) The tag_separator is a single character, and it can be a single space: " ". I need to select null=True in order to get it to work, but when I POST data through my REST API, it saves the tag_separator as an empty string: "tag_separator": "". Is there a simple way to stop django from assuming that my single space string is an empty string? I am using: Django==1.11 and djangorestframework==3.7.7 -
Django 1.10 media (FileField) 404
My first question ever, so go easy. I'll give as much detail as possible. My setup django 1.10 (I know, I need to upgrade) python 3.5.[something] postgres DB gunicorn nginx The problem and what I've tried The problem is that I pulled a recent commit that was working fine locally and suddenly none of a model's images, which previously rendered fine, are working - I'm getting 404s for all of them. I've tried the following: Checking out previous commits Restarting gunicorn (sudo systemctl restart gunicorn) Restarting nginx Restarting postgresql Using python manage.py shell to access objects and check that they're still associating with a URL to the file My code works when run locally - none of the uploaded images/files are causing 404s. As with my production environment, the logos folder sits in the main directory of my project, rather than being appended to a media folder (which other answers and the django docs suggested would be the case - this could be a red herring though). My browser console shows the 404s and that it's trying to fetch from <domain.com>/media/logos/<filename>, even though they're stored (I've checked the file structure) in <project_folder>/logos/<filename> (i.e. without the media folder), but this was … -
what is the documentation to make a excellent regex in django?
i need do match path to validate my email in django: path() path('validate_email/<slug:username>/(?P<email>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/<slug:token>', views.validate_email, name="validate_email") I want to catch the username, email and generate a token to validate a email step by step from django 2.0.1. -
Django: path doesn't find the right primary key in url path
I'm using django2 and I get an error when I access this url: http://127.0.0.1:8000/hotes/12/access/7/update I get an error 404 "None access object was found" To make a long story short: I want to update an object linked to another. To do so, I have to send through the link, both primary keys (12 and 7 in the url). Also, I use the generic view "UpdateView" given by Django. This is the path concerned in my project.urls: urlpatterns = [ path('hotes/<int:pk>/access/<int:access_pk>/update',views.AccessUpdateView.as_view(), name='access_update'), ] I want the second primary key to be used in my view "AccessUpdateView". This is a part of my models.py: class Host(models.Model): name = models.CharField(max_length=30, unique=True) usage = models.CharField(max_length=30, blank=True) function = models.CharField(max_length=30, blank=True) production = models.NullBooleanField(blank=True, null=True) place = models.CharField(max_length=30, blank=True) type = models.CharField(max_length=30, blank=True) processor = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) storage = models.CharField(max_length=10, blank=True) memory = models.CharField(max_length=10, blank=True) dns_inner = models.CharField(max_length=50, blank=True) dns_extern = models.CharField(max_length=50, blank=True) os = models.ForeignKey(Os, null=True, related_name='hosts', on_delete=models.SET_NULL, blank=True) class Access(models.Model): service = models.CharField(max_length=20) client_access = models.NullBooleanField(blank=True, null=True) ip = models.GenericIPAddressField() login = models.CharField(max_length=30, blank=True) password = models.CharField(max_length=50, blank=True) host = models.ForeignKey(Host, related_name='access', on_delete=models.CASCADE) As you can see on host can have multiple access but an access in linked to only one … -
Django admin, ManyToManyField -> ForeignKey relation
Suppose I have these models (with some properties omitted obviously): class Product(Model): name = CharField(max_length=100) class Variety(Model): product = ForeignKey(Product) class ProductMerge(Model): parent_product = ForeignKey(Product) products = ManyToManyField(Product, related_name='merge_proposals') How can I show all the Varieties of all Products of a ProductMerge on an inline inside of the admin panel? I've tried settings a custom get_queryset on a TabularInline: def get_queryset(self, request): return Variety.objects.filter( product__in=self.instance.parent.child_products.all()) But I get the following exception: ValueError: 'marketplace.Variety' has no ForeignKey to 'marketplace.ProductMergeProposal'. -
nginx doesn't serve static files
I've configured a conda virtual environment for Python 3.6 under OS X and installed everything necessary to test the deployment: Nginx, django, gunicorn, celery. My app runs perfectly well on a Django test server, so I've tried serving it via Nginx. The site works (all pages open and submissions carry on), but Nginx serves no static files. Here are the relevant lines from my project's setting.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) with open(os.path.join(BASE_DIR, 'config.json')) as conf: CONFIGS = json.loads(conf.read()) ALLOWED_HOSTS = ['localhost'] DEBUG = CONFIGS["DEBUG"] STATIC_URL = '/static/' STATIC_ROOT = CONFIGS['STATIC_ROOT'] STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] Now config.json (I removed irrelevant lines): { "DEBUG": false, "STATIC_ROOT": "/Users/user/static/" } Here is how the files are referenced in the base of my templates: {% load static %} <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title></title> <!-- Bootstrap Core CSS --> <link href="{% static 'css/bootstrap.css' %}" rel="stylesheet"> <!-- Style customisation --> <link href="{% static 'css/custom.css' %}" rel="stylesheet"> <!-- jQuery --> <script src="{% static 'js/jquery.js' %}"></script> <!-- Bootstrap Core JavaScript --> <script src="{% static 'js/bootstrap.bundle.js' %}"></script> </head> I've added the include sites-enabled/*.conf; line to the <conda_env_dir>/etc/nginx/nginx.conf: ... include conf.d/*.conf; include sites-enabled/*.conf; } (END) as it was … -
Django app. ModuleNotFoundError when running server
Here is a problem with my code urls.py : from django.conf.urls import url from django.contrib import admin from django.conf.urls import include from rango import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^rango/', include('rango.urls')), # above maps any URLs starting # with rango/ to be handled by # the rango application url(r'^admin/', admin.site.urls), views.py : from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Rango says hello to you!") list of apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rango', ] and structure of project: ├───.idea └───tango_with_django ├───rango │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ └───tango_with_django └───__pycache__ When I try to run server this error appears ModuleNotFoundError: No module named 'rango.urls'.What could be wrong there.I'm using PyCharm editor. -
Python, Django can't run my server
I try create RESTful API with Django. Can you help me with this problem i don't know why i have this error. I did migration so i used python manage.py makemigrations and python manage.py migrate and I created superuser python manage.py createsuperuser If do you need it more code, answer. Thanks Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x05F4C9C0> Traceback (most recent call last): File "D:\python\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "D:\python\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "D:\python\lib\site-packages\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "D:\python\lib\site-packages\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "D:\python\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "D:\python\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "D:\python\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "D:\python\lib\site-packages\django\utils\functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "D:\python\lib\site-packages\django\urls\resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "D:\python\lib\site-packages\django\utils\functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "D:\python\lib\site-packages\django\urls\resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "D:\python\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", … -
Update User Model Without Entering Password
I am trying to create a page where users can edit their first_name, last_name or email that is stored in the User model. However whenever try to do so, the page refreshes and asks for the password. Is there anyway to make these changes without entering the password. This is what my original UserFrom looks like (this is what users fill out when they register): class UserForm(forms.ModelForm): email = forms.EmailField(required=True) password = forms.CharField(widget=forms.PasswordInput()) confirm_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password') # Make sure passwords match: def clean(self): cleaned_data = super(UserForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError("Password do not match") And here is the form users can use to edit the User model once signed up: class EditUserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email') exclude = ('password',) and the correlating views.py: if request.method == 'POST': user_form = UserForm(data=request.POST, instance=request.user) user_form.fields['username'].widget.attrs['readonly'] = True if user_form.is_valid(): user_form.save() return HttpResponseRedirect('/account-settings/') else: user_form = EditUserForm(instance=request.user) user_form.fields['username'].widget.attrs['readonly'] = True context_dict['user_form'] = user_form Any idea on how I can have users edit the User model without entering a password? -
MultiValueDictKeyError on sending data using AJAX to Django 2
I'm trying to send this ajax request to python (with django framework): $.ajax({ url: '/search/', type: 'post', data: { mname: mname, fname: fname }, success: function (data) { console.log("result from python: " + data.result); } }); The view from django views.py: def my_search(request): before sending here if request.method == 'POST': mname = request.POST['mname'] fname = request.POST['fname'] But after sending data I'm getting: Exception Type: MultiValueDictKeyError Exception Value: 'mname' I followed this answer and changed codes like this: Ajax data part: data: { json_data: JSON.stringify({ info: {'mname':mname,'fname': fname} }) }, views.py: data_string = request.POST.get('json_data') data_dict = json.loads(data_string) mname = data_dict['info']['mname'] fname = data_dict['info']['fname'] But now I get: Exception Type: TypeError Exception Value: the JSON object must be str, not 'NoneType' This obviously somehow related to the first try error which means data sent from ajax is not received by python. How can I solve this issue? -
Django seems to truncate strings in a long text field
I have a MySQL longtext field, that corresponds to the following field in a Django model: class MyModel(models.Model): # some other fields my_long_text_field = models.TextField(blank=True, null=True) The problem is that Django seems to truncate my string when I am trying to save data to database. I have come across a question where they say that models.TextField corresponds to MySQL longtext. Then why does this data truncating happening ? What I am doing wrong ? -
Match a multi-level URL in Django
I am trying to set up my urls.py file so that it can process the following url: http://localhost:8000/project/path/level1/level2/level3 The desired outcome is to go to path view and pass a parameter containing the entire highlighted path ("level1/level2/level3"). I have tried urlpatterns = [ url(r'^path(/(?P<url_path>[-\w]+)?){0,8}$', views.path, name='index') ]; However this only works for 1 level, i.e. http://localhost:8000/project/path/level1 will work http://localhost:8000/project/path/level1/level2 won't work -
Optimize count query in Django
I have the following queries: files = DataAvailability.objects.all() type1 = files.filter(type1=True) type2 = files.filter(type2=True) # People information people = Person.objects.all() users = people.filter(is_subject=True) # count information (this is taking a long time to query them all) type1_users = type1.filter(person__in=users).count() type2_users = type2.filter(person__in=users).count() total_users = files.filter(person__in=users).count() # another way total_users2 = files.filter(person__in=users) type1_users2 = total_users.filter(type1=True).count() type2_users2 = total_users.filter(type2=True).count() total_count = total_users2.count() I thought about creating a query with .values() and putting into a set(). After that is done execute some functions within the set (like diff). Is this the only way to improve the query time? -
Sending Push Notifications using Firebase and Django
I have a Django application configured to send push notifications using Firebase. I am able to send notifications from the development server (http) but when I deploy my application and access it using 'https' I am not able to receive notifications sent from within my app. I am implementing the FCM library for Django. Here is code used to send the notification: def send(self, data, registration_ids=None, **kwargs): if not isinstance(data, dict): data = {'msg': data} registration_ids = registration_ids or [] if len(registration_ids) > self.max_recipients: ret = [] for chunk in self._chunks( registration_ids, settings.FCM_MAX_RECIPIENTS): ret.append(self.send(data, registration_ids=chunk, **kwargs)) return ret values = { 'data': data, 'collapse_key': 'message'} if registration_ids: values.update({'registration_ids': registration_ids}) values.update(kwargs) values = json.dumps(values) headers = { 'UserAgent': "FCM-Server", 'Content-Type': 'application/json', 'Authorization': 'key=' + self.api_key} response = requests.post( url="https://fcm.googleapis.com/fcm/send", data=values, headers=headers) response.raise_for_status() return registration_ids, json.loads(force_text(response.content)) Messages are received by Javascript on the frontend: <script type="text/javascript"> $(document).ready(function () { requestPermission(); }); const messaging = firebase.messaging(); const tokenDivId = 'token_div'; var sendTokenInProcess = false; messaging.onTokenRefresh(function () { messaging.getToken() .then(function (refreshedToken) { console.log('Token refreshed.'); setTokenSentToServer(false); sendTokenToServer(refreshedToken); resetUI(); }) .catch(function (err) { console.log('Unable to retrieve refreshed token ', err); showToken('Unable to retrieve refreshed token ', err); }); }); messaging.onMessage(function (payload) { console.log("Message received. ", payload); … -
How do you "skip" the Django Middleware when using the requests library or urllib3?
I have a Django REST Framework and I am trying to pull json data from it to be used for the different projects I have in my Django application. I have middleware that hijacks urls with HttpRequest.urlconf = 'app.urls' so I don't have to use my base urls.py. Whenever I try to use requests.get("url"), my middleware picks it up and tries to redirect my original path to the api page instead of pulling the json data. Is there a way I can tell my custom Middleware to not run or is there a completely better way to do this? -
Why can't I use, user input in jinja if statement ? (I am new to django)
I want to display database item by using for loop if they match the user input through form. I want to stay on the same page after submitting the input. Basically what I am doing here is matching if the city name entered matches my database city. inc.html <form method = "get" action = ""> City: <input type= "text" name = "q" value = "{{ query}}" /> <input type = "submit" value = "search" /> </form> <h2>Inc</h2> {%for inc in incubators%} {%if query == {{inc.city_location}}%} #inc.city_location is in my database <ul> <li><p>{{inc.inc_name}} <br> {{inc.city_location}}<p></li> </ul> <hr> {%endif%} {%endfor%} views.py def search(request): query = request.GET.get('q') return render(request, 'ekyam/incubators.html', {"query": query}) Help would be greatly appreciated. Also let me know If I should add urls file too. -
Editing a field belonging to a through table in a formset
I have two models that have a many to many relationship via a custom through table. Foo(models.Model): ... models.ManyToManyField('Bar', through='Foo_Bar', related_name='foo_bar') Bar(models.Model): ... Foo_Bar(models.Model) foo = models.ForeignKey(Foo, related_name='foobar') bar = models.ForeignKey(Bar, related_name='foobar') foobar_relationship = models.CharField() I have created a modelformset for the model Foo allowing users to edit all records of Foo belonging to a specific instance of Bar via, FooBarFormSet = modelformset_factory(Foo, form=FooForm) foobar_formset = FooBarFormSet(queryset=Foo.objects.filter(foobar__BAR_ID=id)) What I would like is to have the users be able to edit the field foobar_relationship at the same time. I am not really sure how to achieve this. I can add foobar_relationship as an input no problem, I simply add a charfield to the form used to create my formset, and then I save the values when I set the relationships. The problem is that once a value is stored I don't know how to populatethe forms in my formset during a GET request. -
A wrong id is assigned to each new object being created in Django
I deleted some objects belonging to one of my models in Django. Now when I create a new object, a wrong id is assigned to this object. This id is not successive. How can I address this problem? The example: >>> Programmer.objects.all().values() <QuerySet [{'id': 1, 'name': 'Linus Torvalds','occupation': 'Software enginner'}, {'id': 2, 'name': 'Tim Cook', 'occupation': 'CEO'}, {'id': 3, 'name': 'Elon Musk', 'occupation': 'Entrepreneur, engineer'}]> >>> p4=Programmer(name='Mark Zuckerberg') >>> p4.save() >>> Programmer.objects.all().values() <QuerySet [{'id': 1, 'name': 'Linus Torvalds', 'occupation': 'Software enginner'}, {'id': 2, 'name': 'Tim Cook', 'occupation': 'CEO'}, {'id': 3, 'name': 'Elon Musk', 'occupation': 'Entrepreneur, engineer'}, {'id': 15, 'name': 'Mark Zuckerberg', 'occupation': None}]>