Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter a query with a string ignoring it's lowercase or uppercase?
I want to create a query for filtering with an input. It's working but I want to filter by ignoring lower or capital cases. For example: input> test --> output listing but when I enter input> Test -->no output I want to get output in any cases. Here is my query alerts = Event.objects.filter(process_type__reporting_group__option__contains=group_search_bar) -
Django: Adding Item to specific list (One page Django list app)
I am trying to make a To-Do list app with Django. My current app webpage: My App page I am showing all the lists on one page, including their list items. I have made a form to make a new list, I have added buttons to delete the lists and their items. So, the final challenge to is add a form to create a new list item for a specific list. I am trying to use the same method as I did for creating a new list, i.e., use a Meta form. My problem: I want to add an item which is specific to the list it is in i.e., the list that the form text box falls under (see webpage again here: My App page) but I am having trouble with this because I don't know how to tell Django that I want to add that item to a specific list. In other words I don't know to add an item to a specify list.id. If anyone could help me, I would much appreciate it <3 The current code for my forms, models, views and index are as follows: models.py from typing_extensions import Required from django.db import models class … -
Get multiple postgresql function returned cursors from Django
I'm new to django and not able to figure out if it is possible to retrieve multiple cursors returned by a postgresql function. I've been searching the net for hours now and haven't been able to find a single example. I plan to write raw sql from django (no ORM) to call the postgresql functions. Anyone to enlight me? Thanks -
How to write a Graphene+Django filter that acts upon two columns at the same time
I am trying to write a filter in Graphene + Django that takes a single input but acts upon two columns at the same time. The two columns represent two numbers a and b, and the filter I want is one that select all element where the product of a and b is greater that some filter value. class MyModel(models.Model): a = models.FloatField() b = models.FloatField() class MultiplicationFilter(Filter): def filter(self, qs, value): # what to do here??? class MyModelCustomFilter(FilterSet): class Meta: model = MyModel multiplication_filter = MultiplicationFilter(field_name=???) # I can't have 2 fields, what do I put here? order_by = OrderingFilter( fields=("a", 'b'), ) class MyModelNode(DjangoObjectType): class Meta: model = MyModel fields = "__all__" filterset_class = MyModelCustomFilter interfaces = (graphene.relay.Node, ) I am aware that Django offers so more elaborate querying functionality by means of a Q() function, but I don't know how to formulate this in the Graphene Filter type of way. -
How to check if which radio button is selected using django
I have 5 radio buttons and each have different values but as user can only select 1 option out of 5 and after selecting the value of radio button should be stored in my django models. This is my html code <div class="col"> <div class="form-group"> <input class="form-check-input" type="radio" name="reason" id="reason1" checked> <label class="form-check-label" for="reason1"> Casual Leave </label> </div> <div class="form-group"> <input class="form-check-input" type="radio" name="reason" id="reason2"> <label class="form-check-label" for="reason2"> Medical Leave </label> </div> <div class="form-group"> <input class="form-check-input" type="radio" name="reason" id="reason3"> <label class="form-check-label" for="reason3"> Earned Leave </label> </div> <div class="form-group"> <input class="form-check-input" type="radio" name="reason" id="reason4"> <label class="form-check-label" for="reason4"> Office Duty </label> </div> <div class="form-group"> <input class="form-check-input" type="radio" name="reason" id="reason5"> <label class="form-check-label" for="reason5"> Compensatory Off </label> </div> </div> *this code contains form tag My Django function def leaveapplicationsubmit(request): if request.method == 'POST': reason1 = request.POST['reason1'] reason2 = request.POST['reason2'] reason3 = request.POST['reason3'] reason4 = request.POST['reason4'] reason5 = request.POST['reason5'] if 'reason1' in request.POST: reason = "Casual Leave" elif 'reason2' in request.POST: reason="Medical Leave" elif 'reason3' in request.POST: reason="Earned Leave" elif 'reason4' in request.POST: reason="Office Duty" elif 'reason5' in request.POST: reason="Compensatory Off" else: return HttpResponse('Please select the reason') else: return HttpResponse("Failed") Please help me with it, I really need that -
Django command makemessages does not generate string marked for translations for files in templates directory
I have project in Django==2.2.12 and this is part of my settings: TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, "templates")], "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", "django.template.context_processors.static", ], }, }, ] LANGUAGE_CODE = "pl" TIME_ZONE = "Europe/Warsaw" USE_I18N = True USE_L10N = True USE_TZ = False LANGUAGES = ( ('pl', gettext('Polish')), ('en', gettext('English')), ) When I execute: django-admin makemessages --locale=en It generates .po files with string to translate in locale directory from .py files but it completly skips .txt files that are located in my templates directory. For example it does not generate string for translation for my text.txt file with following content: {% load i18n %} {% blocktranslate %} string to translate {% endblocktranslate %} -
is there any way to access the python list variable inside jinja with the for loop(in jinja) in Djnago?
<tr> {%for i in desc %} <td>{{desc[i]}}</td> {%endfor%} </tr> I get this result when i run above code -
How to pass values from views.py to html template?
My views.py is: def result(request): countries = ["nepal", "india", "bhutan"] rand_country = random.choice(countries) return render(request,'result.html',{ 'rand':rand_country} ) I'm trying to access rand_counrty from Html template by using following code : <form action="check"> <h1> What is the capital city of {{ rand }}</h1> your input: <input type="text" name="text1"><br> <input type="submit"> </form> But {{rand}} doesn't return any value , How do i solve this ? Thanks -
Django queryset returning items that it shouldn't return
I'm using a queryset that is assisted by a serializer in Django RestApi to return a list of names that are in particular fields of certain tables. "DataSourceIdUnique" is the model common to all others via Foreign Key and is used to build the queryset. Here's the API view: class ProfileAPI(generics.ListAPIView): filter_backends = (DynamicSearchFilter,) def get_queryset(self): queryset = DataSourceIdUnique.objects.all().prefetch_related( "address", "data", "name", "list", "iddata" ) name_type = self.request.query_params.getlist("nametype", []) country_type = self.request.query_params.getlist("countrytype", []) id_type = self.request.query_params.getlist("idtype", []) policy_code = self.request.query_params.getlist("policy_code", []) user = self.request.user group_id = self.request.user.groups.all() if name_type != []: queryset = queryset.filter(name__name_type__in=name_type) print(name_type) if country_type != []: queryset = queryset.filter(address__address_type__in=country_type) if id_type != []: queryset = queryset.filter(iddata__doc_id_type__in=id_type) if policy_code != []: group_id = user.groups.all().values_list("id", flat=True) queryset = queryset.filter(data__policy_code__policy_name__in=policy_code) queryset = queryset.filter( data__policy_code__associated_user_groups__in=group_id ) return queryset serializer_class = DataSerializer and here's the serializer that is used: class DataSerializer(serializers.ModelSerializer): class Meta: model = DataSourceIdUnique depth = 2 fields = [ "data_source_id", "data", "address", "iddata", "list", "name", ] When I inspect the representations by using python manage.py shell and running: >>> from data_viewer.serializers import DataSerializer >>> serializer = DataSerializer() >>> print(repr(serializer)) everything checks out. ALL the relevant fields are available and can be filtered into. >>> print(repr(serializer)) DataSerializer(): data_source_id = CharField(max_length=45, … -
Using python dictionaries in a django template
I'm learning django by myself and as you can imagine it's quite difficult. I was trying to make a self-adapting form in a view. The app has a model where are stored all the infos about the form (like the placeholder, id and type of the input fields) via JSON (if there's an easier or smarter way I think it'll be better). So, in the views file I've passed to the template (picture below) 2 variables which refer to the dict from the object in the picture above. So, now my scope is to extract the values from the keys "inputType" and "placeholder" in a for statement in the template, in order to insert them into the html file. With the method above I obviously cannot retrieve anything, but I'm not able to resolve this problem. This is the view by the way (it is an example, that's why it has only two fields): -
Any alternative to Heroku that allows timeout of more than 30 secs?
I am developing a web-scrapping Django app using selenium that finds valid credentials for my University CMS users. As it relies heavily on internet speed, the request can take up to 5 minutes to execute on the server and return some data to the user. The problem is that many web servers, e.g. Heroku, only allow a timeout of 30 seconds, and if the request doesn't execute within the time limit, it returns an error. So is there any way to bypass the timeout ceiling or any alternate webserver that doesn't have this type of restriction? -
React and Django CORS header ‘Access-Control-Allow-Origin’ missing
I have a React frontend app that needs to send a request to my Backend written in Django But I'm getting some CORS problems, more specificly, CORS header ‘Access-Control-Allow-Origin is missing. I found a lot of questions on stackoverflow on how you need to install django-cors-headers but it simply doesn't work for me. my current backend configuration: settings.py INSTALLED_APPS = [ ..., "corsheaders", ..., ] MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'simple_history.middleware.HistoryRequestMiddleware', ] ALLOWED_HOSTS = ["*"] CORS_ALLOWED_ORIGINS = ["http://localhost:3000"] CSRF_TRUSTED_ORIGINS = ["http://localhost:3000"] CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", ] views.py (where I create the api) @csrf_exempt @api_view(["POST"]) @permission_classes([AllowAny]) @xframe_options_exempt def create_user_and_ci(request): try: # code to execute return Response({"status": "Succes"}, status.HTTP_200_OK) except: return Response({"status": "Error"}, status.HTTP_500_INTERNAL_SERVER_ERROR) And then on my frontend i execute this: fetch(`https://myexampledomain.com/ci/get/${est}`, { headers: { Authorization: `Token ${localStorage.getItem("token")}`, 'Content-Type': 'application/json' }, }).then((res) => console.log(res)) -
Django: How to use the contents of a table cell inside a tamplate as data for another template
I am creating a reporting site for software distribution within my company. I am currently focused on reporting packages that have been corrupted. I was able to create a report showing a table of corrupted packages. The first column of the table lists the package name as a link to a rep_violate.html page but I would like the package name to be used in the new page (rep_violate.html) as a key for a query. Note: All queries are made on an external database and not on a Django internal model Table example Here my the views.py: ... from django.shortcuts import render, redirect from django.http import HttpResponse, request from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.db.models import ObjectDoesNotExist import psycopg2 from datetime import datetime, timedelta import locale ... def get_violations(request): violations_context = { 'Current_Year': current_year, 'Yesterday': Yesterday_Date, 'Yesterday_Violations': yesterday_violations, 'Violations_per_Month': violations_per_month, } return render(request, "violations.html", violations_context) ... Here my urla.py: urlpatterns = [ path('admin/', admin.site.urls), path("", home_views.homepage, name="homepage" ), path("index.html", home_views.homepage, name="homepage" ), path("violations.html", home_views.get_violations, name="violations"), ] Here my template violations.html: <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Package</th> <th>Versione</th> <th>Data Rilevamento Violazione</th> </tr> </thead> <tfoot> <tr> <th>Package</th> <th>Versione</th> <th>Data Rilevamento Violazione</th> … -
Why a request for a field value in a database table inside docker container returns empty value?
I need to connect to a postgres database and view the contents of one of the tables. No problem to connect, I do it this way sudo docker-compose exec db psql -p 5432 -d gpanel_db -U db_root where db - service name in docker-compose file gpanel_db - DB name db_root - DB user Connecting to DB use gpanel_db Show tables gpanel_db=# \dt List of relations Schema | Name | Type | Owner --------+------------------------------------------+-------+--------- public | auth_group | table | db_root public | auth_group_permissions | table | db_root public | auth_permission | table | db_root public | auth_user | table | db_root public | auth_user_groups | table | db_root public | auth_user_user_permissions | table | db_root public | creative_performer_creativecategory | table | db_root public | creative_performer_creativestatushistory | table | db_root public | creative_performer_creativetag | table | db_root public | creative_performer_creativetype | table | db_root public | creative_performer_googlecreative | table | db_root public | creative_performer_googlecreativespend | table | db_root public | creative_performer_playablecreativesize | table | db_root public | creative_performer_tag | table | db_root public | creative_performer_videocreativeduration | table | db_root public | django_admin_log | table | db_root public | django_content_type | table | db_root public | django_migrations | table | db_root public … -
How to show on a form, values you add on Django Admin?
I am struggling with showing new values I add through django-admin, I am adding years on the model and then I want to show them on a form, the problem is on the value="" within the form, it gives values like: 1, 2, 3... But I want to get the values I write (2010, 2011, 2012). My Model: class MyYear(models.Model): year = models.IntegerField() class Meta: verbose_name = 'XXX' def __str__(self) -> str: return f'{self.year}' def my_year(self): return self.year.value -
Can't find/load sub module inside django app(module) dynamically
i have django project where i added app called Employee and employee has following modules (files). and i have some requirement where i want to load number of module dynamically where variables has! so for the test purpose i just loading employee module using __import__ method In [21]: __import__("Employee") Out[21]: <module 'Employee' from '/home/dev/projects/lab/rule-engine-django/RuleEnginePoc/Employee/__init__.py'> In [22]: hasattr(app, "variables") # defined by me Out[22]: False In [23]: hasattr(app, "models") # created while creating employee app Out[23]: True through the app i can only access some sub-module not all. why I'm not able to access custom defined sub-module(file)? And one more thing i just checked output of dir(app) but at there, also some of sub-module is missing(Please compare output with above image). In [26]: dir(app) Out[26]: ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'admin', 'apps', 'models'] Here at the end, you can see only three sub-module other are still missing. And my init.py is empty!! there are no any data there. -
Move some code from GenericAPIView post method to other methods in django
I have my django GenericAPIView with post method, I want some part of the logic which uses self to be in some other method and exccute that code when my post method gets hit class MyAPIView(models.Model): def post(self, request, *args, **kwargs): -
How to use multiple for in template to get elements from object in django
I am passing below variables from backend. I want to get values dynamically. num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] answers = [ {'date': datetime.date(2022, 8, 26), 1: 100.0, 2: 50.0, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}, {'date': datetime.date(2022, 8, 27), 1: 100.0, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None} ] In my template I used: {% for i in answers %} <tr> <td>{{i.date}}</td> {% for j in num_list %} <td>{{i.j}}</td> {% endfor %} </tr> {% endfor %} Using the above code in templates is not giving me the output, it just displays empty. but if type manually it works. <td>{{i.1}}</td> <td>{{i.2}}</td> . . <td>{{i.9}}</td> Any Solution to solve this? -
Authenticate user and get info about it with AWS Cognito and Django
I need to use Amazon Cognito to register and login my users. Info about users stored at User Pools. I want to authenticate users and provide some part of my app only for them (for authenticated users). And also i want additionally stored users profiles at my own database. How best to authenticate users: maybe frontend should send me access token or smth else or maybe i should do another things? And how to get users info(email, gender, date of birth...)? I look through boto3, but can't understand is it normal way to use this SDK for getting users info or nor? -
How to read query parameter after (hash)#
Here I have Url http://127.0.0.1:8000/accounts/google/login/callback/#access_token=ya29.a0AVA9y1tO4d94lkiHbIT2qjh89k0TNGXFMJ_6XzdHXvxLrsLbphuMaBmEvUHCSX8XWq5L3dqQ88ULG9Vsw1llmYi24DpbFamGcoW4KPZP-9y2ynPBJMqmuFdazz7t9KEp5qrdkVwvaCgYKATASAQASFQE65dr8nbFmeih28Lvt_Q68CBXhiQ0163 I want to get value of access_token and return that token as response mention below but don't know the way to get query_parameter after hash(#) { "token":'ya29.a0AVA9y1tO4d94lkiHbIT2qjh89k0TNGXFMJ_6XzdHXvxLrsLbphuMaBmEvUHCSX8XWq5L3dqQ88ULG9Vsw1llmYi24DpbFamGcoW4KPZP-9y2ynPBJMqmuFdazz7t9KEp5qrdkVwvaCgYKATASAQASFQE65dr8nbFmeih28Lvt_Q68CBXhiQ0163' } in urls.py from user.views import GoogleRedirect path('accounts/google/login/callback/', GoogleRedirect.as_view()) in views.py class GoogleRedirect(APIView): def get(self, request): return Response("success") -
How to embed xlsxwriter workbook in django web portal?
I am trying to embed xlsxwriter workbook in django web portal.I have created a workbook using xlsxwriter. But I do not have any idea to embed it in the web page. from io import BytesIO as IO import xlsxwriter from django.http import HttpResponse def export_page(request): excel_file = IO() workbook = xlsxwriter.Workbook(excel_file, {'in_memory': True}) worksheet = workbook.add_worksheet() worksheet.write('A1', 'Some Data') workbook.close() excel_file.seek(0) response = HttpResponse(excel_file.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename="Report.xlsx"' return response Here I am using Django.Can anyone suggest a solution to solve this issue? -
Alternative to hardcoding urlpatterns in django
I am making a django website in which the homepage shows links of domains... upon clicking on each domain, you links of respective topics and upon clicking each topic you get links of respective subtopics... The problem is that I want to extract the domains, topics, and subtopics from database using queries... which means that I cannot hardcode urlpatterns into my program... How can I make this work so that in the homepage, I extract the list of domains... display them... and upon clicking them, extract the list of topics under them and display them on a new link... -
I want Staffuser in Django not to see any superusers
Right now i have applied this code from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User class MyUserAdmin(UserAdmin): def get_fieldsets(self,request,obj=None): if not obj: return self.add_fieldsets if request.user.is_superuser: perm_fields = ('is_active','is_staff','is_superuser','groups','user_permissions') return [(None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('first_name', 'last_name')}), ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), ('Important dates', {'fields': ('last_login', 'date_joined')}), ('Contact info', {'fields': ('contact_no',)})] else: perm_fields = ('is_active','is_staff') return [(('Creds'),{'fields':('username','password')}), (('Personal info'),{'fields':('first_name','last_name','email')})] admin.site.unregister(User) admin.site.register(User,MyUserAdmin) Here all the staff user are able to see superuser when i am logged in as staffuser But I want that the staffuser wont be able to see any superuser. so in this case staffuser can only view 1 user which is "new" and "admin" user which is superuser, should be hidden How can i do that ? -
Pagination Ajax Django
I get the data through the search and display it on the page, since there is a lot of data, I want to implement pagination via Ajax. But when you click on the pagination, everything disappears and the data is not updated. If Ajax is turned off, then everything works, but there is a transition to the page (search/?page=2), which immediately removes all search results. Please help, what am I doing wrong? def search_venus(request): if request.method == "GET": searched = request.GET.get('searched', False) p = Paginator(Movie.objects.filter(title__contains=searched), 1) page = request.GET.get('page') object_list = p.get_page(page) coursesearch = Course.objects.filter(name__contains=searched) context = { 'searched':searched, 'object_list':object_list, 'coursesearch':coursesearch, } return render(request, 'search.html', context) Ajax function ajaxPagination_s_m() { $('#pagination_s_movie a.page-link').each((index, el) => { $(el).click((e) => { e.preventDefault() let page_url = $(el).attr('href') console.log(page_url) $.ajax({ url: page_url, type: 'GET', csrfmiddlewaretoken: '{{ csrf_token }}', success: (data) => { $('#search_movie').empty() $('#search_movie').append($(data).find('#search_movie').html()) $('#pagination_s_movie').empty() $('#pagination_s_movie').append($(data).filter('#pagination_s_movie').html()) } }) }) }) Form search <div class="form_search"> <form action="{% url 'search-venus' %}" method=GET> {% csrf_token %} <input class="inp_text" name="searched" type="search" placeholder="Схемы, видео, книги"> <button type="submit"></button> </form> </div> -
move post method logic to seperate method in GenericAPIView
I have GenericAPIView i want to move some part of post method logic into seperate method and i want that method to run when the request gets into post method how can i do that. Class MyApiView(GenericAPIView): def post(self, request, *args, **kwargs): if self.something and self.something.something: i want if self.something and self.something.something: logic to be in a separate function and should be able run the logic when post method is hit how can i achieve this