Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django redirects to non existing url
Two days ago I created a django project and it worked all right. But, now when I am working on another django project still when I run server it's redirecting me to the older project. I am using different virtual environment for both of them. Even after deleting the old one the issue is not resolved. Thanks in advance. -
Creating an autocomplete search form (probably w/ jQuery) using a comprehensive (huge) movie title list (Django project) from IMDBPy
I am in the early stages of retrieving IMDB data via the Python package IMDBPy (their site) (proj github). I have been referring to this nice IMDBPy implementation for help with aspects of what I'm doing here. Several of the queries that I'm using generate datasets that come in "nested dictionary" form, e.g. 'movie_1':{'title':'One Flew Over the Cuckoo's Nest', 'director': 'Milos Forman'...}. My early version of the title retrieval takes this form in VIEWS.PY: def index(request): imdb = IMDb() test_movies = {} for i in range(1100000, 1100015): test_movies[f'movie_{i}'] = imdb.get_movie(f'{i}') context = { 'test_movies':test_movies, } return render(request, 'index.html', context) And this in my INDEX.HTML template: <div id="search-part1"> <ul> {% for k1,v1 in test_movies.items %} {% for k2,v2 in v1.items %} {% if 'title' in k2 %} <li>{{v2}}</li> {% endif %} {% endfor %} {% endfor %} </ul> <input type="text" name="search" id="search" class="form-control" placeholder="Search for Movies"> </div> Right now, the HTML is just to show that I *can generate a list of these titles. My actual implementation of the dropdown from the search bar (via jQuery's Autocomplete), is a little further down the road at this point. Here is an example that they provide of the Autocomplete in action, in the … -
django how to set form ModelChoiceField drop down to required if specific value is selected from the previous drop down
I have the following form: class RegisterForm(UserCreationForm): company_role = forms.ModelChoiceField(queryset=CompanyRole.objects, empty_label='Select Company Role') office = forms.ModelChoiceField(queryset=Office.objects, empty_label='Select Office', required=False) location = forms.ModelChoiceField(queryset=Country.objects.all(), empty_label="Select Location", required=False) class Meta: model = User fields = ["first_name", "last_name", "username", "email", "password1", "password2", "company_role", "location", "office"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['office'].queryset = Office.objects.none() Is it possible through this form to set office ModelChoiceField drop down to be required if the first item (id 1) is selected in company_role ModelChoiceField drop down and also if second item (id 2) is selected in company_role ModelChoiceField drop down then set location ModelChoiceField drop down to be required? If so would greatly apprecaite some help on how to do so. Thanks in advance -
Send both POST and GET parameters in Django test client
I've created a view created in Django which accepts both GET and POST parameters. When trying to test it using django-rest-framework test APIClient, it's not clear how I can send both GET and POST parameters. self.client.post has a signature as follows: self, path, data=None, format=None, content_type=None, follow=False, **extra Using data would probably send POST data, is there any workarounds for this? -
How to query and update nested JSON data in Django
I have below class defined to do statistics for voting system. class FormPage(AbstractForm): submission_stats = models.JSONField(null=True, editable=False) Now, I have submission_stats in below format: [ { "id":4, "label":"checkboxes", "choices":[ { "content":"option-A", "num_vote":0, "user_list":[ ] }, { "content":"option-B", "num_vote":0, "user_list":[ ] }, { "content":"option-C", "num_vote":0, "user_list":[ ] } ] }, { "id":7, "label":"Radio Button", "choices":[ { "content":"option-1", "num_vote":0, "user_list":[ ] }, { "content":"option-2", "num_vote":0, "user_list":[ ] }, { "content":"option-3", "num_vote":0, "user_list":[ ] } ] } ] When I receive a vote submission, I want to update num_vote and user_list field in this JSONField accordingly. How to query and update elements in nested JSONField data please ? -
Cloning existing python project anyjson setup command error
I have this project shared to me via github, after I clone and run this steps: python -m venv ./venv venv\scripts\activate pip install -r requirements.txt in pip install -r: It gives me this errors: error in anyjson setup command: use_2to3 is invalid. ERROR: Could not find a version that satisfies the requirement anyjson==0.3.3 (from versions: 0.1, 0.2.0, 0.2.1, 0.2.2, 0.2.3, 0.2.4, 0.2.5, 0.3, 0.3.1, 0.3.2, 0.3.3) ERROR: No matching distribution found for anyjson==0.3.3 Here is what inside the requirements.txt amqp==1.4.9 anyjson==0.3.3 billiard==3.3.0.23 celery==3.1.25 certifi==2019.3.9 chardet==3.0.4 dj-database-url==0.5.0 Django==2.0.13 django-appconf==1.0.3 django-axes==1.7.0 django-celery==3.2.2 django-compressor==2.2 django-crispy-forms==1.7.2 django-dynamic-formsets==0.0.8 django-polymorphic==2.1.2 django-reversion==3.0.1 djangorestframework==3.7.4 ffs==0.0.8.2 gunicorn==20.0.4 idna==2.7 Jinja2==2.10 kombu==3.0.37 letter==0.5 MarkupSafe==1.1.1 opal==0.14.2 Pillow==8.1.0 psycopg2==2.8.6 python-dateutil==2.7.5 pytz==2019.1 rcssmin==1.0.6 requests==2.20.1 rjsmin==1.0.12 six==1.12.0 urllib3==1.24.3 whitenoise==4.1.4 mysqlclient==2.0.3 cryptography==3.4.1 Already tried removing anyjson from requirements.txt but still gives me error. What Am I missing here? -
Why we must have form with model in django, why model alone can't work?
In django: request.POST--1-->corresponding_SQL--2-->database . And we use form = ModelForm(requst.POST).save() to save a form to database. The form has well designed "consructor", which take value and key inside queryDict(request.POST) and convert them to data inside the instance of form one by one. I guess this 'Form' object is kindof an agent,which can be easily stored to database (like above) and can be rendered out in HTML using form.as_p(). Actually I wonder why we don't put all the functions of a form into the model itself, I think that is more intuitive than create a new class called "form". We could just use model.save() or model.is_valid() or model.as_p(), emmm why bother to design a new class called form? -
LISTAR EL NUMERO DE CATEGORIA CONSULTADAS DENTRO DE UNA ITERACION
Hola, buenas noches ¿Por favor me podrían ayudar con la siguiente duda? En mi vista cree una consulta que me lista todas las categorías exceptuando una, esas categorías las itere en un bucle For en la página html, el modelo Categoría está relacionado con otro que se llama Post, mi intención ahora es que en la parte que dice (N. Post) de mi template, se liste el número de Post que tiene esa categoría. ¿Como podría implementar esa consulta en mi Views? ¿Puedo directamente dentro de ese bucle For contar las categorías y ahí mismo listarlas en la etiqueta ? [1]: https://i.stack.imgur.com/Q4jhU.jpg [2]: https://i.stack.imgur.com/LxxcX.jpg [3]: https://i.stack.imgur.com/kmC6m.jpg [4]: https://i.stack.imgur.com/nz1PV.jpg -
Deploying django app to EC2.. server is running through docker compose, but times out when trying to reach the host?
First time deploying an application, so bear with me... I have my EC2 instance up. I have my code on the server with docker-compose being run (docker-compose -f docker-compose.yml up), and the logs say that it is running with Starting development server at http://0.0.0.0:8000/ I have my allowed_hosts to specify the ec2 instance. When i attempt to hit the server in my browser, im getting nothing. It times out, and no logs in the ec2 instance. Any idea of what im potentially missing? -
Django Channels: WebSocket messages are not sent in production
I have Django server which uses WebSockets to send real time updates to web clients. This is all running perfectly fine locally (with manage.py runserver), but in production I am running into the problem that most messages are simply not sent at all. I test this by opening two browsers, making a change in one, which should then be reflected in the other browser. Like I said, this all works locally, but not in production. In production some WebSocket messages are sent by the server and received by the web client, but maybe 20% or so? The rest is just not sent at all. # /websocket/__init__.py import logging from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from djangorestframework_camel_case.util import camelize logger = logging.getLogger("django.server.ws.critical-notes") def ws_send(model_type, action, model_data, user_ids): logger.info(f"Called ws_send for model {model_type}, action {action}, user_ids: {user_ids}") channel_layer = get_channel_layer() for user_id in user_ids: group_name = f"user-{user_id}" async_to_sync(channel_layer.group_send)( group_name, { "type": "send.data", # this calls Consumer.send_data "data": {"type": model_type, "action": action, "model": camelize(model_data)}, }, ) # /websockets/consumers.py import logging from channels.generic.websocket import AsyncJsonWebsocketConsumer from channels.db import database_sync_to_async from django.db import close_old_connections from knox.auth import TokenAuthentication logger = logging.getLogger("django.server.ws.critical-notes") class Consumer(AsyncJsonWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.group_name = None @database_sync_to_async … -
Django Rest Framework Patch Request with Image Upload
I'm trying to make an endpoint for updating the profile image of a user. However, whenever I make the PATCH request, the profile_image field does not change to the uploaded file. I've tested on postman using form-data and I get the response "Updated completed" but the profile_image field remains null. views.py class ProfileImageView(APIView): parser_classes = [MultiPartParser, FormParser] def patch(self, request, user_email, format=None): print(request.data) profile = ProfileImage.objects.get(user_email=user_email) serializer = ProfileImageSerializer(profile, data=request.data, partial=True) data = {} if serializer.is_valid(): serializer.update(profile, request.data) data["response"] = "Update completed." data["user_email"] = user_email data["profile_image"] = ( profile.profile_image.url if profile.profile_image else None ) return Response(serializer.data) data["response"] = "Wrong parameters." return Response(data) models.py class ProfileImage(models.Model): user_email = models.CharField(max_length=255) profile_image = models.ImageField( upload_to="uploads/", height_field=None, width_field=None, null=True, blank=True, ) serializers.py class ProfileImageSerializer(serializers.ModelSerializer): class Meta: model = ProfileImage fields = ["user_email", "profile_image"] urls.py urlpatterns = [ path("api-auth/", include("rest_framework.urls")), path("admin/", admin.site.urls), path("register/", RegisterView.as_view(), name="register"), path("login/", obtain_auth_token, name="login"), path("log/add/", LogView.as_view(), name="log"), path("log/all/", LogView.getAll, name="logall"), path("log/<str:user_email>/", LogView.getByUserEmail, name="logbyuseremail"), path("profile/<str:user_email>/", ProfileView.profile, name="profile"), path("edit-profile/<str:user_email>/", ProfileView.as_view(), name="profile"), path( "profile-image/<str:user_email>/", ProfileImageView.getProfileImage, name="profile-image", ), path( "edit-profile-image/<str:user_email>/", ProfileImageView.as_view(), name="profile-image", ), path("events/", EventView.as_view(), name="events"), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) enter image description here -
How to pass data from one View function to another for a multi-step form?
I'm currently working a developing a Hockey League management website. The feature I am currently working on, is entering a "Game Report". This is where a score keeper enters in all the details for that game once it has been completed. The Game report feature itself requires 3 steps to be completed. Selecting the game for which you want to enter the report for. A form which populates the roster of both teams, with a checkbox for each player to mark off if they played in the game. In addition, there is 2 separate formsets to add players for either team if they aren't already on the roster. The final part of the game report, where you enter in the goals, penalties, and the game results. Where the goals and penalties are formsets, and the game results are a simple model form. The confusion comes from the fact that data from the prior step, is required for the current step. SelectGame View (Step 1) - No issues here @login_required(login_url="/login/") def selectGame(request): games = Game.objects.all().values( 'iceSlot__date', 'homeTeam__name', 'awayTeam__name', 'id' ) context = {'games': games} return render(request, "home/select-game.html", context) Transition From Step 1 to Step 2 occurs in select-game.html (Also No issue) … -
Django - Why is full URL being returned for some FileFields, but not others?
So I have this view that returns a list of posts that are like a facebook wall post. As you can see in the above image this encompasses: images, videos maybe, avatar, text, and metadata about the post and metadata about the user. I get all the relevant data for the post via table joins. For some reason Video and Photo are returning the full URL with the domain of MEDIA_URL prepended, but creator_avatar_url is only returning the tail end of the url (i.e something like /media/user/avatar.jpeg). Why is my code not returning the full URL for creator_avatar_url? model.py class User(AbstractDatesModel): uuid = models.UUIDField(primary_key=True) username = models.CharField(max_length=USERNAME_MAX_LEN, unique=True, validators=[ MinLengthValidator(USERNAME_MIN_LEN)]) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) avatar = models.ImageField(upload_to=avatar_directory_path, blank=True, null=True) @property def avatar_url(self): return self.avatar.url class Post(models.Model): uuid = models.UUIDField(primary_key=True) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator") body = models.CharField(max_length=POST_MAX_LEN, validators=[MinLengthValidator(POST_MIN_LEN)]) class Photo(AbstractBaseModel): post = models.OneToOneField(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to=images_directory_path) @property def image_url(self): return self.image.url class Video(AbstractBaseModel): post = models.OneToOneField(Post, on_delete=models.CASCADE) video = models.FileField(upload_to=videos_directory_path) @property def video_url(self): return self.video.url helper.py def query_to_full_post_data_serializer(request, post_query_set: QuerySet): query_set_annotated = post_query_set.annotate( creator_username=F('creator__username'), creator_avatar_url=F('creator__avatar'), ).prefetch_related( … -
Django view with slug and id
I have this URL path('kategorie/<slug:slug>-<int:pk>', views.category_view, name="category_view"), And this view def category_view(request,slug,pk): categories = EcommerceProductCategory.objects.all().filter(slug=slug, pk=pk).order_by('-created_at') product = Product.objects.filter(slug=slug).order_by('-created_at') context = { 'categories': categories, 'product': product, } return render(request, 'ecommerce/category_view.html', context=context) Now i wanna show on that page category_view.html only the products that have particular slug and pk. Lets say kategorie/cat-4. Cat is the category.slug and the category.pk is 4 and i only wanna show the products that have this category and this pk. (Btw yes product is connected with Ecommerce via M2M) -
Multiple Widgets in Form Field - Django Forms
I'm working on a form in Django and it has a select element with a unique ID. This is what I'm currently doing: instance_type = forms.CharField(label='Instance Type', widget=forms.Select(choices=INSTANCE_TYPES), widget=forms.TextInput(attrs={'id':'instance_type'})) The problem is that Django is giving me a syntax error that says: SyntaxError: keyword argument repeated: widget I need to combine these two widgets into one, but haven't found a solution to it. Any help is appreciated. Thank you all! -
pipenv.exceptions.ResolutionFailure; ERROR: Disabling PEP 517 processing is invalid
I ran into what seems to be a dependency conflict when trying to run pipenv lock but can't seem to figure out what is causing this: [pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. You can use $ pipenv install --skip-lock to bypass this mechanism, then run $ pipenv graph to inspect the situation. Hint: try $ pipenv lock --pre if it is a pre-release dependency. ERROR: Disabling PEP 517 processing is invalid: project specifies a build backend of setuptools.build_meta:__legacy__ in pyproject.toml I tried to debug using the suggested pipenv install --skip-lock and pipenv graph and wasn't able to spot any conflicts in the output below: bleach==4.1.0 - packaging [required: Any, installed: 21.3] - pyparsing [required: >=2.0.2,!=3.0.5, installed: 3.0.6] - six [required: >=1.9.0, installed: 1.16.0] - webencodings [required: Any, installed: 0.5.1] bpython==0.21 - curtsies [required: >=0.3.5, installed: 0.3.5] - blessings [required: >=1.5, installed: 1.7] - six [required: Any, installed: 1.16.0] - cwcwidth [required: Any, installed: 0.1.4] - cwcwidth [required: Any, installed: 0.1.4] - greenlet [required: Any, installed: 1.1.1] - pygments [required: Any, installed: 2.10.0] - pyxdg [required: Any, installed: 0.27] - requests [required: Any, installed: 2.26.0] - certifi [required: >=2017.4.17, installed: 2021.5.30] … -
Django: Script that executes many queries runs massively slower when executed from Admin view than when executed from shell
I have a script that loops through the rows of an external csv file (about 12,000 rows) and executes a single Model.objects.get() query to retrieve each item from the database (final product will be much more complicated but right now it's stripped down to the barest functionality possible to try to figure this out). For right now the path to the local csv file is hardcoded into the script. When I run the script through the shell using py manage.py runscript update_products_from_csv it runs in about 6 seconds. The ultimate goal is to be able to upload the csv through the admin and then have the script run from there. I've already been able to accomplish that, but the runtime when I do it that way takes more like 160 seconds. The view for that in the admin looks like... from .scripts import update_products_from_csv class CsvUploadForm(forms.Form): csv_file = forms.FileField(label='Upload CSV') @admin.register(Product) class ProductAdmin(admin.ModelAdmin): # list_display, list_filter, fieldsets, etc def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} extra_context['csv_upload_form'] = CsvUploadForm() return super().changelist_view(request, extra_context=extra_context) def get_urls(self): urls = super().get_urls() new_urls = [path('upload-csv/', self.upload_csv),] return new_urls + urls def upload_csv(self, request): if request.method == 'POST': # csv_file = request.FILES['csv_file'].file # result_string = … -
Import "rest_framework" could not be resolved
I was installing a django Rest Framework for my project. I installed this with pip install djangorestframework it worked perfectly fine, then i add a rest_framework line into INSTALLED_APPS in settings.py. And now at this point I want to import Response from rest_framework in views.py but it shows: ImportError: cannot import name 'Response' from 'rest_framework' It looks like it's not installed I guess, but it is ... I checked even a version of rest_framework from the console and it shows everything. Do you have any idea what is going on ? -
why I am having TypeError: expected string or bytes-like object - django
hello I am doing an app with django and I was using sqlite I want to migrate to postgres now but I am having this error I think something related to time but I really don't know how to solve it. Applying users.0018_auto_20210911_1322...Traceback (most recent call last): File "C:\Users\lenovo ideapad\Desktop\callservices\manage.py", line 22, in <module> main() File "C:\Users\lenovo ideapad\Desktop\callservices\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\db\migrations\migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\db\backends\base\schema.py", line 490, in add_field definition, params = self.column_sql(model, field, include_default=True) File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\db\backends\base\schema.py", line 237, in column_sql default_value = self.effective_default(field) … -
Ajax POST fails to due missing CSRF token
I've got a rather odd problem. I've got probably 100s of ajax calls back to my backend. They all work except for one. For some reason, on one page that doesn't require that the user be logged in to access (but can be logged in when they access the page), the ajax query fails due to missing CSRF token. When I clear history/cookies in Chrome, the ajax call is successful. Any thoughts on what could be causing this? Thanks! -
How to run a script or command every time a terminal (zsh) opens in a VSCode workspace?
I am working on a Django project on macOS. My terminal runs zsh. I want to create helpful aliases, like run instead of python manage.py runserver, but, I don't want to run these commands every single time I open a new terminal. So here's what's going on: I don't want to create these aliases or run any command in my home directory's .zshrc or .zprofile because I don't want them to be system-wide. I want to run them on local project directories exclusively. Every time we open a new terminal on VSCode, when working with a selected Python virtual environment, a command to activate it gets run first thing. It will look like this: source /Users/.../venv/bin/activate This (should be) carried out by Microsoft's Python extension. I cloned its repo but had no luck finding where they place this in VSCode's configurations. Where do they? Some posts on StackOverflow told me to take a look on the terminal.integrated.profiles.osx setting. I did, and the closest thing I came to was creating this profile: "zsh (Django)": { "path": "zsh", "args": [ "-c", "source setup.sh" ] } setup.sh is a file on my working directory. Its only command, for now, is echo "Hello World". … -
pytest-django and conservative db access
I know that pytest-django takes a ‘conservative’ approach to database access: https://pytest-django.readthedocs.io/en/latest/database.html And I don’t have a problem with that, but as that same page makes clear, the db being accessed is still a test db that is being setup and then torn down, so why the ‘need’ to be ‘conservative’? The real database isn’t being touched at all, so there’s no risk, or am I missing something? Thanks. -
Handling many text input fields in Django?
I'm using Django 3 (still) on my resume website. I'm working on a Sudoku Solver as an example personal project, so I have 81 text input fields in a grid. I'm trying to find the least painful way to handle up to 81 inputs in Django, so I can pass the inputs to my Python function(s) that handle the sudoku logic. How would I go about getting the user input into my views.py and handling all of them? I'm wanting to take whichever cells in which the user inputs numbers, process them through my Python function(s), and then send the full puzzle back into the cells once processed. I'm not super experienced with forms and form data in HTML just yet. For reference, here is my HTML that handles the grid. I know I'll need to add in maximum text length for the input fields, to ensure the user can only enter 1 digit per cell. <section class="resume-section"> <div class="d-lg-grid" id="grid"> <div id="grid-1"> <input type="text" size="3" id="cell1"> <input type="text" size="3" id="cell10"> <input type="text" size="3" id="cell19"> <input type="text" size="3" id="cell28"> <input type="text" size="3" id="cell37"> <input type="text" size="3" id="cell46"> <input type="text" size="3" id="cell55"> <input type="text" size="3" id="cell64"> <input type="text" size="3" id="cell73"> </div> … -
Django How to bulk update all child object?
I am building help desk system on django. Where anyone can open ticket for customer support. Assume I have an parent object #001 and every child object of this parent have same ticket id. See the screenshot for better understand: child1 and child2 have same ticket id like their parent object. How to apply bulk update on all objects if they have same ticket id?. Assume if I change ticket status of child2 then I want it will also apply bulk update of child1 and parent object. any idea how to do that on django? here is my code: models.py class Contact(models.Model): choice = (("pending","pending"),("solved","solved"),("closed","closed")) ticket_status = models.CharField(choices=choice,max_length=100,default="pending") parent =models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='contact_parent') sno = models.AutoField(primary_key=True,) def save(self,*args,**kwargs): if not self.parent and not self.support_ticket: self.support_ticket= str(rand_support_ticket()) if not self.support_ticket: self.support_ticket = self.parent.support_ticket super(Contact,self).save(*args,**kwargs) forms.py class SupportAgentFrom(forms.ModelForm): class Meta: model = Contact fields = ['support_message','ticket_status'] views.py def AddReplySupport(request,slug): # fetch the object related to passed id obj = get_object_or_404(Contact, slug = slug) # pass the object as instance in form form = SupportAgentFrom(request.POST or None, instance = obj) if form.is_valid(): form.instance.support_agent = request.user form.save() now I can update only single object once at a time. I want to apply bulk … -
Heroku being extremely slow when there's a lot of requests
I have a Django app deployed to Heroku. A few days ago it was totally fine, when my traffic was low. I had 5 requests per second, and the response time was not more than 2 seconds. However, I have recently started getting a lot of traffic. My requests per second have gone up to 50, and now my response time is 30 seconds. I'm trying to figure out whats going on. Naturally I scaled up my dynos. I went from a Standard tier dyno to a professional dyno with 2 workers. I also updated my Procfile to have Gunicorn use 12 workers: web: gunicorn wsgi -w 12 --timeout 30 I also updated my database to a standard tier so I'd have more connections. I realized I wasn't using Gzip compression with Django, so I added the Gzip middleware as well 'django.middleware.gzip.GZipMiddleware'. However, surprisingly, the request time is still 30 seconds or more. None of these new changes have made a difference. I also optimized some of my database queries, and that had a very minor impact. All this is leading me to think there's something wrong with either how my Django app is set up or Heroku itself, but …