Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
For vvxhid who helped me a lot
I add Chapter to make it easier to find the page How to make it so that when choosing a chapter on the site, linked pages to the chapter dynamically appear? models.py class Page(models.Model): title_title = models.ForeignKey('Book', on_delete=models.PROTECT) chapter_chapter = models.ForeignKey('Chapter', on_delete=models.PROTECT) number_page = models.CharField(max_length=(500)) def __str__(self): return self.number_page class Chapter(models.Model): book_name = models.ForeignKey( 'Book', on_delete=models.CASCADE, null=True) chapter_name = models.CharField(max_length=(500), db_index=True) def __str__(self): return self.chapter_name views.py def Second_page(request, book_slug): page = Page.objects.all() chapter = Chapter.objects.all() page = Page.objects.filter(title_title__slug=book_slug) chapter = Chapter.objects.filter(book_name__slug=book_slug) get_object_or_404(Book, slug=book_slug), return TemplateResponse(request, "second.html", {'page': page, 'chapter': chapter}) second.html {% extends 'index.html' %} {% block content %} <div class="chapter"> <select> {% for c in chapter %} <option value="">{{c.chapter_name}}</option> {% endfor %} </select> </div> {% for p in page %} <ul> <li><p>{{p.number_page}}</p></li> </ul> {% endfor %} {% endblock %} -
How do I get user deleted from Django database when I delete from Auth0 users and vice versa?
I am using Auth0 with my Django App for users login/logout authentication. I want a way that when I delete any User from Auth0, the same user account should be deleted from Django Database, likewise if I delete any user account from Django, the attached user from Auth0 should be deleted as well. How will I achieve this functionality? Any help will be appreciated. -
How to send emails and whatsapp messages to inactive members in django
I would like to send emails and whatsapp messages once a membership expires. I have a management command set up to check if the membership expired and updates it status. However, how do I know which member is being updated? I would like to set up a list of dictionary with name and number and filter through them each day and send out the messages. models.py class Member(models.Model): full_name = models.CharField(max_length=125) email = models.EmailField(max_length=125, blank=True, null=True) phone = models.CharField(max_length=20) image = models.ImageField(max_length= 256, upload_to=upload_to_image_post, null=True, blank=True) date_created = models.DateTimeField(default=django.utils.timezone.now) class Meta: verbose_name_plural = "All Members" def __str__(self): return str(f"{self.full_name}") class ActiveMember(models.Model): member = models.OneToOneField(Member, on_delete=models.CASCADE, related_name='is_member') start_date = models.DateField(default=django.utils.timezone.now) end_date = models.DateField(default=django.utils.timezone.now) status = models.CharField(max_length=2, choices=(('1','Active'), ('2','Inactive')), default = '1', blank=True, null=True) def __str__(self): return str(f"{self.member}") management command from turtle import update from django.core.management.base import BaseCommand, CommandError from members.models import ActiveMember from datetime import datetime, timedelta class Command(BaseCommand): help = 'Deactivate expired memberships!' def handle(self, *args, **options): ActiveMember.objects.filter(end_date__lt=datetime.now().date()).update(status='2') What's the easiest way to find out which member status is being changed and pull their name and phone number or name and email. -
Django Model Linking
How it should be: I choose a Book A http://127.0.0.1:8000/<slug:book_slug> opens with a selection of pages that are associated with the book that I have chosen; As it turns out: I choose a book A http://127.0.0.1:8000/<slug:book_slug> opens with a choice of absolutely all created pages; My Code: models.py from django.db import models from django.urls import reverse class Book(models.Model): title = models.CharField(max_length=(500)) slug = models.SlugField( max_length=(150), unique=True, db_index=True, verbose_name="URL" ) def __str__(self): return self.title def get_absolute_url(self): return reverse('book', kwargs={'book_slug': self.slug}) class Page(models.Model): title_title = models.ForeignKey('Book', on_delete=models.PROTECT) number_page = models.CharField(max_length=(500)) def __str__(self): return self.number_page urls.py from django.urls import path from .views import First_page, Second_page urlpatterns = [ path('', First_page), path('<slug:book_slug>', Second_page, name='Second_page') ] views.py from django.template.response import TemplateResponse from .models import Book, Page from django.shortcuts import get_object_or_404 def First_page(request): book = Book.objects.all() return TemplateResponse(request, "first.html", {'book': book}) def Second_page(request, book_slug): page = Page.objects.all() get_object_or_404(Book, slug=book_slug), return TemplateResponse(request, "second.html", {'page': page}) first.html {% extends 'index.html' %} {% block content %} {% for b in book %} <ul> <li><a href="{{b.slug}}">{{b.title}}</a></li> </ul> {% endfor %} {% endblock %} second.html {% extends 'index.html' %} {% block content %} {% for p in page %} <ul> <li><p>{{p.number_page}}</p></li> </ul> {% endfor %} {% endblock %} -
removetags returns invalid filter
Im trying to use {{ content|removetags:"style link script"|safe }} to remove specific html tags, but it is returning error django.template.exceptions.TemplateSyntaxError: Invalid filter: 'removetags' can someone help? -
Cannot resolve keyword 'location' into field
Good day, I spent a couple of day to solve that issue and I hope you can help. I installed django and I would like to use leaflet to display the position of my weather station. I found that nice tutorial and I could success the process. However, now I would like to apply that exercise to my project. I have a database with about less of one million of measures and I need to keep the structure of my database/table. I will do my best to describe my problem. My problem start here (viewsets.py) and here . As I understand, the 'location' match to a field of my table, which should contain a value similar to this 'POINT(6.000251769184164 46.19337852885697)',0 because the type of the field is POINT. However, my database does not have a such field. Instead, I have a field station_lat (float(8.6)) and station_lng (float(8.6)), where I save the latitude and longitude. That the reason why, I have the error Cannot resolve keyword 'location' into field. Choices are: fields_id_field, fields_id_field_id, id_station, installed, map, sensors, station_active, station_alt, station_archive, station_created, station_description, station_lat, station_lng, station_longname, station_name, station_order, stations_types_id_stations_type, ttn_app_id, ttn_dev_id, ttn_hardware_serial As I have to use my database as the fields … -
UNIQUE constraint failed: account_user.username
I customized the user model And I want to create a superuser in the terminal and I get an error. I was only able to make it the first time((I still can't login, it gives an error:Please enter the correct email address and password for a staff account. Note that both fields may be case-sensitive.) Note that I do not enter duplicate username and email. my models.y: from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models from django.utils.html import format_html from .managers import UserManager class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField(max_length=155, unique=True) full_name = models.CharField(max_length=200 , null=True, blank=True) phone_number = models.CharField(max_length=11, unique=True, null=True, blank=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) avatar = models.FileField(upload_to='avatar_user', null=True, blank=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin def showImage(self): # show image … -
django - making sections for course
I am building a site with the logic of Course - Section- Lesson. I can shoot the sections of the course, but I cannot shoot the lessons of the sections. Where am I doing wrong? Models.py class CourseCategoryModel(models.Model): name = models.CharField(max_length=200, verbose_name="Category Name") slug = models.SlugField(unique=True) class CourseModel(models.Model): name = models.CharField(max_length=200, verbose_name="Course Name") category = models.ForeignKey(CourseCategoryModel, null=True, blank=True, on_delete=models.PROTECT, verbose_name="Course Category") class CourseLessonSectionModel(models.Model): name = models.CharField(max_length=200, verbose_name="Section Name") order = models.IntegerField(max_length=3, verbose_name="Section Order") course = models.ForeignKey(CourseModel, null=True, blank=True, on_delete=models.PROTECT, verbose_name="Course") class CourseLessons(models.Model): course = models.ForeignKey(CourseModel, null=True, blank=True, on_delete=models.CASCADE, verbose_name="Course") section = models.ForeignKey(CourseLessonSectionModel, null=True, blank=True, on_delete=models.CASCADE, verbose_name="Lesson Section") name = models.CharField(max_length=200, verbose_name="Lesson Name") order = models.IntegerField(max_length=3 , verbose_name="Lesson Order", default=0) View.py def detail(request, slug): course = CourseModel.objects.get(slug=slug) courseSection = CourseLessonSectionModel.objects.all().filter(kurs__slug=slug) courseLessons = CourseLessons.objects.all().filter("what should i write here?") return render(request, "coursedetail.html", context={ "course": course, "courseLessons" : courseLessons, "courseSection" : courseSection }) -
Search bar error: 'WSGIRequest' object has no attribute 'Post' / Django
I am trying to implement search in Django. When I enter something into the search, I get an error: 'WSGIRequest' object has no attribute 'Post'. app view def searchbar(request): if request.method == "POST": searched = request.Post["searched"] students = Q(pk__contains=searched) | Q(first_name__contains=searched) | Q(last_name__contains=searched) return render(request, template_name='searchbar.html', context={"searched": searched, "students": students}) else: return render(request, template_name='searchbar.html', context={}) template {% extends "index.html" %} {% block content %} <center> {% if searched %} <h1>You search for {{ searched }}</h1> <br/> {% for student in students %} {{ student.first_name }} {{ student.last_name }}<br/> {% endfor %} {% else %} <h1>Nothing to search</h1> {% endif %} </center> {% endblock %} Tell me what could be the problem? Thanks in advance. -
Django: Table doesn't exist( python manage.py migrate)
I dropped some table related to an app. and again tried the syncdb command python manage.py migrate It shows error like django.db.utils.ProgrammingError: (1146, "Table 'homeapp_enroll_course' doesn't exist") models.py class Enroll_course(models.Model): SHFE_CHOICES = ( ('M', 'Moring'), ('E', 'Evening'), ) BATCH_CHOICES = ( ("A", "1ST"), ("B", "2ND") ) userinfo = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) batch = models.CharField(max_length=1, choices=BATCH_CHOICES, default="A") shife = models.CharField(max_length=1, choices=SHFE_CHOICES, default="M") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
Stuck at the start lerning Django
Sorry for mistakes, this text transleted by Google Translate Hi all! My story is short: I'm 21, I studied computer science, Python and algorithmization, basic sql, a little Git for 3 months. I am a 3rd grade university student. I started learning django and got stuck. The library turned out to be a stone wall that I pick with a wooden stick. knowledge does not fit in the head. I went through 5 of the 7 steps of the documentation tutorial. They say, start writing small programs, or catch up with tons of theory, or buy a course) But what to write when, at the start of writing, there is a fog in my head. I have of course ideas for pet-projects but they are hard to realize for me) I have been standing still for 2 months and it seems that I have already lost the knowledge gained in the tutorial I thought of copy-pasting a project on tutorials from YouTube, but some people told me that you won’t remember anything, that is why this idea died at the start) advice me something! -
Django AUTH0 serializer
In my app I use auth0 to do authentication. Everything works great, I can see new users being created in admin panel etc, but there is one issue. when I go to my endpoint that displays data I have an empty list. Like this { "id": "d458196e-49f1-42db-8bc2-ee1dba438953", "owner": 1, "name": "dsdsds", "viewable": [] } the list viewable is a list of users that can view the data object. So if you want to share your data with your friend you just add his email Like I said previous. This list is viewable form django admin level and drf form level but not in JSON. How to display this data? Models from django.contrib.auth.models import AbstractUser from django.conf import settings class User(AbstractUser): pass class WalletInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=30, null=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='owner', on_delete=models.CASCADE) viewable = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='can_view', blank=True) Settings.py AUTH_USER_MODEL = 'budget_app.User' SOCIAL_AUTH_TRAILING_SLASH = False SOCIAL_AUTH_AUTH0_DOMAIN = '####' SOCIAL_AUTH_AUTH0_KEY = '####' SOCIAL_AUTH_AUTH0_SECRET = '####' SOCIAL_AUTH_AUTH0_SCOPE = [ 'openid', 'profile', 'email' ] AUTHENTICATION_BACKENDS = { 'social_core.backends.auth0.Auth0OAuth2', 'django.contrib.auth.backends.ModelBackend' } LOGIN_URL = '/login/auth0' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' Serializers class WalletInstanceSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.id') class Meta: model = WalletInstance fields = '__all__' depth = 1 -
django channels + nginx occurs 504 timeout
I deployed my django server with nginx. I use daphne as a web server in my docker image, so docker execute ENTRYPOINT ["daphne", "-b", "0.0.0.0", "-p", "8000", "my_app.asgi:application"] daphne is the only web server and nginx cover all about django. location / { proxy_pass http://my_backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } and when I'm trying to login in admin panel, 504 occurs. I implemented one django channels consumer (about chatting) but I can't understand why chat websocket is related with the problem being logined in django admin. and docker saids, my_app | 2022-08-14 03:30:14,084 WARNING Application instance <Task pending name='Task-5' coro=<ProtocolTypeRouter.__call__() running at /usr/local/lib/python3.10/site-packages/channels/routing.py:71> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/local/lib/python3.10/asyncio/futures.py:384, Task.task_wakeup()]>> for connection <WebRequest at 0x7ff0f0feb7c0 method=POST uri=/admin/login/?next=/admin/ clientproto=HTTP/1.1> took too long to shut down and was killed. Ironically, swagger documentation(drf-yasg) and django login page is normally connectable. Everything is ok in localhost when I execute in my pycharm. I don't know anymore. What should I do further? please help -
How to call next page in cursor pagination in django
from rest_framework.pagination import CursorPagination # In API View def get(self, request, *args, **kwargs): all_message = GroupMessages.objects.filter(group_id=ChannelGroup.objects.filter(group_name=group_name).first()) paginator = CursorPagination() result_page = paginator.paginate_queryset(all_message, request) serializer = GroupMessagesSerializer(result_page, many=True,context={'request': request}) response = Response(serializer.data, status=status.HTTP_200_OK I have implemented Cursor Pagination and i am getting response also. In PageNumberPagination We can manipulate our response via parameter in request url for eg ?page=1 or 2 but in cursor pagination if i want to test my pagination in postman how should i manipulate it when i hit my url {{BaseUrl}}channel/getmessages/GeneralChannel/ i am getting 2 records but how can i fetch next two records which parameter should i pass or is there something else in Cursor pagination in order to do this -
Redux Toolkit Query sends empty data to DRF API, ie. request.data is showing empty in django backend views
I want to send form data using Redux RTK Query to Django API. I have two models User and Profile related with One To One Relationship. Everything works fine in backend as I checked with Postman. I can update in Profile model or Create new entry in Profile model. But when I send my form data from React front end using Redux RTK Query for POST/PATCH, I got request.data as empty {} . RTK Query: editProfile: builder.mutation({ query: (access_token, actualData) => { console.log(actualData) return { url:'editprofile/', method:'PATCH', body:actualData, headers:{'authorization' : `Bearer ${access_token}`, 'Content-type':'application/json'} } } }), createProfile: builder.mutation({ query: (access_token, actualData ) => { return { url:'createprofile/', method:'POST', body:actualData, headers:{'authorization' : `Bearer ${access_token}`, 'Content-type':'application/json'} } } }) console.log(actualData) gives {locality: 'ffff', city: 'ffff', address: 'ffff', pin: 'fffff', user: 1} view.py : Through POSTMAN I have checked everything works fine. class UserProfileDataView(APIView): renderer_classes = [UserRenderer] permission_classes = [IsAuthenticated] def get(self, request, format=None): serializer = ProfileSerializer(request.user.profile, context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request, format=None): serializer = ProfileSerializer(data= request.data, context={'request': request}) serializer.is_valid(raise_exception=True) serializer.save() return Response ({ 'msg':'Data Updated Successfully'},status=status.HTTP_201_CREATED ) def patch(self, request, format=None): item = Profile.objects.get(user = request.user) serializer = ProfileSerializer(item ,data = request.data, partial=True, context={'request': request}) print(request.data) serializer.is_valid(raise_exception=True) user = … -
axios post request not giving any data to django view
I am trying to make my first post request using axios to a Django view which accepts both POST and GET. I am getting an empty dict from the request.POST: <QueryDict: {}> [13/Aug/2022 16:44:00] "POST /users/114260670592402026255 HTTP/1.1" 200 9 The server does return a 200 status code but the data I sent from the UI is not present. I have the following django view: from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import json from .models import UserProfile @csrf_exempt def get_user_profile(request, user_id): if request.method == 'GET': try: user = UserProfile.objects.get(user_id=user_id) print("user found") except Exception as error: print("User profile wasnt found:") print(error) user = None profile = UserProfile() profile.user_id = user_id profile.searches = [ {'search_term': 'hd'}, {'search_term': 'wba'}, ] profile.save() print("user saved in db") user = UserProfile.objects.get(user_id=user_id) data = { 'user_id': user.user_id, 'searches': user.searches } json_data = json.dumps(data) return HttpResponse(json_data, content_type='application/json') if request.method == 'POST': data = request.POST print(data) return HttpResponse("it worked") in the UI app, SearchPage.js: useEffect(() => { console.log("user id changed") if (userId) { const user_profile_api_url = BASE_URL + '/users/' + userId axios.get(user_profile_api_url, {}) .then(response => { const recent_searches_response = response.data.searches; const new_recent_searches = []; recent_searches_response.map(dict => { new_recent_searches.push(dict.search_term) }) setRecentSearches(new_recent_searches); }) .catch((error) => { … -
problem: Table doesn't exist( python manage.py migrate)
I dropped some table related to an app. and again tried the syncdb command 'python manage.py migrate' It shows error like django.db.utils.ProgrammingError: (1146, "Table 'someapp.feed' doesn't exist") models.py ''' class Enroll_course(models.Model): SHFE_CHOICES = ( ('M', 'Moring'), ('E', 'Evening'), ) BATCH_CHOICES = ( ("A", "1ST"), ("B", "2ND") ) userinfo = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) batch = models.CharField(max_length=1, choices=BATCH_CHOICES, default="A") shife = models.CharField(max_length=1, choices=SHFE_CHOICES, default="M") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) ''' -
How to send to print an ajax response in django
I'm trying to print (the action of sending to printer) a png image I get as a response from my ajax call. The reply from ajax is successful, meaning the image is properly sent. I can even open it in another window. However, I want to send that image automatically to print. I can do window.print() but that just prints the current page, not the response (obviously). Does anyone know how to process the response in order to print it? function traer_1234(){ $.ajax({ dataType: "html", contentType: "application/json", type: 'GET', data: {"nanda": 1}, url: "{% url 'View_test' %}", success: function (response) { alert("1234") window.print() }, error: function (response) { alert("Error") } }) } Thanks in advance to anyone who can supply any info. -
DRF display nested json
i have my DRF app. In my case, one wallet can have many entries such as income or expense. When I call my endpoint (viewset) I get data in this format [ { "id": "d458196e-49f1-42db-8bc2-ee1dba438953", "owner": 1, "viewable": [], "entry": [] } ] How can I get the content of "entry" variable?. class Category(models.Model): name = models.CharField(max_length=20, unique=True) def __str__(self): return self.name class BudgetEntry(models.Model): STATE= [ ('income','income'), ('expenses','expenses'), ] amount = models.IntegerField() entry_type = models.CharField(max_length=15, choices=STATE, null=True) entry_category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.SET_NULL) class WalletInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='owner', on_delete=models.CASCADE) viewable = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='can_view', blank=True) entry = models.ManyToManyField(BudgetEntry, related_name='BudgetEntry', blank=True) serializers class BudgetEntrySerializer(serializers.ModelSerializer): class Meta: model = BudgetEntry fields = '__all__' class WalletInstanceSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.id') class Meta: model = WalletInstance fields = '__all__' views class WalletViewset(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] serializer_class = WalletInstanceSerializer def get_queryset(self): user_id = self.request.user.id available = WalletInstance.objects.filter( Q(owner=user_id) ) return available -
Why celery task read past value
I want celery task read value in settings.py to getattr. When I call a specific API, the value changes to setattr. But, celery still get the initial value through getattr. I tested to output the changed value when calling API, It's print change data. def api(mode): setattr(settings, SYSTEM_MODE, mode) ... def tasks(): ... mode = getattr(settings, SYSTEM_MODE) ... -
How to download Instagram DP in browser using Instaloader in django?
views.py def submit_form(request): if request.method=="POST": url=request.POST.get('url1') test=instaloader.Instaloader() test.download_profile(profile_name=url,profile_pic_only=True) return HttpResponse main.html <div class="row text-center py-3 mt-3"> <div class="col-4 mx-auto"> <form action="{% url 'submit_form' %}" method='post'> {% csrf_token %} {{ form | crispy }} <input type="text" placeholder="Regular" class="form-control" name="url1" > <input type="submit" value="Download" class="btn bg-gradient-primary btn-sm me-2" > </form> </div> </div> url.py urlpatterns = [ # The home page path('', views.index, name='home'), path('main', views.main, name='main'), path('submit_form', views.submit_form, name='submit_form'), # Matches any html file re_path(r'^.*\.*', views.pages, name='pages'), ] OFFICIAL MODULE INSTALOADER LINK https://instaloader.github.io/index.html actually its download in project dir but i want to download file from browser when we click on download button. so how to download in my computer from browser. Please guys help me. -
Create a LDAP users and groups from the dajango interface admin
I am trying to modify a user in OpenLDAP server. As of now I can log but when I try to create users or groups in django. I can't see those users and groups in my LDAP server. Do you have any idea how a can sycnronize this data from django to LDAP For now i use the package django-auth-ldap for LDAP backend. This my conf in settings.py #OpenLdap-AUTH import ldap from django_auth_ldap.config import LDAPSearch, LDAPGroupQuery,GroupOfNamesType,PosixGroupType AUTH_LDAP_SERVER_URI = 'ldap://localhost' AUTH_LDAP_BIND_DN = 'cn=admin,dc=example,dc=com' AUTH_LDAP_BIND_PASSWORD = 'omar77' AUTH_LDAP_USER_SEARCH = LDAPSearch('ou=users,dc=example,dc=com',ldap.SCOPE_SUBTREE, '(uid=%(user)s)') AUTH_LDAP_GROUP_SEARCH = LDAPSearch('ou=groups,dc=example,dc=com',ldap.SCOPE_SUBTREE, '(objectClass=top)') AUTH_LDAP_GROUP_TYPE = PosixGroupType(name_attr="cn") AUTH_LDAP_MIRROR_GROUPS = True # Populate users from the LDAP directory to Django db. AUTH_LDAP_REQUIRE_GROUP = "cn=enabled,ou=groups,dc=example,dc=com" AUTH_LDAP_DENY_GROUP = "cn=disabled,ou=groups,dc=example,dc=com" AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", "username": "uid", "password": "userPassword", } AUTH_LDAP_PROFILE_ATTR_MAP = { "home_directory": "homeDirectory" } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "cn=active,ou=groups,dc=example,dc=com", "is_staff": "cn=staff,ou=groups,dc=example,dc=com", "is_superuser": "cn=superuser,ou=groups,dc=example,dc=com" } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_TIMEOUT = 3600 AUTH_LDAP_FIND_GROUP_PERMS = True -
Django find common instances data in two models
I have models like: class Hospital(models.Model): name = models.CharField(max_length=200, unique=True) manager_name = models.CharField(max_length=200, default='') manager_id = models.CharField(max_length=200) def __str__(self): return f'{self.name}' class Sick(models.Model): name = models.CharField(max_length=200, default='') nationalID = models.CharField(max_length=200) illName = models.CharField(max_length=200) hospital = models.ForeignKey(Hospital, related_name='sicks', on_delete=models.DO_NOTHING) def __str__(self): return f'({self.name}, {self.nationalID})' class Employee(models.Model): name = models.CharField(max_length=200, default='') nationalID = models.CharField(max_length=200) company = models.ForeignKey(Company, related_name='employees', on_delete=models.CASCADE) def __str__(self): return f'({self.name}, {self.nationalID})' views: @api_view(['POST']) def get_sick_employee_by_hospital(request): pass and a serializer like : from rest_framework import serializers class NameSerializer(serializers.Serializer): name = serializers.CharField(required=True, max_length=200, allow_null=False) my problem is : my view get_sick_employee_by_hospital() receives a hospital name and it must return all sick peoples that are employees and They have visited that hospital, in a dictionary with keys 1,2,3,..., n and values like "(name, nationalID)". Pay attention that it does not matter which value is assigned to which key. what is the best way to do that ? how can i get all sick peoples that are employees and They have visited a hospital? thanks for your time. -
verbose name on class field in django
I am need of help to add a verbose name class Address(models.Model) : class Zip(models.Field): def db_type(self, connection): return 'char(8)' zip = Zip() address = models.CharField(max_length=200, verbose_name="Rua") ..... Need put the vebose name of ZIP to CEP -
How multiply and sum two columns in different tables in django
I have an application for calculating diets based on the nutrients of each meal. In admin of this application I want to price of each meal to the Meal table, which I have managed to do by calculating the price when displaying it in admin: # admin.py class AdminMeal(admin.ModelAdmin): list_display = ['name', 'meal_type_names', 'price'] @admin.display(description='Price') def price(self, obj): unit_prices = np.asarray(obj.mealingredient_set.order_by('id').values_list('ingredient__unit_price')) amounts = np.asarray(obj.mealingredient_set.order_by('id').values_list('amount')) to_return = float(np.matmul(np.transpose(unit_prices), amounts) / 1000) return mark_safe(to_return) Now my main question: I need to allow ordering of Meal table based on Price which I don't know how. based on my search it seems I should use annotate instead of my current way of calculating the price to be able to sort my table, I found a solution in here # admin.py class AdminMeal(admin.ModelAdmin): list_display = ['name', 'meal_type_names', 'price'] def get_queryset(self, request): queryset = super().get_queryset(request) queryset = queryset.annotate(_price=Sum('mealingredient__amount * mealingredient__ingredient__unit_price')) But sadly it throws this error (I think it's because i'm trying to SUM over different tables): Unsupported lookup 'amount * mealingredient' for AutoField or join on the field not permitted. Any help is appreciated, forgive me if I have missed something obvious, I'm a beginner in django. Some of the relevant Models for Meal table: …