Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Search for advice | Using a few tables from an external database?
I'm currently working on a small app to evaluate and also modify some tables from an external mysql db, without changing you original DB, to create a report. For example, one of the columns is a subject. Sometimes it is necessary to modify and change the subject, since the ppl. Wrote it wrong, and I want to have it differently in my report. But i don't want to save this to the original db. It should be only changed for my app. The possibilities I have thought of so far are: synchronize the whole Mysql DB into a second DB and then re-sync regularly, but that would mean that I also sync the unnecessary tables. select only the tables that I need and then create a Django model and fill it with the Table data, after that, only getting the new lines in the table and add them to my Django DB with the model Are there any other possibilities that might be better, or would my variants lead to problems? Currently, I would decide for variant two, because I create an independent DB. Thank you -
How would I stop a browser page from refreshing automatically infinite times?
The browser page reloads continuously infinite times when I perform the post method and for each reload, the same data is automatically added to the database continuously unlimited times. The HTML code run from VSCode. When I run the HTML file without any server(by clicking the HTML file in any browser manually) it works fine(the browser page reloads one time). Please help me to solve this issue. This JavaScript code is to perform the POST method to post data to the database. -
Why my defined custome model manager not working
I defined a custome django manager inheriting Model by overriding queryset.Then i hooked mu custome manager in my model.But it is not working. class MyManager(models.Model): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter(is_active=True) my model class Product(models.Model): product_type = models.ForeignKey(ProductType, on_delete=models.PROTECT, related_name='products') upc = models.BigIntegerField(unique=True) title = models.CharField(max_length=32) description = models.TextField(blank=True) category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name='products') brand = models.ForeignKey(Brand, on_delete=models.PROTECT, related_name='products') is_active = models.BooleanField(default=False) # default_manager = models.Manager() objects = MyManager() -
pytest for function as an argument
I was writing a test using pytest library where I need to test a method which takes another method as an argument. class Certificate: def upload(self, upload_fn: Callable): try: if self.file_name: upload_fn(self.file_name) return raise ValueError("File name doesn't exist") except Exception as e: raise e Now I created a dummy mock function which I am passing while calling upload method but I am not sure how do I make sure if the upload_fn is called. I am trying to achieve something like this def test_certificate_upload(certificate): certificate.upload(some_mock_fn) assert some_mock_fn.called_once() == True -
Override RetrieveUpdateAPIView Django Rest Framework
Right now I'm overriding the whole retrieve and update function. I want to override only that part, it does not ask for the pk value. Thanks View.py class EmployeeView(generics.RetrieveUpdateAPIView): permission_classes = [EmployeePermission] serializer_class = EmployeeSerializers def retrieve(self, request, *args, **kwargs): employee = Employee.objects.get(user=self.request.user) serializer = EmployeeSerializers(employee) return Response(serializer.data) def update(self, request, *args, **kwargs): employee_user = Employee.objects.get(user=self.request.user) serializer = EmployeeSerializers(employee_user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)strong text urls.py path('viewEmployee/', views.EmployeeView.as_view()),