Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tailwind - Div not taking up full height of screen
I am creating a simple login form using tailwind.css. I want the form to take up the full height of the screen, but for some reason, it doesn't and leaves white space at the bottom: I don't understand why this is happening, but I think it has something to do with the second div, which has the lg:w-1/2 property. Here is my HTML code (I'm including all of it, just in case my issue has is being caused by another HTML element): <div class="" id="content"> <section class="relative bg-white overflow-hidden"> <div class=> <nav class="flex justify-between p-6 px-4" data-config-id="toggle-mobile" data-config-target=".navbar-menu" data-config-class="hidden" style="background-color: #2A3342 !important;"> <div class="flex justify-between items-center w-full"> <div class="w-1/2 xl:w-1/3"> <a class="block max-w-max" href="{% url 'home' %}"> <img class="h-8" src="https://i.ibb.co/LRCrLTF/Screenshot-2022-04-03-140946-removebg-preview.png" alt="LOGO" data-config-id="auto-img-1-2" style="transform: scale(2); padding-left: 30px"> </a> </div> <div class="w-1/2 xl:w-1/3"> <ul class="text-slate-400hidden xl:flex xl:justify-center"> <li class="mr-12"><a class="text-slate-400 font-medium hover:text-white transition ease-in-out delay-150" href="#" data-config-id="auto-txt-1-2" style=" font-size: 18px">About</a></li> <li class="mr-12"><a class=" text-slate-400 font-medium hover:text-white transition ease-in-out delay-150" href="{% url 'classes' %}" data-config-id="auto-txt-2-2" style=" font-size: 18px">Classes</a></li> <li class="mr-12"><a class=" hover:text-white font-medium text-slate-400 transition ease-in-out delay-150" href="{% url 'resources' %}" data-config-id="auto-txt-3-2" style=" font-size: 18px">Resources</a> </li> <li><a class=" hover:text-white font-medium text-slate-400 transition ease-in-out delay-150" href="#" data-config-id="auto-txt-4-2" style=" font-size: 18px" id = "responsivehide">Upcoming</a></li> </ul> … -
Django + APP ENGINE (GAE) - No local .env or GOOGLE_CLOUD_PROJECT detected. No secrets found
i want to deploy in App Engine a Django app. I created and configurate a SECRET MANAGER in GAE and when i want to get that secret from my SETTINGS.PY, it display the error 'No local .env or GOOGLE_CLOUD_PROJECT detected. No secrets found'. If i create the .env locally it works, but i want to get the secret info from the GAE. SETTING.PY env_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(env_file): # Use a local secret file, if provided env.read_env(env_file) # ... elif os.environ.get("GOOGLE_CLOUD_PROJECT", None): # Pull secrets from Secret Manager project_id = os.environ.get("GOOGLE_CLOUD_PROJECT") client = secretmanager.SecretManagerServiceClient() settings_name = os.environ.get("SETTINGS_NAME", "secret-django-phi") name = f"projects/{project_id}/secrets/{settings_name}/versions/latest" payload = client.access_secret_version(name=name).payload.data.decode("UTF-8") env.read_env(io.StringIO(payload)) else: raise Exception("No local .env or GOOGLE_CLOUD_PROJECT detected. No secrets found.") REQUIREMENTS.txt google-cloud-secret-manager==1.0.0 django-environ==0.4.5 SECRET MANAGER that i upload on GAE like an .env file db_ip=x db_name=x db_user=x db_pass=x SECRET_KEY=*a lot of characters* -
Django REST Framework reverse() not finding match for router's "{basename}-detail"
This question is extremely similar to: How to fix this NoReverseMatch exception in Django rest frameworks routers? but that hasn't been answered/resolved and after a lot of investigating here I am looking for help. I am trying to build an API with test-driven development. As common practice I begin my tests by saving constant variables for the URLS using django.urls.reverse() The problem is reverse('{app}:{basename}-list') works fine, but reverse('{app}:{basename}-detail') throws the exception: django.urls.exceptions.NoReverseMatch: Reverse for 'designer-detail' with no arguments not found. 2 pattern(s) tried: ['api/design/designer/(?P<pk>[^/.]+)\\.(?P<format>[a-z0-9]+)/?$', 'api/design/designer/(?P<pk>[^/.]+)/$'] My test.py: (notice the list url runs first and throws no exception) from rest_framework.test import APITestCase, APIClient from django.contrib.auth import get_user_model from rest_framework_simplejwt.tokens import RefreshToken from django.urls import reverse from rest_framework import status from designs.models import Designer from designs.serializers import DesignerSerializer DESIGNER_LIST_URL = reverse('designs:designer-list') DESIGNER_DETAIL_URL = reverse('designs:designer-detail') My app/urls.py: from rest_framework.routers import DefaultRouter from designs.views import DesignerViewset app_name = 'designs' router = DefaultRouter() router.register(r'designer', DesignerViewset, 'designer') urlpatterns = router.urls My project/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/user/', include('user.urls')), path('api/design/', include('designs.urls')) ] My serializers.py: from rest_framework import serializers from designs.models import Designer class DesignerSerializer(serializers.ModelSerializer): """ Model serializer for Designer. """ class Meta: model = Designer fields = … -
Please someone tell how can I run this (https://github.com/kaan0nder/ceng-407-408-2019-2020-Movie-Recommendation-System) project locally on my system
Please someone tell how can I run this (https://github.com/kaan0nde/ceng-407-408-2019-2020-Movie-Recommendation-System) project locally on my system project locally on my system -
Running Django on Google Colab
I was trying to run the Django on Colab, by following the instruction here, however, after the !python manage.py runserver step, I tried to access the server using Google Colab link you printed by running the eval_js method earlier. there is a error msg: This page isn’t working0yztv6fmakbj-496ff2e9c6d22116-8000-colab.googleusercontent.com is currently unable to handle this request. HTTP ERROR 500 then I tried to access the link http://127.0.0.1:8000/, and it appears error msg as follows This page isn’t working127.0.0.1 didn’t send any data. May I ask how to fix this? If this is not the way to run Django in Colab, what should I do? and every time I run !python manage.py runserver, it keeps executing the Performing system checks... Is that normal? Thanks in advanced. -
How to display image here
Hi there, how can i display image here(its example place on the photo but it will be nice if i can put image here) from field Image but not after saving but live(when i paste url then display preview). I dont have any idea how to do that so the last thing is to write a question here. -
What should my nested URLs look like in REST API?
Let's say that I have Books and Authors. I want to be able to get all the Books for a specified Author. What should my URL look like? I have 2 possible ways, which are: localhost:8000/api/books?author=3 localhost:8000/api/authors/3/books I would also need to retrieve specific books, relating to a specific author. So localhost:8000/api/books/5?author=3 and localhost:8000/api/authors/3/books/5 should only work if the Book 5 was written by Author 3. I noticed that old school developers seem to prefer the first one, while new developers (as well as new companies during interviews) seem to favor the 2nd one. My framework is Django and I'm using DRF, but I think my question is not restricted to Django. If you think RESTful restricts things like this too much, I'd still be interested in your answer in a RESTless way of thinking. -
CS50W lecture7 testing,CI/CD--a problem about YAML and GitHub Actions
I am taking CS50’s Web Programming with Python and JavaScript(CS50W) course. I am now having a problem for lecture 7 Testing, CI/CD. When I followed along Brian in the GitHub Actions section(Timestamp at about 1:13:36), the result in my GitHub Actions turned out not to be the same with his. This is the yaml code( I exactly copied from the lecture) : name: Testing on: push jobs: test_project: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Run Django unit tests run: pip3 install --user django python manage.py test In his GitHub Actions there was nothing wrong about the "run django unit tests" part. But Mine turned out to have some errors. My result in GitHub Actions showed as this: Run pip3 install --user django python manage.py test pip3 install --user django python manage.py test shell: /usr/bin/bash -e {0} Collecting django Downloading Django-4.0.3-py3-none-any.whl (8.0 MB) ERROR: Could not find a version that satisfies the requirement python (from versions: none) ERROR: No matching distribution found for python Error: Process completed with exit code 1. So I thought there was something wrong for setting up django or python in the GitHub Ubuntu virtual machine, then I tried to get rid of the python … -
Django Tables2 - Format cell based on value from another cell - Blank values causing issues
I'm using Django Tables2. My goal is to highlight a specific table cell based on the value of another field. I've implemented a solution using render_foo methods (similar to the solution for this post). I have a Team_Leader Column and I would like it to be highlighted if New_Team_Leader is True (signifying that the Team_Leader has changed). It's working for the most part, except if the Team_Leader is left blank. When the Team_Leader is blank, the cell accepts the formatting from the previous row. Here is my code: tables.py import django_tables2 as tables Class AuditTable(tables.Table): def render_Team_Leader(self, value, column, record): if record.New_Team_Leader == True: column.attrs={'td': {'class': 'yellow'}} else: column.attrs={'td': {}} return value This image hopefully demonstrates my problem: Highlight rule fails when cell value is None How can I set it up so that the True/False New_Team_Leader formatting rules are applied, even if the Team_Leader is blank? -
Webpage not loading on Apple Devices
I made a webpage on Django + Bootstrap 5. The page works fine and shows everything, and so does on Mobile for android phones. But when it comes to iPhones 6, 7 or older the page wont display the gifs nor pictures that come dynamically from the DjangoDB as an URL. [this is how it looks on iphone, and a MacbookAir][1] [1]: https://i.stack.imgur.com/hvKVK.jpg This is the code segment that's supposed to display the video_list <ul id="first-category" class="items-container"> {% for video in video_list %} <li class="item"> <section class="video-container {{video.source_name}}"> <a href="{% url 'iepheme_app:video_player' pk=video.id %}"> <img class="visual-resource" aria-describedby="{{video.id}}-title" src="{{ video.thumbnail_url }}" alt="{{ video.title }}"> <section class="info"> <label id="{{video.id}}-title" for="{{video.id}}">{{video.title}}</label> </section> </a> </section> </li> {% endfor %} I have tried putting static images instead of gifs, deleting the media queries to check if it wasn't a display problem. A friend of mine tried the site on these devices: MacBook Pro MacOS Monterrey 2.01+ Tablet Ipad Pro 2018 iOS 15.01 + Iphone 11 Pro Max iOS 15.3.1 and all of them display the webpage without a single problem. So the issue is centered specially around IPhone 6, 7 or older. The site in question is https://www.ipeheme.com I appreciate all kinds of help. -
Django form fill all models and dynamic template
I do not find an example for this and I do not know the best way to do it. The goal is to create one form to fill all models. But, I would like to create a dynamic template. The user can choose in a list something in the database and if he does not find it, he could create the new element in the corresponding model. Following a picture with an example. The form contains for each model a selection of possibility or a + to add a new possibility to the Model. In this example, Model1 does not have what the user want, so he selects the + and dynamically, the fields' Model1 appear. And so, the user can add the new element. Thanks for tracks, example of other idea ;) -
django_auth_ldap, проблемы с разграничением доступа
Дамы и господа, помогите. Создал проект django и подключил к нему библиотеку django_auth_ldap, которая позволяет логиниться пользователям из IPA (причём членам только той группы, которую я вписал в настройках в файле settings.py). Всё работает. Но есть задача- разграничить доступ к разным сайтам проекта, чтобы на один сайт могли логиниться пользователи из одной группы на IPA, а на другой сайт - из другой группы. Как это можно реализовать и возможно ли это вообще? Просто я начинающий сисадмин и чуток не хватает знаний. Заранее благодарен за ответ. Дамы и господа, помогите. Создал проект django и подключил к нему библиотеку django_auth_ldap, которая позволяет логиниться пользователям из IPA (причём членам только той группы, которую я вписал в настройках в файле settings.py). Всё работает. Но есть задача- разграничить доступ к разным сайтам проекта, чтобы на один сайт могли логиниться пользователи из одной группы на IPA, а на другой сайт - из другой группы. Как это можно реализовать и возможно ли это вообще? Просто я начинающий сисадмин и чуток не хватает знаний. Заранее благодарен за ответ. -
django-elasticsearch-dsl-drf suggest url gives 404 'Page not found' error
I am using django-elasticsearch-dsl-drf library and have configured my viewset as per the documentation, but it's still throwing me a 404 'Page not found' for some reason. Also I have already used DocumentViewSet instead of BaseDocumentViewSet Document class ItemDocument(Document): Brand = fields.TextField( fields={ 'raw': fields.KeywordField(), 'original': fields.TextField(), 'suggest': fields.CompletionField(), } ) Category = fields.TextField( fields={ 'raw': fields.KeywordField(), 'original': fields.TextField(), 'suggest': fields.CompletionField(), } ) Viewset: class ProductsDocumentView(DocumentViewSet): document = ItemMasterProductsDocument serializer_class = ProductsSerializer fielddata = True filter_backends = [ FilteringFilterBackend, FacetedSearchFilterBackend, OrderingFilterBackend, DefaultOrderingFilterBackend, SuggesterFilterBackend ] faceted_search_fields = { ... } filter_fields = { ... } ordering_fields = ... ordering = ... # Suggester fields suggester_fields = { 'brand_suggest':{ 'field': 'Brand.suggest', 'suggesters': [ SUGGESTER_COMPLETION ], 'options': { 'size': 10, 'skip_duplicates': True } }, 'category_suggest':{ 'field': 'Category.suggest', 'suggesters': [ SUGGESTER_COMPLETION, ], 'options': { 'size': 10, 'skip_duplicates': True } }, } My route for viewset: 'api/products/' URL that I tried: http://127.0.0.1:8000/api/products/suggest/?brand_suggest__completion=Jack I am getting "The current path, api/products/suggest/, didn't match any of these." -
Django Test unique violation with auto increment field
There is problem with unique constraint violation in Django models use. My model is like: class Document(models.Model): id = models.BigAutoField(primary_key=True) ...bla bla bla So "id" field must be unique and it is autoincrement. In production environment I'm encounting problem of saving documents with same id. I think it is caused by parallel celery tasking but now it is handled by business logic to respond with 400 Bad request. Now I have to test logic to handle such type of errors in unit test. So I've tried to think in direction of editing Model's Meta values for "id" field inside a unit test but it isn't worked out. -
Why cannot vscode trace into the breakpoint in django.setup?
Why cannot vscode trace into the breakpoint in django.setup? [1]: https://i.stack.imgur.com/ZGmhK.png -
How to send firebase Phone Auth SMS to my flutter app users from my Django backend
How to send firebase Phone Auth SMS to my flutter app users from my Django backend. Am already sending notifications from my Django backend using pycfm def send_single_notification(deviceID,title,body): push_service = FCMNotification(api_key="<api-key>") registration_id = deviceID message_title = title message_body = body result = push_service.notify_single_device( registration_id=registration_id, message_title=message_title, message_body=message_body) So now I need also to trigger the phone auth SMS , so that when user register a new account I use a signal to send him the SMS from firebase and I complete the auth process -
Django filter queryset for replacing charactors
I have a customer table with masked phone numbers (944 (543) 3556) stored in it. (field: phone). I want to filter/search the table using phone number without any special charactors. I tried below filter queries and it is not return expecting results. self.queryset = self.queryset.annotate(customer_phone=Value(re.sub('[^0-9]','','123@#'),output_field=models.CharField())) print ('customer_phone:', self.queryset[0].customer_phone) # Output: customer_phone: 123 [Expected result] But when I give field name, it returns following error. self.queryset = self.queryset.annotate(customer_phone=Value(re.sub('[^0-9]','',F('phone')),output_field=models.CharField())) print ('customer_phone:', self.queryset[0].customer_phone) File "/usr/local/lib/python3.6/re.py", line 191, in sub backend_1 | return _compile(pattern, flags).sub(repl, string, count) backend_1 | TypeError: expected string or bytes-like object Is there anyway to filter phone number without considering the special charactors in it? python version: Python 3.6.5 Django==2.0.1 -
ManytoMany relation in Django?
I have two models class Group(models.Model): .... and class User(models.Model): ... group = models.ManyToManyField( Group) have ManyToMany relations What's the best way to prevent delete Group instance if there are some Users with this Group my solution is : def delete(self, request, *args, **kwargs): try: list_ = [] for user in User.objects.all(): for group in user.group.all(): if group.name not in list_: list_.append(group.name) else: continue if Group.objects.get(pk=kwargs['pk']).name in list_: return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED) else: return self.destroy(request, *args, **kwargs) except: raise ValueError("Error") I hope there are much better solution. -
How to remain in my current page after log-in - Django
I am currently learning Django using the Mozilla developer tutorials. I came across this problem of being redirected to homepage during login even after adding the URL parameter next in my template. The logic works fine during logout, but I seems to have a problem during login I do believe it is my login_direct that is causing the problem. Please how do I override the login_redirect. Thanks. Snippet of my code: My settings.py contains this: LOGIN_REDIRECT_URL = '/' And my template contains this: <li><a href="{% url 'logout'%}?next={{request.path}}">Logout</a></li> {% else %} <li><a href="{% url 'login'%}?next={{request.path}}">Login</a></li> I tried removing the login redirect. -
How can I access Django models from an app running in a different docker container?
I have a django app running in a docker container, attached to a mysql container. Everything is defined a docker-compose file. Now I need another filesystem_watcher container running, that will periodically check a directory on the host. When some files appear in this directory, this app needs to create a new instance of a Django model, and save it to the database. The only way I can think of to do this is to: Have a Django container, with the application code Have a container for my filesystem_watcher, which will also have the entire Django app Attach both to the same mysql container My filesystem_watcher app will import the django models, and use them. This works, but in this scenario, both the Django app Dockerfile, and the filesystem_watcher Dockerfile have entries that copy the entire Django app into both containers. If the source code for the Django app changes, both containers need to be rebuilt. Is there a better way to do this without copying the Django app into the filesystem_watcher container? -
Github Checks are failing due to setuptools dependency
Github checks I have searched online and there seems to be some issue with setuptools version but also changed that in build.yml and still they are failing and this is the line added in build.yml pip install --upgrade pip setuptools wheel please refer to this image github check fail -
Django-apscheduler app the database is locked
I have a fresh django installation with django-apscheduler app ( https://github.com/jcass77/django-apscheduler ) Following the django-apscheduler documentation I was able to add some jobs in the database but after a while the django-apscheduler app stop working with the following error: During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\ginyu\.virtualenvs\django-apscheduler-rsfawqf\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Users\ginyu\.virtualenvs\django-apscheduler-rsfawqf\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: database is locked The database timeout was already increased in django settings but error persists. Beside to migrate to another database backend, what else can I do to fix this issue? -
How create list with forms? Django
I would create forms with fields. Number fields depends of the user. For example we have list to do: To do: .... .... .... +add more How have I create this form? The simple form is: class ListToDoForms(forms.Form): do = forms.CharField() -
Django ChoiceField RadioSelect widget in form, test whitch element selected in template
I have 2 radio buttons in a ChoiceField and I would like to display some parts of the template, depending of witch radio button is selected. Following : form.py class CtdForm(forms.Form): protocol_name = forms.CharField(max_length=100) rb = forms.BooleanField(required=False, label='RB') mr = forms.BooleanField(required=False, label='MR') CHOICES = [('rb' ,'RB'), ('mr', 'MR')] analyse_type = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) template html ... {{ form.analyse_type }} Here I would like to test which button is selected and display the template depending of the selection something like : {% if form.analyse_type.? == true %} ... I test a lot of syntaxe with form.analyse_type.? like form.analyse_type.field.widget.choices to have each choices in a loop ect. , but I do not found the right one returning the selected radiobutton... Maybe this way is not the right one to do what I want. If you have any idea, solution thank you ;) -
Dynamic raw query (select clause) Django
I'm trying to execute a raw query in Django where I dynamically want to pick column names. Eg def func(all=True){ if all: query_parameters = { 'col': '*' } else: query_parameters = { 'col': 'a,b,c' } with connections["redshift"].cursor() as cursor: cursor.execute( "select %(col)s from table limit 2 ;", query_parameters, ) val = dictfetchall(cursor) return val } Django is executing it like. select "*" from table limit 2; so the output is just like select "*" * and in the else case it is executed like select "a,b,c" from table limit 2; so the output is a,b,c How can I run the command so that Django run it like select a , b , c from table limit 2 so that the output is a b c 1 2 3 4 5 6