Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Autocomplet Light select2 widget not working on ios
I have a project that uses DAL and I thought was all well and good till a friend told me the Select2 widget was broken. Turns out it does not work on any iOS(iphone, ipad) device in safari or chrome. It works on my Google pixel and macOS. Below is a picture of what it looks like on iOS. But basically eh problem is you cannot type into it. It just shows a blank list. Has anyone else run into this. Any idea of where to start would be great. I looked at the css for the select2 in DAL but could not see anything that would be device specific. I am using bootstrap as well and in my search ran into something where select2 did not play well with bootstrap and will try and do some testing of that tonight. Any direction would be appreciated. -
How to make existing columns empty in Django
I want to make existing columns empty and in the future the coulumn can not be filled. application = models.CharField(default="noname", max_length=100, null=False) Make existing columns empty and in the future the coulumn can not be filled with any values. -
How to filter QuerySet depending on fields of a reverse foreign key related model?
I have two following models: class Tour(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=3000, blank=True # some other fields here and class TourDatesInfo(models.Model): departure_date = models.DateTimeField() return_date = models.DateTimeField() tour = models.ForeignKey(Tour, on_delete=models.CASCADE, related_name='dates') Tour model has a one-to-many relationship with a TourDatesInfo, so that one tour may have multiple different sets of departure/return dates. What I try to achieve is to be able to filter the tours QuerySet depending on their set of TourDatesInfo, preciesely on whether each tour contains departure/return pair that satisfies specific conditions, e.g., get all tours that have at least one TourDatesInfo with departure_date > 2022-04-12 and return_date < 2022-05-01. I can write an SQL query to perform this, something like SELECT * FROM tours_tour tours WHERE tours.id IN (SELECT DISTINCT tour_id FROM tours_tourdatesinfo WHERE departure_date > '2022-04-12' AND return_date < '2022-05-01');, but how it can be done using django ORM without raw queries? -
Django with Javascript form not returning to View
I am trying to learn Javascript by developing an interactive form in Django. The form presents a Select list that allows multiple selections. As one or more tests in the list are selected the Javascript updates a list on the page with the current selections. When I press Submit, I expect to return to the View but instead I get a 405 Error and am not directed to the success URL. I added a Print statement to the form_valid method in the View and it never executes. Not sure how to get where I want to go. views.py class OrderTestsViewForJS(ListView): model = Universal_Test_File context_object_name = "testlist" success_url = '/list-patient/' template_name = "lab/order_tests_js.html" def get_context_data(self, *args, **kwargs): patient = get_object_or_404(Patient, pk=self.kwargs['pk']) context = super(OrderTestsViewForJS, self).get_context_data(**kwargs) context['patient'] = patient return context def form_valid(self, form): print("in form valid") return super().form_valid(form) stripped down template.html {% extends 'base.html' %} {% block title %}Order Tests{% endblock title %} {%load static%} {% block content %} <div class="card mt-5 "> <div class="card-header text-center"> NovaDev Order Tests Module </div> <div class="card-body"> <div class="row"> <div class="col-3 m-5"> <form action="" method="post"> {% csrf_token %} <select id="select_tests" name="select_tests" multiple > {% for test in testlist %} <option value = "{{test.service_id}}" > {{test.test_name}}</option> … -
Updating code on via GitHub Digital Ocean
New to Django, Python, and working with digital ocean. I have a Django app on digital ocean https://chicagocreativesnetwork.com/ which was uploaded via GitHub (with the help of a friend) I need to make some changes to the CSS and HTML for this app, which I am doing locally and pushing to my gitHub repository https://github.com/ktduffyincorperated/chicagocreativesnetwork. How do I get the pushed gitHub updates into my Digital Ocean app? thank you! -
How to show the flags in the options for internationalization?
I'm using the i18n to translate, only when I want to put the flags, it doesn't show them. Does anyone have an idea how to show the flags that I have in my images folder? By the way, I'm using spanish and english to translate. {% get_current_language as LANGUAGE_CODE %} <h1>{{LANGUAGE_CODE}}</h1> <h1>{{title}}</h1> <div class="d-flex flex-row"> <form action="{% url 'set_language' %}" method="POST"> {% csrf_token %} <input type="hidden" name="next" value="{{ redirect_to }}"> <div class="input-field p-2"> <select name="language" id="" class="form-control"> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected {% endif %}> {{ language.name_local }} {{language.code}} <img class="rounded-circle header-profile-user" src="{%static 'assets/images/flags/us.jpg' %}"> </option> {% endfor %} </select> </div> <input type="submit" value="Go" class="p-2"> </form> </div> -
how to delete int object in django
After filtering and updating I have to delete the objscts, How to solve the isuue, AttributeError: 'int' object has no attribute 'delete' def handle(self, *args, **options): trees.objects.filter(old=True).update(new=False).delete() My objective is to first filte all the old trees as True and new as False then updating I have to delete all the object list. -
Django initialize table with post_migrate not working
I want to initialize the database table with some predefined instances. # apps.py from django.apps import AppConfig from django.db.models.signals import post_migrate def initialize(sender, **kwargs): from .models import Address Address.objects.create( # address fields ) print('Created') class BackendConfig(AppConfig): name = 'backend' def ready(self): print('Ready') post_migrate.connect(initialize, sender=self) However nothing was created and nothing was printed after migration like the signal not triggered at all. -
Start scrapy by click button
I started project in django & scrapy. On the homepage I want to user can input model of car (I add car details to link to select right listing for scraping) and click button and the extraction process start and load data to django db. Can you help me how can I do it, is it possible? How make this button? Thanks -
Page 404 not found, current path did not match any of these
PAGE not found (404) Request method: GET Request URL: http://127.0.0.1:8000/action_page.php?steam_uid=12345678912345678&email=example%40gmail.com&username=johndoe&password1=123456&password2=123456 Using the URLconf defined in ReadyUp.urls, Django tried these URL patterns, in this order: [name='home'] account/ game/ group/ login [name = 'login'] logout [name = 'logout'] register/ [name ='register'] admin/ The current path, action_page.php, didn’t match any of these. I'm not exactly sure which url is creating the problem and would like some help. Here's a look at the url: from django.contrib import admin from django.urls import include, path from account.views import( register_view, login_view, logout_view, ) from group.views import ( home_screen_view ) urlpatterns = [ # Te4m Paths path('', home_screen_view, name='home'), path('account/', include('account.urls')), path('game/', include('games.urls')), path('group/', include('group.urls')), path('login/', login_view, name="login"), path('logout/', logout_view, name="logout"), path('register/', register_view, name="register"), # Default paths path('admin/', admin.site.urls), ] -
Django application doesn't seem to recognize related name?
I have a django app with a User's model that contains a followers field that serves the purpose of containing who follows the user and by using related_name we can get who the User follows. Vice versa type of thing. Printing the User's followers works, but I can't seem to get the followees to work. views.py followers = User.objects.get(username='bellfrank2').followers.all() following = User.objects.get(username='bellfrank2').followees.all() print(followers) print(following) models.py class User(AbstractUser): followers = models.ManyToManyField('self', blank=True, related_name="followees") Error: AttributeError: 'User' object has no attribute 'followees' -
Import statement openpyxy is not working on pycharm
i am very new to this language. trying to import openpyxl into pycharm, but it displays error messages that says "No module named 'openpyxl', when i checked through command prompt it says the file is installed, but i can't find it in the libraries -
term 'celery' is not recognized as an external function or cmdlet
I'm using Celery in my django application and when i'm trying to start celery worker with command: 'celery -A <project_name> worker -l info --pool=solo' it shows me an error that module 'celery' is not recognized, despite i've installed all necessary packages... >: celery worker --app=demo_app.core --pool=solo --loglevel=INFO : The term 'celery' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 celery worker --app=demo_app.core --pool=solo --loglevel=INFO ~ CategoryInfo : ObjectNotFound: (celery:String) [], CommandNotFoundException FullyQualifiedErrorId : CommandNotFoundException I've also tried to add celery's path to PATH variable, but it throws this error anyway. -
I have installed django-user-accounts but the templates dont seem to exist
from account.views import ( ChangePasswordView, ConfirmEmailView, DeleteView, LoginView, LogoutView, PasswordResetTokenView, PasswordResetView, SettingsView, SignupView, ) urlpatterns = [ path('admin/', admin.site.urls), path("signup/", SignupView.as_view(), name="account_signup"), path("login/", LoginView.as_view(), name="account_login"), path("logout/", LogoutView.as_view(), name="account_logout"), path("confirm_email/<str:key>/", ConfirmEmailView.as_view(), name="account_confirm_email"), path("password/", ChangePasswordView.as_view(), name="account_password"), path("password/reset/", PasswordResetView.as_view(), name="account_password_reset"), path("password/reset/<str:uidb36>/<str:token>/", PasswordResetTokenView.as_view(), name="account_password_reset_token"), path("settings/", SettingsView.as_view(), name="account_settings"), path("delete/", DeleteView.as_view(), name="account_delete"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/signup/ -
How i can use "database_sync_to_async" function for fetching multiple object
I am implementing a consumer, and y want get all productos for example: class TeamConsumer(AsyncConsumer): async def get_all_producs(): products = await database_sync_to_async(Products.objects.all)() When i try fetch all products from the above code causes the error "You cannot call this from an async context - use a thread or sync_to_async." I know that query ar lazy, but, how i can get all products? -
How does discord manages roles and permissions in database?
Users can have multiple roles, roles have multiple permissions, and roles are protected by servers. I was wondering do they use relational db for that? Is django capable of doing such thing? Because to fetch each user for server with role will be very expensive. Does discord uses django for this or any other framework? Any thoughts please? I am trying to build a similar schema but I think it will be very expensive for the db transactions and queries. I have workspace, workspace have users, users have multiple roles, roles have multiple permissions(groups in djangos). And I think this will be very expensive to call a single user to check whether he belongs to this group or not. -
How do I translate the radio selection buttons?
I can change the language of all the other forms, the problem is that I don't know how to change the language through forms.py, because it wouldn't be the same as in the template, right? html <div class="mb-3"> <label class="form-label d-block mb-3">{% trans "Country" %}:</label> <div class="custom-radio form-check form-check-inline"> {{ form.pais }} </div> </div> forms.py PAIS = ( ('United States', 'United States'), ('Canada', 'Canada'), ('Other', 'Other'), ) class ClientesForm(forms.ModelForm): pais = forms.ChoiceField( choices=PAIS, widget=forms.RadioSelect(attrs={'class':'custom-radio-list'}), ) -
What is equivalent to TestCase.client in normal script
For example with TestCase I can check login post and so on with self.client class TestMyProj(TestCase): response = self.client.login(username="user@example.com", password="qwpo1209") response = self.client.post('/cms/content/up', {'name': 'test', '_content_file': fp}, follow=True) However now I want to use this in script not in test case. because this is very useful to make initial database. I want to do like this. def run(): response = client.login(username="user@example.com", password="qwpo1209") response = client.post('/cms/content/up', {'name': 'test', '_content_file': fp}, follow=True) What is equivalent to TestCase.client in normal script?? -
Django rest serializer can't handle object - TypeError: Object of type Hero is not JSON serializable
I have the below simple rest api set up in Django. Calling the url http://127.0.0.1:8000/listheros/ returns TypeError: Object of type Hero is not JSON serializable for a reason I can't seem to figure out. # views.py from rest_framework.views import APIView from rest_framework.response import Response from .serializers import HeroSerializer from .models import Hero class ListHeros(APIView): def get(self, request, format=None): """ Return a list of all users. """ queryset = Hero.objects.all().order_by('name') serializer_class = HeroSerializer print('get') return Response(queryset) # urls.py from django.urls import include, path from applications.api.views import ListHeros urlpatterns = [ path('listheros/', ListHeros.as_view()), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] # serializers.py from rest_framework import serializers from .models import Hero class HeroSerializer(serializers.ModelSerializer): class Meta: model = Hero fields = ('name', 'alias') # models.py from django.db import models class Hero(models.Model): name = models.CharField(max_length=60) alias = models.CharField(max_length=60) def __str__(self): return self.name -
How to use Property in Django Rest Framework model?
I am newbie to Django Rest Framework. I am have problem with using Property in Django rest framework My Model class AwsConsoleAccess(TimeStampedModel): _resources = CharField(max_length=4096) @resources.setter def resources(self, resources: List[str]): self._resources = ','.join(resources) @property def resources(self) -> List[str]: if self._resources: return self._resources.split(',') return [] My serializer class AwsConsoleAccessSerializer(ModelSerializer): class Meta: model = AwsConsoleAccess fields = '__all__' My view def post(self, request, *args, **kwargs): serializer = AwsConsoleAccessSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() My curl request http://localhost:8000/access/842b1012-53ef-4e98-9a20-484e681c3789 request body: { "resources": [ { "id": "dev-atm-jr1-platformcanary-APPLICATION" } ] } Response { "_resources": [ "This field is required." ] } status code - 400 bad request If I rename the resources to _resources in request_body it does not accept the List[str] . I wanted to set the List of string -
Test tags not found in Django project with nested apps
I have a Django project with nested apps layout, i.e. created with the following commands: django-admin startapp app cd app django-admin startapp app_nested Such layout was proposed by Dan Palmer in DjangoCon US 2021 and it works great for me. I’m really content with such organization of larger projects, but I failed to find an open source examples of its implementations. This causes problems with writing the details. Right now I struggle with unit test loader not finding the tests by tags in nested apps (tags in normal apps work fine). Consider the following example: @tag('testme') class SomeTest(TestCase): def test_foo(self): self.assertTrue(False) This test can be found by python manage.py test app/app_nested command, but python manage.py test --tag=testme runs 0 tests. Given that the first command works the test construction seems fine. How to make the test runner find tags from nested apps? Also, if someone knows some open source Django projects with nested apps structure this could be helpful as well. The current project is in Django 2.2, but this question refers to all Django distributions. -
Django migrations relations
Suppose we have two models, Person and Worker. Know, I want to alter the name of Person to InterestPerson. How does Django exactly knows that the new name belongs to the old one? I was looking in the generated tables in DB and in the migrations, but I can't figure out how is he able to make the relation. Same applies with fields, datatypes, lengths... etc. -
How to use while loop for showing more items in Django view?
I am making a small Django project, but I have an issue. When I write names to one form and topics to other one and press button, I want to see list of randomly attached names and topics. In my current code I don´t get a list but just one name and one topic. How can I solve that problem? My views.py file: from django.shortcuts import render from .losovaci_zarizeni import UvodniTabulka from random import choice def losovani_view(request): form = UvodniTabulka(request.GET) spoluzaci = request.GET.get("spoluzaci") temata = request.GET.get("temata") spoluzaci_list = spoluzaci.split() temata_list = temata.split() while True: spoluzak = choice(spoluzaci_list) spoluzaci_list.remove(spoluzak) tema = choice(temata_list) temata_list.remove(tema) if len(spoluzaci_list)==0: break return render(request, "losovani.html", {"form":form, "spoluzak": spoluzak, "tema":tema}) My file with UvodniTabulka: from django import forms class UvodniTabulka(forms.Form): spoluzaci = forms.CharField(max_length=500) temata = forms.CharField(max_length=500) -
why is dynamic path not working in djnago
so i tried to make a dynamic path in django but when i pass 'frame' as argument in the view function 'details_meetups' that error show up function i got this error. error image urlpatterns = [ path('admin/', admin.site.urls), path('BookList', BookList.views.index), path('BookList/<frame>', BookList.views.Meetup_Details)] def Meetup_Details(request,frame): selected_one = {"name":"jacob", "description":"tall"} return render('request,BookList/meetup-detail.html',{ "name" : selected_one["name"], "description" : selected_one["description"] } ) -
How to follow the redirct and test again in test script
I have this test script for uploading file with open('_material/content.xlsx','rb') as fp: response = self.client.login(username="user@example.com", password="qwpo1209") response = self.client.post('/cms/content/up', {'name': 'test', 'content_file': fp,"is_all":"True"}) self.assertEqual(response.status_code,302) # it shows ok #then next, how can I follow the redirect and test the page?? self.assertContains(response, "success!") It returns the redirect 302 but I want to follow the redirect and nect check. Because there comes the message such as success! Is it possible?