Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Limiting models based on status
I need to create a route to edit a purchase, but editing can only be done if the status of the purchase is "in validation". Does anyone know what Django tool I use to limit a status-based model? -
Error kernel Out of memory: Killed process (uwsgi) & consume too much memory
In the past few days, my site is crashing and OS message logs shows the OOM killer kills the process. Server have 32GB RAM but still we face Out Of Memory Issue due to uwsgi. OS: Gentoo Linux Here is my uwsgi.ini [uwsgi] chdir = /var/www/%n virtualenv = venv pythonpath = %(chdir)/python/ socket = /var/run/uwsgi/%n.sock logger = syslog:%n vacuum = true module = mysite.wsgi:application master = true threads = 32 enable-threads = true plugins = python27 spooler = %(chdir)/uwsgi_spooler spooler-processes = 5 spooler-frequency = 5 import = mysite.fork env = LC_ALL=en_US.UTF-8 env = LANG=en_us.UTF-8 Error Message logs /var/log/messages:Jul 20 06:31:39 ip-10-0-0-45 kernel: Out of memory: Killed process 16625 (uwsgi) total-vm:6933540kB, anon-rss:1988220kB, file-rss:3676kB, shmem-rss:68kB, UID:998 pgtables:12824kB oom_score_adj:0 /var/log/messages:Jul 20 16:02:48 ip-10-0-0-45 kernel: Out of memory: Killed process 25622 (uwsgi) total-vm:8216796kB, anon-rss:3184288kB, file-rss:4336kB, shmem-rss:72kB, UID:998 pgtables:15408kB oom_score_adj:0 /var/log/messages:Jul 20 18:22:25 ip-10-0-0-45 kernel: Out of memory: Killed process 27520 (uwsgi) total-vm:10033820kB, anon-rss:7766404kB, file-rss:4900kB, shmem-rss:72kB, UID:998 pgtables:18960kB oom_score_adj:0 /var/log/messages:Jul 20 18:41:47 ip-10-0-0-45 kernel: Out of memory: Killed process 26553 (uwsgi) total-vm:9450820kB, anon-rss:4271912kB, file-rss:0kB, shmem-rss:408kB, UID:998 pgtables:15804kB oom_score_adj:0 /var/log/messages:Jul 20 18:43:58 ip-10-0-0-45 kernel: Out of memory: Killed process 26988 (uwsgi) total-vm:9023384kB, anon-rss:4560056kB, file-rss:4896kB, shmem-rss:40kB, UID:998 pgtables:17080kB oom_score_adj:0 /var/log/messages:Jul 20 18:49:20 ip-10-0-0-45 kernel: Out of memory: … -
module not found error even though modules are in place
I had this error previously but at an instant, it was somehow fixed, but now it seems to crawl back,don't know where is the issue, thanks in advance Directory structure food_deliveryapp |- manage.py |- food_deliveryapp |- customers |- entries |- restaurants | |- __init__.py | |- admin.py | |- apps.py | |- models.py | |- City | |- Restraunts | |- views.py | |- tests.py | |- migrations | |- static |- templates my modules and models are in place but still getting this error Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\atif\PycharmProjects\my_proj_basic\food_deliveryapp\menus\models.py", line 3, in <module> from … -
How to convert from time stamp to a date time filed in dajngo
I 'm working on a django app and i have a model with a datetimefield and in my view i accept data in json format which has date in time stamp , when i try to save the date in my model i get this error "Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]." i tried to use this with no help : date_converted_to_date_time_field = datetime.utcfromtimestamp(due_in_time_stamp ) any help to achieve this ? -
Django - Celery - Heroku error: Redis is not responding
I would like my django to make a periodic task every 15 minutes. I've found out that celery would be a solution to my problem. I've created an heroku app, installed redis server addon there but it actually is not working anyway. While making a worker there is an output: ERROR/MainProcess] consumer: Cannot connect to redis://:pe8c9b5be760e533395873863fc98c469f126ca80574a04d6112a172d1756e2aa@ec2-34-194-101-94.compute-1.amazonaws.com:7140 My settings.py: # CELERY STUFF CELERY_BROKER_URL = 'redis://:pe8c9b5be760e533395873863fc98c469f126ca80574a04d6112a172d1756e2aa@ec2-34-194-101-94.compute-1.amazonaws.com:7140' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' tasks.py from celery import shared_task from time import sleep @shared_task def apiCalls(self, duration): #here I would like my function to execute - yet even print('abcdef') is not working return 'Done' What am I doing wrong? -
pytest cannot find database and tables
I am trying to speed up the test runtime by using pytest-xdist, previously I was using pytest, pytest-django to run the tests, After installing pytest-xdist, One is an issue which I am facing is most of the tests are failing with messages that relation does not exist pytest -n auto accounts/tests for example psycopg2.errors.UndefinedTable: relation "auth_user" does not exist I guess there is error which says database does not exist: django.db.utils.OperationalError: FATAL: database "test_dev" does not exist But the interesting thing is some of tests are passing :( -
Websocket disconnects immediately after handshake (guacamole)
Forgive bad formatting as it is my first question on here, and thanks in advance for reading! I am currently writing a remote web application that utilises Apache Guacamole to allow RDP, VNC, and SSH connections. The components I am using are: Django for backend server - API calls (database info) and Guacamole Websocket Transmissions; I am using Pyguacamole with Django consumers to handle Guacamole Server communication; Reactjs for frontend and proxy; Nginx for reverse proxy; All this is hosted on a Centos Stream 8 vm Basically, my websocket has trouble communicating through a proxy. When I run the application without a proxy (firefox in centos running localhost:3000 directly), the guacamole connection works! Though this is where the application communicates directly with the Django server on port 8000. What I want is for the react application to proxy websocket communications to port 8000 for me, so my nginx proxy only has to deal with port 3000 for production. Here is the code I have tried for my react proxy (src/setupProxy.js): const { createProxyMiddleware } = require('http-proxy-middleware'); let proxy_location = ''; module.exports = function(app) { app.use(createProxyMiddleware('/api', { target: 'http://localhost:8000', changeOrigin: true, logLevel: "debug" } )); app.use( createProxyMiddleware('/ws', { target: 'ws://localhost:8000' + … -
Django multiple parents and every parent may have the same children, but changing one children should be changed for this parent not the others?
I have a system for ambulance service built with Django, React for the API and dashboard and Android for the mobile app, where crew belong to an ambulance and ambulance has calls and every call has forms and every form has questions Now when crew login to mobile app he will see his ambulance details and its calls and inside each call he will see the forms Now crew need to do two things, submit forms and submit call In case submitting a form it should be showed on the admin dashboard a list of submitted forms and in case to submit a call, crew must submit first all required forms inside that call, and submitted calls should be showed on the admin dashboard Also I need to make checkbox done on the mobile app to the submitted call or form To solve this, I added a boolean field for the call model and form model to check if call or form is submitted Now the client didn't want that, because he could assign the same form or call for another ambulance that has different crew, so in my case if another crew logged to the app he will see … -
how to delete useranme and password of customuser in django
how to delete username and password of a customuser in Django. I wanna set phone and OTP code instead of username and password. class User(AbstractUser): """ . . . """ image = models.ImageField(blank = True) number = models.IntegerField() -
How to update a specific value of a object present in array of object within Postgres JSON Field
Here is my JSON field value. which is stored in the PostgreSQL table. I want to search and update the specific user_name in the user key { "user": [ { "user_name": "Devang", "user_weight": 0.7676846955248864 }, { "user_name": "Meet", "user_weight": 0.07447325861051013 }, { "user_name": "L.b.vasoya", "user_weight": 0.056163873153859706 } ], "address": [ { "address_name": "India" } ] } whose name is Devang to Dev using Django JSONField for example "user": [ { "user_name": "Dev", "user_weight": 0.7676846955248864 }, .... I have tried the RAWQuery for the find. This is the query. ``` select json_field->user from user_table where json_field @> '{"user": [{"user_name": "Devang"}]}'; It will return like this ```[ { "user_name": "Devang", "user_weight": 0.7676846955248864 }, { "user_name": "Meet", "user_weight": 0.07447325861051013 }, { "user_name": "L.b.vasoya", "user_weight": 0.056163873153859706 } ] I have also tried JSON_SET to update the user_name but JSON_SET only accepts. It will update the upper level, not a nesting level -
What is the difference between cached_property in Django vs. Python's built-in?
Django has a decorator called cached_property which can be imported from django.utils.functional. On the other hand, Python 3.8 added cached_property to the standard library which can be imported from functools. Are both equivalent, i.e., are they interchangeable? or what is the difference between both? Are there any best practices when to use one or the other? -
How to recommend items in Django?
I want to track the user and which categories of blogs he/she is searching/reading then utilise this data to recommend blogs in a recommended blogs section in the home page. I have been researching for several days and found Django-recommends but the documentation is very unclear.Thanks in Advance... -
How can I use the information of a field from one model to calculate another field in other model?
Im creating a restaurant software with python and Django. I have an Ingredient model that has cost and quantity fields. I use them to return the cost_per_unit calculated field (cost / quantity). Then, I created a recipe model, with the fields: ingredient as Foreign key, ingredient_quantity and cost_per_ingredient. How can I use the information that I already have in the Ingredient model (cost_per_unit) to calculate the cost_per_ingredient (it would be cost_per_unit * ingredient_quantity) ? Thanks in advance -
How to filter list data by id and show the single object in HTML template by django?
This is the Json List Below: "chartOfAccounts": [ { "id": 147, "name": "Sales Product - Wholesale test", "description": "Sales - Wholesale", "balance": "0.00", "is_active": true, "is_editable": true, "account_detail_type": { "id": 5, "name": "Accounts Receivable (A/R)", "account_type": { "id": 2, "name": "Accounts Receivable (A/R)", "principle": { "id": 1, "name": "Asset", "calculation_type": "dr" } }, "calculation_type": "dr" } }, { "id": 146, "name": "Sales Product - Wholesale test", "description": "Sales - Wholesale", "balance": "0.00", "is_active": true, "is_editable": true, "account_detail_type": { "id": 5, "name": "Accounts Receivable (A/R)", "account_type": { "id": 2, "name": "Accounts Receivable (A/R)", "principle": { "id": 1, "name": "Asset", "calculation_type": "dr" } }, "calculation_type": "dr" } }, { "id": 145, "name": "Cash in hand rony", "description": "Cash in hand rony", "balance": "-45980.00", "is_active": true, "is_editable": true, "account_detail_type": { "id": 1, "name": "Cash and cash equivalents", "account_type": { "id": 1, "name": "Cash and cash equivalents", "principle": { "id": 1, "name": "Asset", "calculation_type": "dr" } }, "calculation_type": "dr" } }, { "id": 144, "name": "6yt4", "description": "gyyy", "balance": "5203.00", "is_active": true, "is_editable": true, "account_detail_type": { "id": 1, "name": "Cash and cash equivalents", "account_type": { "id": 1, "name": "Cash and cash equivalents", "principle": { "id": 1, "name": "Asset", "calculation_type": "dr" } }, "calculation_type": "dr" … -
Django TrigramSimilarity search gives no such function: SIMILARITY
I am trying to do a TrigramSimilarity search in my Django project. As written in the django documentation i have done the following import: from django.contrib.postgres.search import TrigramSimilarity; I have also added 'django.contrib.postgres' inside the INSTALLED_APPS of the settings.py file. This is the code that brings to the error (i say 'brings' because the error itself comes only if i use the queryset: for example, if i do print(articles)(obviously after query) the error comes): articles = Article.objects.annotate( similarity=TrigramSimilarity('name', search_str), ).filter(similarity__gt=0.3).order_by('-similarity') print(articles) #that line causes the error (no such function: SIMILARITY) I have literally searched for everything, but it seems that no one had this error before. I have exactly did what the documentation says -> here -
Django - How to populate manytomany field in forms by previously selected options by users
How can I populate manytomany form field with previous user selected subs. In this code forms render choices with empty checkboxes. I want checkboxes to show which subscriptions user subscribed to. models.py class Subscription(models.Model): SUBSCRIPTION_TYPES = ( ('SUB1', _('sub 1')), ('SUB2', _('sub 2')), ) subscription_type = models.CharField(choices=SUBSCRIPTION_TYPES, max_length=30, unique=True) description = models.CharField(max_length=255, blank=True) class UserSubscription(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) subscriptions = models.ManyToManyField(Subscription, related_name='subscriptions', related_query_name='subscriptions') forms.py class SubscriptionForm(forms.ModelForm): class Meta: model = UserSubscription fields = ('subscriptions',) widgets = { 'subscriptions': forms.CheckboxSelectMultiple(), } views.py class SubscriptionFormView(FormView): template_name = 'profile/subscription.html' form_class = SubscriptionForm -
How to save and return multiple objects using PUT and PATCH method in Django
I'm trying to update some records in a DB table using the Update API view which consists of PUT and Patch methods. Upon calling the API I'm getting MultipleObjectsReturned: get() returned more than one error. Below are sample records that I'm trying to update. [ { "id": 1, "value": 1.00, "spec_id": 6, }, { "id": 2, "value": 1.00, "spec_id": 6, }, { "id": 3, "value": 1.00, "spec_id": 6, }, I'm sending spec_id in API for ex:- /api/specification/:spec_id/ and payload as {'value':2.00}, which will basically be used for updating the data on the basis of spec_id by querying in to the table. Code to look data in the DB table based on spec_id and update all the records related to spec_id & return: views.py class SpecificationUpdateAPIView(BaseAuthenticationMixin, generics.UpdateAPIView): serializer_class = SpecificationAdminSerializer permission_classes = [IsAdminUser] lookup_field = "spec_id" queryset = Specification.objects.all() serializers.py class SpecificationAdminSerializer(CreateUpdateModelSerializer): class Meta(CreateUpdateModelSerializer.Meta): model = Specification fields = ("id", "value", "spec") urls.py path( "api/specification/<int:spec_id>/", views.SpecificationUpdateAPIView.as_view(), name="specification-update-view", ) Could someone please help me resolve this issue, highlight the mistake I'm doing or navigate me to any other better approach to make this kind of scenario work? Thanks in advance. -
Custom filter with Django Filters
I am trying to write my own custom filter class as follows using django_filters: from django_filters import rest_framework as filters class FooFilter(filters.FilterSet): class Meta: model = Model fields = ['custom_field',] class Foo(): filter_backends = (filters.DjangoFilterBackend,) filterset_class = FooFilter In models, as I do not have the field custom_field, it will give the error: TypeError: 'Meta.fields' must not contain non-model field names: custom_field Question: Is it possible to define my own custom query that is a non-model field name using Django Filterset? -
Django AssertRedirects throws Assertion error 301 != 302
My Django view conditionally redirects to either error page or the target page on invoking 'get'. I am using redirect(reverse()) for the redirection logic. When I run this application, the url redirections are working as expected. For writing test cases, I mocked the function that returns this redirect(reverse()). I confirmed that the mock response is being returned when the method is called. But the response in the test case either shows http404ResponseNotFound or an assertion Error 301 != 302. How to properly test for redirection? Below code for reference Class MyView: def foo(self): try: # some logic return redirect(reverse('someview', kwargs={'key': '12345'})) except(ExceptionClass1, ExceptionClass2) as err: return errorView.as_view()(err) def get(self): # some logic if (some_condition) return self.foo() # Test case is for this line. return something_else Class MyViewTests: @mock.patch(MyView.foo) def test_1(self, mock_foo): mock_foo.return_value = redirect(reverse('step', kwargs={'key': '123'})) client = Client() response = client.get('/myview', follow=True) self.assertRedirects(response, '/view/step/123', fetch_redirect_response=False) Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/mock/mock.py", line 1346, in patched return func(*newargs, **newkeywargs) File "/usr/src/app/django/tests/test_api.py", line 488, in test_1 self.assertRedirects(response, '/view/step/123', fetch_redirect_response=False) File "/usr/local/lib/python3.8/site-packages/django/test/testcases.py", line 274, in assertRedirects self.assertEqual( AssertionError: 301 != 302 : Initial response didn't redirect as expected: Response code was 301 (expected 302) -
OperationalError at /admin/login/ even after making migrations
I have made migrations still i am getting this error . I have tried deleting the database and making it again. I have tried making migrations again and again but problem is still there. OperationalError at /admin/login/ no such table: auth_user -
Javascript Uncaught ReferenceError: grp is not defined
This error occured in the admin model object list panels. This caused the select all checkbox to not work. (grp.jQuery); Is at the end of a few admin js files. Yet I cannot find where grp is defined. Reinstalling django did not work for me. Edit: This problem occured after I uninstalled grappelli, I am fairly sure I have removed everything related to that. -
How to delete model data on button click? - Django
I have the following button: <a style="float:right; margin:5px; color: white;" href="" class="btn btn-success" >Accept</a> When the button is clicked on by the user, I want to delete data that is associated with the pk For example, when the button is clicked, I want to pass the {{donation.pk}} into a function and delete the Donation that is associated with it I have done so much research but I can not find out a way to do this. -
django displaying subcategories of categories
how can i pass subcategories to a category, i am trying {%for subcat in cat.sub_categories_set.all %} is it worth doing it separately? then I will not be able to display new categories? template <div class="widget catagory mb-50"> <!-- Widget Title --> <h6 class="widget-title mb-30">Categories</h6> {% for cat in categories %} <div class="catagories-menu"> <ul id="menu-content2" class="menu-content collapse show"> <!-- Single Item --> <li data-toggle="collapse" data-target="#{{ cat.name }}"> <a href="#">{{ cat.name }}</a> <ul class="sub-menu collapse show" id="{{ cat.name }}"> <li><a href="{% url 'shop_clothing' %}">All</a></li> {% for subcat in cat.sub_categories_set.all %} <li><a href="{% url 'shop_subcategory' subcat.slug %}">{{ subcat.name }}</a></li> {% endfor %} </ul> </li> </ul> </div> {% endfor %} *view* class Shop(ListView): template_name = 'essense/shop.html' context_object_name = 'items' paginate_by = 9 allow_empty = True model = Item def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) categories = Category.objects.all() sub_categories = SubCategory.objects.all() context['categories'] = categories context['sub_categories'] = sub_categories return context def get_ordering(self): return self.request.GET.get('orderby', ) -
How to proccess token?
I have a question. In my project, after a user loges in my app generates an access token and then put it on cookies. This access token contains information like user rights and some other details about him. For authentication part I use 'DEFAULT_AUTHENTICATION_CLASSES' which is mapped to a class that subclasses TokenAuthentication class from rest_framework.authentication. Instead of decoding again the access token in every view, how can I have it's rights from access token? What should I use? May put decoded token in request.session? -
Hi, is there any way of getting rid of the autocomplete background when my webpage has loaded my saved login credentials?
If i delete the login credentials, the colour of the field is fine. it turns back to the grey colour that you can see in the image i've provided. However when reloading the page the light blue colour appears, which as you can see doesn't look very appealing. I've tried to find a solution on YouTube and i cant seem to find anything. Does anyone have a solution for this? image of my field HTML code: <form method="POST" autocomplete="off" action="" name="form" > {% csrf_token %} <div class="wrapper"> <h1>Login</h1> <div class="form" > <div class="user_input" style="padding-top:10px ;"> <input type="text" name="username" placeholder="Username" class="form-control" style="border: none; background-color:#e9e9e9; height: 40px; padding:10px;"> </div> <div class="user_input"style="padding-top:10px;" > <input type="password" name="password" placeholder="Password" class="form-control" style="border: none; background-color:#e9e9e9; height: 40px; padding:10px;"> </div> <div class="button" > <button type="submit" style="width: 130px; height: 40px; border-radius: 8px; color: white; background-color:#0088a9; border: none;" >Login</button> </div> {% for message in messages %} <p id="messages" style="text-align: center; margin-top: 20px;">{{message}}</p> {% endfor %} <div class="loginbtn"> <p style="margin-top: 20px; text-align: center; color: black;">Don't have an account?<br> click here to <a href="{% url 'register' %}">Sign up</a> </p> </div> </div> </div> </form> CSS code: *{ margin: 0; padding: 0; box-sizing: border-box; outline: none; text-decoration: none; font-family: 'Raleway', sans-serif; } .wrapper{ position: …