Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run command when worker starts on Heroku-Django
I have a Django app running on Heroku, wich consist in a web process and a worker process (running django background tasks library). My Procfile looks like this: web: gunicorn search.wsgi --log-file - worker: python manage.py process_tasks I need to run a Python management command when worker starts(and not when the web process starts), to check some issues related to the daily dyno restart of Heroku. Specifically, when worker restarts, I need to run python manage.py somescript.py, and then python manage.py process_taks (the command that starts the worker as needed by DJB library). How can I achieve this? Is there any way to run two or more commands per process in the procfile? Thanks in advance! -
Style sheets refusing to load on the browser
I have downloaded an html template online. And I have gone ahead and pasted the index.html to my templates folder, and the assets to my static files, and I have placed the '{% load static %)' tag inside my index file. Here is a snippet of the index.html {% load static %} <!DOCTYPE html> <html class="no-js" lang="zxx"> <head> <meta charset="utf-8" /> <meta http-equiv="x-ua-compatible" content="ie=edge" /> <title>ClassiGrids - Classified Ads and Listing Website Template.</title> <meta name="description" content="" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="shortcut icon" type="image/x-icon" href="{% static 'assets/images/favicon.svg' %}" /> <!-- Place favicon.ico in the root directory --> <!-- Web Font --> <link href="https://fonts.googleapis.com/css2?family=Jost:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Lato&display=swap" rel="stylesheet"> <!-- ========================= CSS here ========================= --> <link rel="stylesheet" href="{% static 'assets/css/bootstrap.min.css' %}" /> <link rel="stylesheet" href="{% static 'assets/css/LineIcons.2.0.css' %}" /> <link rel="stylesheet" href="{% static 'assets/css/animate.css' %}" /> <link rel="stylesheet" href="{% static 'assets/css/tiny-slider.css' %}" /> <link rel="stylesheet" href="{% static 'assets/css/glightbox.min.css' %}" /> <link rel="stylesheet" href="{% static 'assets/css/main.css' %}" /> </head> <body> <!--[if lte IE 9]> <p class="browserupgrade"> You are using an <strong>outdated</strong> browser. Please <a href="https://browsehappy.com/">upgrade your browser</a> to improve your experience and security. </p> <![endif]--> <!-- Preloader --> <div class="preloader"> <div class="preloader-inner"> <div class="preloader-icon"> <span></span> <span></span> </div> </div> </div> <!-- /End … -
Django Quiz Application Storing User responses
I am creating a Django quiz application where there will be monthly quizzes. So suppose there will be a quiz for July and there will be a quiz for august. Now let's assume that we have a user who is named "Sovit". Now let's say each quiz has 42 questions. so I want to store each response that the user has chosen somewhere in the database. So like For the July test all 42 responses must be stored somewhere and the same again for august. Right Now I am thinking of having a JSON file associated with the user and then storing the responses of each quiz inside that. What it will help me do is get the data in JSON format for data analysis purposes . But I am not really liking this method of storing the responses. What could be wrong with this design? Is there any other method that I can try? current models : class Quiz(models.Model): id = models.AutoField(primary_key=True) quiz_name = models.CharField(max_length=500) month = models.CharField(max_length=250,null=True,blank=True) year = models.CharField(max_length=250,null=True,blank=True) def __str__(self): return self.quiz_name+"-"+str(self.month)+"-"+str(self.year) def save(self,*args,**kwargs): if not self.quiz_name: self.quiz_name = self.quiz_name+"-"+str(self.month)+"-"+str(self.year) super(Quiz,self).save(*args,**kwargs) class Question(models.Model): id = models.AutoField(primary_key=True) question = models.CharField(max_length=500) quiz = models.ForeignKey(Quiz,on_delete=models.CASCADE) month = models.CharField(max_length=250,null=True,blank=True) year … -
modify max_length models python django
I'm working on a python-django project. If a have a class where one of its attributes have max_length=100 how can I change to max_length=5000 ? for instance... Thank you! -
How do I pass a single value from a React front-end to a Django views file to use for filtering?
I'm currently trying to pass a single value (userid) from my React front-end to my Django back-end, so that I can use it for filtering in my Django views.py file, which I will then pass back to the front-end. I've been having trouble wrapping my head around this as I'm fairly new to working with APIs. My current Django code (which gives me everything I want it to): class WebRequestView(generics.ListAPIView): queryset = WebRequest.objects.filter(userid="testid") serializer_class = WebRequestSerializer Essentially I want to be able to pass the value "userid" from my React front-end so that it ends up like so: class WebRequestView(generics.ListAPIView): queryset = WebRequest.objects.filter(userid) serializer_class = WebRequestSerializer It can be hard-coded on the front-end, just not the back-end. This would work: const [userid, setUserId] = React.useState("testid"); To give more context: My Django backend is currently connected to an Oracle database. I would like to be able to filter for database entries based on the userid of the currently authenticated user, and nobody else's. I literally have no clue where to begin, or if this is even possible. I've tried things like: useEffect(() => { const requestOptions = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ userid }), }; fetch("http://127.0.0.1:8000/api/add", … -
I don't understand why I keep getting ModuleNotFoundError
I have this package, setuptools, installed on my local machine as you will in the command line code attached, but I don't understand why I keep getting the modulenotfound error. PS C:\Users\MY PC\desktop\django-polls> easy_install --version setuptools 41.2.0 from c:\users\my pc\appdata\local\programs\python\python38\lib\site-packages (Python 3.8) PS C:\Users\MY PC\desktop\django-polls> python setup.py sdist Traceback (most recent call last): File "setup.py", line 1, in <module> from setuptools import setup ModuleNotFoundError: No module named 'setuptools' PS C:\Users\MY PC\desktop\django-polls> pip install setuptools Requirement already satisfied: setuptools in c:\users\my pc\anaconda3\lib\site-packages (52.0.0.post20210125) PS C:\Users\MY PC\desktop\django-polls> python setup.py sdist Traceback (most recent call last): File "setup.py", line 1, in <module> from setuptools import setup ModuleNotFoundError: No module named 'setuptools' PS C:\Users\MY PC\desktop\django-polls> -
Compare String with another string before and after the special character using python language
I am very new to python. I have two string a="he % home now" b="he came home now" Now how to compare the string a with before and after % symbol to string b. -
How to get Django to serve static files?
I built my application in a single directory and 2 subdirectories: App Directory Django Directory Vue/Nuxt3 Directory My Django project is essentially an API built using DRF My Vue/Nuxt3 project is built as an SPA, with hardcoded endpoints for localhost:8000 I ran npm build in my Vue/Nuxt3 directory, which generated a 'public' folder. I copied this folder into the Django directory (as the same level as manage.py) I installed whitenoise on my Django project I updated settings.py with the following: MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'public'), os.path.join(BASE_DIR, 'staticfiles')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS= [ BASE_DIR / 'public', ] STATIC_URL = "static/" STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' then I ran manage.py collectstatic which seems to have generated a collectstatic folder in my django directory my urls.py file: urlpatterns = [ re_path(r'', TemplateView.as_view(template_name='index.html')), ... ] When I run manage.py runserver and navigate to localhost:8000 - I expect to see my Vue app loaded up with all it's static assets. Instead I see a white screen and get the following errors: … -
How to get lookup field names from Django queryset?
In a QuerySet, is there a way to get the field names used to filter the query? I.E., if I try queryset = Reading.objects.get(user__email="testing@example.com", site__name="site name") is there a way to get the value ["user", "site"] or ["user__email", "site__name"]? As of right now, I have [ex.lhs.field.name for ex in queryset.query.where.get_source_expressions()] which will work properly for lookups that don't span relationships. This would be sufficient if I wasn't working in a codebase littered with them. QuerySet returned names Reading.objects.get(user=User(), site=Site()) ["user", "site"] Reading.objects.get(user__email="testing@example.com", site__name="site name") ["email", "name"] -
Can I access my website from Django admin panel?
I am trying to develop a website where I can see the homepage as it is from Django admin panel. The reason I want that is I want to edit the name of the static content like 'Home' to 'All' along with the change of slide show picture. In summary, I want to change the website layout from Django admin panel that is not accessible to users. Is that possible? I just want an idea of how to implement the process. -
Unable to create process using "" once creating a virtualenvironment using python
i a trying to build a virtual environment in python to use django framework but the problem is that once i create the virtual environment i cannot use any command and the terminal display the below error Unable to create process using 'C:\Users\LT GM\AppData\Local\Programs\Python\Python310\python.exe "F:\DJANGO\venv\Scripts\pip.exe" ' I followed these steps: create folder called django run this command Python -m pip install virtualenv create the virtual environment Virtualenv venv activate the virtual environment venv\Scripts\activate it run successfully any command after the fourth step display the above error python version 3.10.4 i tried to uninstall python and re-installed again but still the same problem what am i doing wrong ? and how to fix this -
Filter a list on a table by using a information on a context field
i'm building this app that gives sales information. It's basically a page that that shows a table with products sold and the quantities in the last couple of months. It takes from the database a list of ids and then retrieves information to a list of dictionaries that each dictionary represents info about a product. products_id = ( SalesHistory.objects.filter(store=store) .values_list("product", flat=True) .distinct() ) list_prod = Product.objects.filter(id__in=products_id, **filters).values() prod_dict = [] for item in list_prod: prod_dict.append(item) for i in range(len(prod_dict)): prod_dict[i]['prod_unit'] = SalesHistory.objects.filter(product= prod_dict[i]['id']).first().umb_product prod_dict[i]['months_first']= sum_sales(3, 4, store_id, prod_dict[i]['id']) (example of the building of the context["products"] variable) {% for product in products %} <tr id="{{ product.code }}" name="{{product.code}}"> <td style="font-size:65% !important; padding: 8px 8px 8px 15px !important;" >{{ product.code }}</td> <td style="font-size:60% !important;"> {{ product.name }} <span class="badge bg-primary"> (example on how the table is built on the front end) One of this infos is a category based on an ABC curve I implemented. How can I filter the list while using the page based on this info in the context/list of products? -
is MSAL cache preserved between calls in Django
From Django I have to call a Business Central API through Active Directory Oauth2 using package msal from Microsoft. HTML -> Django -> calls API from backend -> Business Central This is an extract of my code, based on an example from microsoft docs. It works in vanilla python import msal import requests import json # GET OAUTH2 TOKEN WITH CLIENT ID/CLIENT SECRET login_url = 'https://login.microsoftonline.com/<tenant>/oauth2/token' authority = 'https://login.microsoftonline.com/<tenant>' client_id = '<client ID from AAD>' scope = ['https://api.businesscentral.dynamics.com/.default'] client_secret = '<secret from AAD' grant_type = 'client_credentials' resource = 'https://api.businesscentral.dynamics.com' app = msal.ConfidentialClientApplication( client_id, authority=authority, client_credential=client_secret, ) result = app.acquire_token_silent(scope, account=None) if not result: print("No suitable token exists in cache. Let's get a new one from AAD.") result = app.acquire_token_for_client(scopes=scope) if "access_token" in result: token = result["access_token"] # CALL A BUSINESS CENTRAL API base_url = 'https://api.businesscentral.dynamics.com/v2.0/<tenant>/Sandbox' endpoint = base_url + "/ODataV4/Company('<company name>')/<service name>" response = requests.get(endpoint, headers={'Authorization': 'Bearer ' + token},).json() Now I'm going to add this logic in an existing Django project and reading msal.ConfidentialClientApplication code I found the comment: def acquire_token_silent( self, scopes, # type: List[str] account, # type: Optional[Account] authority=None, # See get_authorization_request_url() force_refresh=False, # type: Optional[boolean] claims_challenge=None, **kwargs): """Acquire an access token for given account, without user … -
How to cache queryset results in ListAPIView when pagination, filtering, ordering enabled?
How can I cache queryset (and invalidate cache) results in ListAPIView when there is pagination, filtering and ordering possible? Note that I need to invalidate cache per company so if any new Item object is created for a specific company I need to invalidate. from rest_framework.generics import ListAPIView from rest_framework.pagination import PageNumberPagination class CustomPaginationClass(PageNumberPagination): page_size = "30" page_size_query_param = 'perPage' max_page_size = 10000 class ItemListApiView(ListAPIView): model = Item authentication_classes = (SessionAuthentication, ) serializer_class = ItemSerializer permission_classes = (HasAccessToItems, ) pagination_class = CustomPaginationClass filter_backends = (filters.SearchFilter, DjangoFilterBackend, filters.OrderingFilter, ) search_fields = ('user__name', ) filter_fields = { 'category_type__name': ['exact'], 'item_type__name': ['exact'], 'approver__name': ['exact'], 'status': ['exact', 'in'] } ordering_fields = '__all__' def get_queryset(self): qs = Item.objects.filter(company=self.request.user.company).select_related('company') if not self.request.user.is_all_items_enabled: qs = qs.filter(approver=self.request.user) return qs.order_by('-created') def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) -
What is args in Django Class Based views?
I am a novice in Django and I want to clear for myself in Class Based View - what is self.args? What it contains? I do understand self.kwargs - it's a URL-variable captured, self.request - HTTP-request params captured. But what is self.args and where it's useful? -
update many to many relation table with db orm in django
I have two tables one is boards & the second one is customers. One Customer can have multiple boards and Once board can have multiple customers. I'm using simple DB functionality for adding and updating table. In an update, I'm giving one issue. A customer can select more boards on update and unselect existing than how can manage both new and existing boards because these boards have detail on another page where adding boards detail and on the customer update page only selecting boards. if I'm removing all boards of customers on an update then also deleting boards detail that already has been added. so due to deleting the information is also deleting I want to exist and also a new one and wanto to delete which customer will unselect. This is my code customer = db.table('customers').where('id', id).first() db.table('customers').where('id', customer.id).update({ 'username': username, 'domain': domain, 'subscription_end_date': subscription_end_date, 'updated_at': datetime.datetime.now() }) customer_boards_delete = db.table('customer_boards').where('customer_id', customer .id).delete() if request.data.get('boards') is not None: for board in request.data.get('boards'): db.table('customer_boards').where('id', board['id']).where('customer_id', user.id).update({ 'name': board['name'], 'customer_id': user.id, 'board_id': board['id'], 'updated_at': datetime.datetime.now() }) Can anyone please tell me how can manage existing and new boards and delete unselected boards? Thanks -
Django. How to realize the validation for Question object?
How to realize the validation to exist at least 1 right answer and 1 wrong answer for each Question object? from django.db import models class Test(models.Model): test_name = models.CharField(max_length=255) def __str__(self): return self.test_name class Question(models.Model): test = models.ForeignKey(Test,on_delete=models.CASCADE) question_text = models.TextField() def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question,on_delete=models.CASCADE) choice_text = models.CharField(max_length=255) is_right = models.BooleanField(null=False,blank=False) def __str__(self): return self.choice_text -
How to solve the djongo.exceptions.SQLDecodeError: while trying to run the migrate command
I am creating a DjangoRestful app that uses SimpleJWT for authentication. When I try to add the Blacklist app and make migrations. i.e: py manage.py migrate as suggested in the documentation, I get the error below: raise SQLDecodeError(f'Unknown token: {tok}') djongo.exceptions.SQLDecodeError: Keyword: Unknown token: TYPE Sub SQL: None FAILED SQL: ('ALTER TABLE "token_blacklist_blacklistedtoken" ALTER COLUMN "id" TYPE long',) Params: ([],) Version: 1.3.6 I should also mention I am using MongoDB as my database. Here is my installed apps list: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_simplejwt.token_blacklist', 'drf_yasg', 'main', 'accounts', ] When I remove the app from the installed apps and run the command, there is no error. Anyone knows how to fix this? -
DJANGO: How to write and run the unit tests?
Whenever I run my unit tests, I use this command python manage.py test, but my tests are not running, I get the following message: System check identified 1 issue (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK NOTE: I am using MySQL Database instead of the default SQLite. Does this have to do anything with the unit tests anyway? I have following hierarchy of my project files and folders: --[PROJECT-NAME] ------apps ----------[APP-NAME] --------------migrations --------------templates --------------models.py --------------test.py --------------urls.py --------------views.py ------[PROJECT-NAME] ----------settings.py ----------urls.py ------manage.py And this is my tests.py file from django.test import TestCase from apps.accounts.models import User, Invitation class TestModels(TestCase): def test_sending_password_reset_email(self): user = User.objects.create( login = "testuser@test.com", email = "testuser@test.com", password = "TestPassword1!" ) email_sent = user.send_password_reset_email() self.assertTrue(email_sent) def test_accepting_invitation(self): user = User.objects.create( login = "testuser@test.com", email = "testuser@test.com", password = "TestPassword1!" ) invitation = Invitation.objects.create(created_by = user) accepted = invitation.accept(user, "testinguser@test.com", "TestingPassword1!") self.assertTrue(accepted) def test_cancelling_invitation(self): user = User.objects.create( login = "testuser@test.com", email = "testuser@test.com", password = "TestPassword1!" ) invitation = Invitation.objects.create(created_by = user) invitation.cancel() self.assertTrue(invitation.is_canceled) def test_sending_invite_user_email(self): user = User.objects.create( login = "testuser@test.com", email = "testuser@test.com", password = "TestPassword1!" ) invitation = Invitation.objects.create(created_by = user) message = invitation.send_invite_user_email() self.assertEqual(message, "Success") and these are the function signatures in my … -
Django dynamic url arguements missing
Can someone spot the mistake? What i'm expecting to happen is to dynamically pass in the ids of the classes I have created, so that I can update an entry I created in a previous form. Here is my HTML: <td><a class="btn btn-sm btn-info" href="{% url 'update_type_4_service' type_4_service.order_reference.id type_4_service.id %}>Update</a></td> Here is my urls: path('order/<str:pk_test>/update_type_4_service/<str:pk>', views.updateType_4_Service, name="update_type_4_service"), Here is my views: def addType_4_Service(request, pk_test): order = Order.objects.get(id=pk_test) type_4_service_form = Type_4_ServiceForm(order_reference=order) if request.method == 'POST': type_4_service_form = Type_4_ServiceForm(request.POST, order_reference=order) type_4_service_form.instance.order_reference = order if type_4_service_form.is_valid(): type_4_service_form.save() return redirect('/') context = {'type_4_service_form':type_4_service_form} return render(request, 'orchestration/type_4_service_form.html', context) This is the error: Reverse for 'update_type_4_service' with arguments '('', '')' not found. 1 pattern(s) tried: ['order/(?P<pk_test>[^/]+)/update_type_4_service/(?P<pk>[^/]+)\\Z'] -
Filter Django Admin by custom function return value
Given the following models: Profile Book Campaign The following relationships: A Profile has many Books A Book can be in many Campaigns The following Django Admin model has a custom function which fetches all the Campaigns a Book is in: @admin.register(Book) class BookAdmin(admin.ModelAdmin): @admin.display(description="Running Campaigns") def get_campaign_count(self, obj): book_campaigns_db_count = Campaign.objects.filter(asins__contains=[obj.asin]).count() return book_campaigns_db_count list_display = ["title","format","asin","get_campaign_count"] list_filter = ["profile__nickname", "format"] This is a simplified version of the model but has all the necessary parts for this question. Note: the database is PostgreSQL and the asins field is an ArrayField. Question: I would like to filter and show only Books which have >0 running campaigns. Please advise on how to achieve this. -
Django Infrastructure
I am wondering on the best way to achieve this. Basically, I have built and inventory management system for small business owners (this is more a side project). My question is, is if I were to have multiple users sign up so that they can create their own inventory management portal, how would I achieve this? Right now, I sign up and database info is visible to all auth users. But how can I make it to where users can sign up and they will get their own portal? So if multiple users sign up, they will each have their own for their business. Thanks! -
How to import Wagtail ModelAdmin index page into a template
I created a new AdminModel as follows: class OneModelAdmin(MyModelAdmin): model = SomeModel menu_label = 'One' edit_view_class = OneEditView edit_template_name = '.../one-edit.html' index_view_class = OneIndexView index_template_name = '...' class TwoModelAdmin(MyModelAdmin): model = SomeOtherModel menu_label = 'Two' edit_view_class = TwoEditView edit_template_name = '.../two-edit.html' index_view_class = TwoIndexView index_template_name = '...' How can I import the TwoModelAdmin index view inside the OneModelAdmin edit template? -
How to structure the templates folder in django and to use the extends
I have a folder, templates, structured like below /Users/AndyKw/Documents/Python/Else/Yes/templates Within templates, I have two folders, admin and registration (see below for the tree) templates (need.html) | |-- admin | |-- registration (base.html) The file I use base.htmlis in the folder registration. It needs to use a file , need.html in the folder templates with the extends command. Question is the following: How do I configure in the settings.py the templates parameter to use registration as the main folder and through base.html to reach by using extends the file need.html in the templates folder? One possible solution would be to invert the path, put need.html in the registration folder and put the base.html in the templates folder but the dev team seems to be quite unbending on this solution, this would be the less favourable way. Any ideas/tips are welcomed. -
How to order queryset while keeping objects grouped by other field?
I have a model with two fields date and type class Obj(Model): date = DateTimeField type = ChoiceField I want to order them by their creation date but I want the same type objects to stick together OBJECT: 01.01.2022 BLUE 02.01.2022 BLACK 03.01.2022 BLUE 04.01.2022 GREEN 05.01.2022 BLUE 06.01.2022 BLACK 07.01.2022 GREEN When I order I want it to look at the date first, get the latest date, then take all the objects with that object's type and put them into order keeping the date order amongst them, and then it will take the second type's next date and put them into the order after the previous one: ORDERED: 07.01.2022 GREEN 04.01.2022 GREEN 06.01.2022 BLACK 02.01.2022 BLACK 05.01.2022 BLUE 03.01.2022 BLUE 01.01.2022 BLUE So what I want is basically order_by title first, and then order the groups by date Can I do this trivially or do I have to go Case When or maybe even raw SQL It would be best if I can avoid raw SQL because this is paginated