Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Any way to get nested groups of users in Django rest framework with user[0]=id&user[0]=id&user[1]=id
Need to somehow handle the user[0]=id&user[0]=id&user[1]=id use case and return [[users], [users]] from db in django -
Concatenate gettext_lazy translated string with a normal string in Django 4.1.x
The question seems dummy, but I wish I could append some language-invariant string to a translated string in Django: from django.utils.translation import gettext_lazy as _ class House(models.Model): height_m = models.IntegerField( verbose_name=_("height")+" [m]", null=False, ) Here, the unit [m] is from the SI so I don't need to translate it. But by doing so in my model, the result in other languages desperately stays in English. How could I concatenate a normal string with a translated string in Django 4.1.x? -
Enable a signal only for google log in
I have a customer panel in which customer can sign up by filling a user creation form or via sign in with google. To enable the user to sign in with google I have created a signal as following: @receiver(post_save, sender = CustomUser) def customer_create(sender, instance, created, *args, **kwargs): if created: instance.is_customer = True instance.save() customer = Customer.objects.create(user=instance) customer.username = instance.username customer.email = instance.email customer.first_name = instance.first_name customer.last_name = instance.last_name customer.save() it works fine for the user who are signed with via google. But when user tries to sign up via form a duplicate key value violation arises as it also works with the signal. How can I enable the signal only for the users who are signed in via google? -
Business and IT
Model class schooldetail(models.Model): schoolbranch = models.CharField(max_length=100, unique=True,blank=False) name = models.CharField(max_length=100,blank=False) description = models.TextField(blank=True) email=models.EmailField(max_length=50,blank=True) contactno=models.CharField(max_length=50,blank=True) accountname=models.CharField(max_length=50,blank=False) bsb=models.CharField(max_length=6) accountno=models.CharField(max_length=10) def __str__(self) -> str: return self.schoolbranch class studentdetails(models.Model): first_name =models.CharField(max_length=50,blank=True, null=True) last_name = models.CharField(max_length=50,blank=True, null=True) dob=models.CharField(max_length=15,blank=True, null=True) MALE=1, FEMALE=2 OTHER=3 STATUS_CHOICES=( ('MALE','Male'), ('FEMALE','Female'), ('OTHER','Other') ) sex=models.CharField(max_length=10,choices=STATUS_CHOICES,blank=True, null=True) CITIZEN = 1 PERMANENT = 2 WORKING = 3 STUDENT = 4 TRAVEL = 5 RESIDENTAL_STATUS = ((CITIZEN, 'Australian Citizenship'), (PERMANENT, 'Permanent Resident.'), (WORKING, 'Working Visa'), (STUDENT, 'Student Visa'), (TRAVEL, 'Travel Visa'),) residental_status=models.CharField(max_length=50,choices=RESIDENTAL_STATUS,blank=True, null=True) user=models.ForeignKey(to=User,on_delete=models.CASCADE) def __str__(self) -> str: return self.first_name class EnrollmentModel(models.Model): student=models.ForeignKey(studentdetails,on_delete=models.CASCADE) YES=1 NO=0 COND_STATUS=( ('YES','Yes'), ('NO','No') ) medical_condition =models.BooleanField(default=False) medication_routine = models.BooleanField(default=False) any_restriction = models.BooleanField(default=False) agree_condition = models.BooleanField(default=False) agree_declaration = models.BooleanField(default=False) PROCESS='p', CANCEL='c' APROVED='a' ENROLLED='e' SUBMIT='s' ENROLLMENT_STATUS=( ('PROCESS','Process'), ('CANCEL','Cancel'), ('APROVED','Aproved'), ('ENROLLED','Enrolled'), ('SUBMIT','Submit'), ) enrolment_status=models.CharField(max_length=20,choices=ENROLLMENT_STATUS) FULL='f', UNPAID='n' PARTIAL='p' PAYMENT_STATUS=( ('FULL','Full'), ('UNPAID','UnPaid'), ('PARTIAL','Partial') ) payment_status = models.CharField(max_length=10,choices=PAYMENT_STATUS) application_date=models.DateTimeField(auto_now=True) school = models.ForeignKey( schooldetail, on_delete=models.CASCADE, blank=True, null=True, ) Serializer from rest_framework import serializers from enrolments.models import studentdetails,schooldetail from .models import EnrollmentModel from enrolments.serializers import StudentDetailSerializer,SchoolDetailSerializer class EnrollSerializer(serializers.ModelSerializer): school= serializers.SerializerMethodField('get_school') def get_school(self, instance): school=instance.schoolbranch return school student= serializers.SerializerMethodField('get_student') def get_student(self, instance): student=instance.first_name return student class Meta: model:EnrollmentModel fields=['id','school','student','enrolment_status','payment_status'] --views @api_view(['GET']) @permission_classes((AllowAny,)) def full_list(request): try: school_queryset = EnrollmentModel.objects.all() serializer = EnrollSerializer(school_queryset, many=True) return Response(serializer.data) except schooldetail.DoesNotExist: return Response(status … -
Django model conditionally based on two abstract classes
I have more of a conceptual question, but with practical implications. In a Django 4.1.x app, I have one owner class which can be either a person or an organization, but never both together. These two classes doesn't need to be registered in the database, only the owner has to: from django.db import models class Person(models.Model): first_name = models.CharField( max_length=256, verbose_name=_("First name"), null=False, ) # other person attributes class Meta: abstract = True def __str__(self): return self.first_name class Organization(models.Model): full_name = models.CharField( max_length=256, verbose_name=_("Full name"), null=False, ) # other organization attributes class Meta: abstract = True def __str__(self): return self.full_name Whatever the owner instance is, it must have a name attribute: In the case of a person, the owner's name has to be the first_name and in case of an organization, the full_name. Also, if an owner object is an instance of a Person: I only want to expose those other attributes of Person. Same goes if owner is an instance of an Organization. I certainly miss some concepts here / maybe I'm not looking in the right direction, but how to build the owner model based on a type of "conditional or parametrized inheritance", let's say? Please, note that … -
access django-apscheduler's jobs properties programmatically
I use the django-apscheduler package to run cron (scraping) jobs. the package stores the past jobs with some information/properties (e.g. local runtime, duration etc.) somewhere on the database for display on the admin backend. When I want to access these information/properties about the jobs programmatically in the views.py (e.g. to show the last runtime of a job in the context/template), how would I do that? -
How to optimize queries in Django Rest Framework serializers (DRF)?
info: I have component model with search_tags field which is a many to many field with Search model and i have a serializer for Component model which is ComponentSerializer and i using get_videos method to get videos for each component and i want to get videos for each search tag in search_tags field and store them into a filtered_data_list and return it as a response The response time is very slow and i want to optimize it and i don't know how to do it (I am new to django and rest framework) These are methods i studied but i don't know how to use them in my case and i don't know if they are the best way to do it or not: prefetch_related and select_related but it didn't work. Use raw sql query but i don't know how to do it. Use django cache but i don't know how to do it. Use django cache and raw sql query but i don't know how to do it. class ComponentSerializer(serializers.ModelSerializer): ''' component serializer ''' videos = serializers.SerializerMethodField() class Meta: model = Component fields = ['title', 'slug', 'videos'] def get_videos(self, obj): filtered_data_list = [] for search in obj.search_tags.select_related('component').filter(is_active=True): ''' Thumbnails … -
Stylesheets to use in django-ckeditor
I'm using django-ckeditor which is a TextArea WYSIWYG editor for creating and editing posts in a future blog. The editor produces beautiful posts, but when I save to the database and go to view it, it appears without the style I initially created in the editor. See the following code: {%load static%} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>MyDomain | {{post.title}}</title> <link href="{% static 'ckeditor/ckeditor/contents.css'%}" rel="stylesheet"> </head> <body> <h1>{{ post.title }}</h1> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|safe|linebreaks }} </body> </html> My question is: which styles do I import to present the same view as when I created the post? -
Optimizing dynamic filter
I have this funciton def get_documents_by_metadata(self, params): filters = {} result_filtered = None for index, key in enumerate(params.keys()): filters["metadocument__meta_config__field"] = key filters["metadocument__value__contains"] = params.get(key) if index == 0: result_filtered = super().get_queryset().filter(**filters) else: result_filtered = result_filtered.filter(**filters) return result_filtered I need to filter by dynamic values ( KEY/VALUE metadata registered in my DB), I can't predict what keys Im goint to recieve. My first idea is filter and filter again the result, but I'm sure that exist better way. Ty! -
what are best solutions for hold OTP
I want to create a no password system so user login with email and i sent verification code to the user. user enter email and send request server check email if exist send the otp number to user’s email server need hold otp number so later on compare with user number i want to now in the server side what is the best solution for hold otp code db, file, etc I want to achieve best security and speed for APIs. -
Looking for best practices for Django queries in Python classes
Say I have a Django model Model1 and I have a python class Class1. Class1 has some properties that are derived from values in Model1. What is the best way to accomplish this? Gain access to Mode1 in the Class1 __init__ method, or access Model1 in the Class1 property? Not sure how to define "best way" - more pythonic, more efficient, etc? A very contrived example of what I am asking: class Model1(models.Model): model_id = models.AutoField(primary_key=True) field1 = models.CharField() field2 = models.CharField() class Class1: def __init__(self, value1, value2): self.value1 = value1 self.value2 = value2 self._model1 = Model.objects.get(model_id=self.value1) @property def value3(self): return self._model1.field1 * 10 @property def value4(self): field2 = Model.objects.get(model_id=self.value2).field2 return field2 * 22 Which paradigm is "better" - the property for value4 or value3? I am going to guess the the property for value4 is more efficient because the Model1 query set does not hang around in memory as it does when it is contained in the Class1 __init__. Thanks! -
html2pdf Resize and Fix Copying Onto Same Page
I have the following below: <div> <button id="btn">screenshot</button> </div> <script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.0.0-rc.7/dist/html2canvas.min.js"></script> <script> window.onload = function () { console.log("Window is loaded") document.getElementById('btn').addEventListener("click", function () { html2canvas(document.getElementById('test')).then(function (canvas) { document.body.appendChild(canvas); var imgdata = canvas.toDataURL("image/jpg"); var doc = new jspdf.jsPDF(); doc.addImage(imgdata, "JPG", 10, 10); doc.save("sample.pdf"); }); }) } </script> It works BUT not well. The two problems I can't solve are: It opens a PDF with a screenshot of a small section of the page, like it's too zoomed in. It also puts a screenshot of the page on the page itself, this screenshot is stored in my browser session and goes away on a fresh reload. I don't know which part of the code is responsible for that, so I don't how to stop it from doing this. If there was a way to get that screenshot copied to another .html page and the user can view it from there, that might be a workaround. However, I don't know how to manipulate the code to get it to do that and I am only a beginner with javascript/html2pdf; Python is the only language I know right now. I am using DJANGO as my framework if this matters. Thank you! I … -
Django is not rendering my static file (css, images, etc)
I am able to view my site (html)in the browser but none of my mark-up is working. I have checked my stylesheet links for types, settings.py, but I am at a lost. When I run my site I am getting the below responses in my terminal. `[10/Nov/2022 20:46:23] "GET / HTTP/1.1" 200 168 [10/Nov/2022 20:46:23] "GET /static/css/main.css HTTP/1.1" 404 1795 [10/Nov/2022 20:46:23] "GET /static/images/6%2Bcart.png HTTP/1.1" 404 1810` I have tried going over everything possible but cannot locate the issue, any and all feedback would be greatly appreciated. I am not allowed to post images yet so unfortunately, I could not include. I have re-coded, deleted and remade static folder, scoured the internet with no luck yet. -
JWT token authentication in Github Social Authentication
I am working with django github social authentication using dj_rest_auth. I am trying to add JWT token authentication in it. I am trying to get access_token and refresh_token. To get it i want to enter username and password in api view.In social authentication login there is no password. we have Only username and mail id. Is it possible to access token by using only username? If Yes. How is it possible? -
Restrict users to see detailview based on model field value in Django
I am learning and have a change management project where my model contains field confidential which is by default False, however during instance creation so called initiator could tick it as True. This basically means that only users which are part of current record so called signees could open and see the instance. I am trying to apply get_queryset override on my DetailView: # MOC DetailView class MocDetailView(LoginRequiredMixin, DetailView): model = Moc template_name = 'moc/moc_detail.html' def get_queryset(self, *args, **kwargs): qs = super().get_queryset(*args, **kwargs) for obj in qs: print(obj) confidential = obj.confidential initiator = obj.initiator coordinators = obj.coordinators.all() reviewers = obj.reviewers.all() approvers = obj.approvers.all() preimplements = obj.preimplements.all() authorizers = obj.authorizers.all() postimplements = obj.postimplements.all() closers = obj.closers.all() if initiator and initiator == self.request.user and confidential == True: qs = qs.filter(Q(confidential=True) & Q(initiator=self.request.user)) return qs for signee in coordinators: coordinator_name = signee.coordinator_name if coordinator_name and coordinator_name == self.request.user and confidential == True: qs = qs.filter(Q(confidential=True) & Q(coordinators__coordinator_name=self.request.user)) return qs for signee in reviewers: reviewer_name = signee.reviewer_name if reviewer_name and reviewer_name == self.request.user and confidential == True: qs = qs.filter(Q(confidential=True) & Q(reviewers__reviewer_name=self.request.user)) return qs for signee in approvers: approver_name = signee.approver_name if approver_name and approver_name == self.request.user and confidential == True: qs = qs.filter(Q(confidential=True) … -
Django Model Serializer manyToMany relationship
I have problem with Django 4.1.2 (Python 3.8.9). I have 2 entities: Idea and IdeaTheme, which have manyToMany relationship. class Idea(models.Model): short_name = models.CharField(max_length=70) description = models.TextField(null=True, blank=True, default='') class State(models.IntegerChoices): CREATED = 0, _("Создано") TEAM_SEARCHING = 1, _("Поиск команды") IN_PROCESS = 2, _("Реализация") READY = 3, _("Готово") state = models.IntegerField(choices=State.choices, default=State.CREATED) wanted_skills = models.ManyToManyField(to=UserSkill) themes = models.ManyToManyField(to=IdeaTheme, null=True, blank=True) class IdeaTheme(models.Model): name = models.CharField(max_length=70, verbose_name="Название") background_photo = models.ImageField(blank=True, null=True, verbose_name="Изображение для фронта") Also I have ModelSerializer class IdeaSerializer(serializers.ModelSerializer): class Meta: model = Idea fields = '__all__' depth = 1 extra_kwargs = { 'state': { 'read_only': True }, 'pk': { 'read_only': True } } And when I using CreateAPIView in order to create Idea I face the problem, that I must provide IdeaTheme pks. But in the model there are Null and Blank option and I want to create idea without IdeaThemes. I tried to specify IdeaTheme serializer inside IdeaSerializer like this, but Django still require not empty array of IdeaTheme. themes = IdeaThemeSerializer(many=True, required=False) Could someone help me, please, who already has experience using built-in serializers? -
Uploading Image from angular to Django using Rest Api Angular 13 / Django 4.1 Rest Framework
I'm trying to upload an image from Angular to Django using Rest framework, When I try uploading i got the following error : UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 177: invalid start byte So i tryied most of all the answers but no success. Angular v13 Django v4.1 This is My class Model that I'm trying to fetch : ` class Product(models.Model): famille = models.ForeignKey(Famille, on_delete=models.CASCADE) tva = models.ForeignKey(Tva, on_delete=models.CASCADE) poidsUnity = models.ForeignKey(Poids, on_delete=models.CASCADE, null=True) tailleUnity = models.ForeignKey(Taille, on_delete=models.CASCADE, null=True) couleur = models.ForeignKey(Color, on_delete=models.CASCADE, null=True) marque = models.ForeignKey(Marque, on_delete=models.CASCADE, null=True) poids = models.FloatField(null=True) taille = models.FloatField(null=True) photo = models.ImageField(upload_to='pics', null=True, blank=True) ``` ` This is My Serializer Class : class ProductSerializer(serializers.ModelSerializer): photo = Base64ImageField( max_length=None, use_url=True, allow_empty_file=True, allow_null=True, ) class Meta: model = Product fields = '__all__' ``` ``` ``` ` This is My Views : @csrf_exempt def productCrud(request, id=0): if request.method == 'GET': if id != 0: products = Product.objects.filter(id=id).first() products = ProductSerializer(products) else: products = Product.objects.all() products = ProductSerializer(products, many=True) return JsonResponse(products.data, safe=False) elif request.method == 'POST': product = JSONParser().parse(request) product = ProductSerializer(data=product) if product.is_valid(): product.save() return JsonResponse(product.data, safe=False) return JsonResponse(product.errors, safe=False)` ` urls.py : ` urlpatterns = [ # full path /product/ [get, post, … -
Django - Form that lists the fields for every foreign key
I have this 2 models: class AccountsPlan (models.Model): code = models.CharField(max_length=7, unique=True) name = models.CharField(max_length=100, unique=True) active = models.BooleanField(default=True) class Planning (models.Model): accountplan = models.ForeignKey(AccountsPlan, on_delete=models.PROTECT, limit_choices_to={'active': True}) month = models.DateField() amount = models.DecimalField(max_digits=14, decimal_places=2) This form: class PlanningForm(forms.ModelForm): accountplan = ModelChoiceField(queryset=AccountsPlan.objects.filter(active=True).order_by('code')) month = forms.DateField(required=True) amount = forms.DecimalField(max_digits=14, decimal_places=2, required=True, localize=True) class Meta: model = Planning fields = '__all__' And this view: def new_planning(request): if request.method == 'POST': form = PlanningForm(request.POST) if form.is_valid(): form.save() else: form = PlanningForm() return render(request, 'app/pages/planning/new_planning.html', context={ 'form': form, }) The form works as intended, but right now, I have more than a 100 entries in the AccountsPlan model and this number will increase overtime. The user needs to fill the PlanningForm every month for every foreign key in the AccountsPlan model, so filling one by one is not ideal. Since the month field will be the same for every foreign key and only the amount field is different, what I'm trying to do is this: The form lists every foreign key with an amount field for each one and a single month field. The user selects de date and enter just the amount and that saves the data. I tried this answer and managed … -
Unable to load css while running django in docker
If I access http://0.0.0.0:8000/admin/ The console says the following and the css does not load. The Cross-Origin-Opener-Policy header has been ignored, because the URL's origin was untrustworthy. It was defined either in the final response or a redirect. Please deliver the response using the HTTPS protocol. You can also use the 'localhost' origin instead. See https://www.w3.org/TR/powerful-features/#potentially-trustworthy-origin and https://html.spec.whatwg.org/#the-cross-origin-opener-policy-header. My settings is as follows: ALLOWED_HOSTS = ['0.0.0.0', '127.0.0.1', 'localhost'] DISABLE_COLLECTSTATIC = 0 # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "books.apps.BooksConfig", "debug_toolbar", "corsheaders", "django.contrib.postgres", "django_celery_beat", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "corsheaders.middleware.CorsMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "debug_toolbar.middleware.DebugToolbarMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", ] ROOT_URLCONF = "search.urls" LOGIN_REDIRECT_URL = "home" LOGOUT_REDIRECT_URL = "home" CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:8000', 'https://localhost:8000', 'http://0.0.0.0:8000', 'https://0.0.0.0:8000', 'http://127.0.0.1:8000', 'https://127.0.0.1:8000' ) TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [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", ], }, }, ] STATIC_URL = "/static/" -
Get Data Problem with Foreignkey Models QuerySet (Django)
I am making django practising. I found a repo and edited to myself. When i came to the get data from models with foreignkey, i get query instead of data. I think my function is a little bit spagetti or my template file. Full repo is here https://github.com/eseymenler/demo2 Here is the output of my codes. First red square is query, but i want second red square datas. Hasta Adı: {{ patient.name }} Hastanın Sağlık Problemi: {{ prob }} Hastanın Boyu: {{ vital }} Hastanın Sigara Kullanım Durumu: {{ social }} First data {{ patient.name }} is very good for me. Thats what i want. But when i get write {{ prob.problem }} it gives me nothing. So where is my fault. But also when i make for loop like this, i get data which i want. So how can i fix this. {% for y in prob %} {{ y.problem }} {% endfor %} And my views.py @login_required() def patienttumbilgiListView(request, id): patient = Patient.objects.get(aadhaarId = id) prob = ProblemList.objects.filter(patient = patient) vital = VitalSign.objects.filter(patient = patient) social = SocialHistory.objects.filter(patient = patient) return render( request, 'patient_records/patient-problem-tum.html', context={'prob': prob, 'vital': vital, 'social': social, 'patient': patient }) and my template file {% extends … -
(MacOS) Django can't find the MySQL driver ... but, why?
Here's the traceback: Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/mike/.virtualenvs/djangoprod/lib/python3.10/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/mike/.virtualenvs/djangoprod/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so, 0x0002): Library not loaded: '@rpath/libmysqlclient.21.dylib' Referenced from: '/Users/mike/.virtualenvs/djangoprod/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so' Reason: tried: '/usr/lib/libmysqlclient.21.dylib' (no such file) And here's the problem: $ locate libmysqlclient [...] /usr/local/mysql-8.0.31-macos12-x86_64/lib/libmysqlclient.21.dylib So, the library is there, but Django isn't finding it. So, before I "bang my head uselessly against this thing," especially given that it used to work, will someone out there kindly give me a nudge in the right direction? What am I missing here? I particularly notice that the package is trying the path, /usr/lib... when that is not in fact the proper location here. In particular: I see in the text a reference to @rpath which I am sure is the root cause of the problem – obviously, the value is wrong. (I notice that it does have the library-name right.) I'm frankly not familiar with this @rpath thing, nor exactly what sets it. Thank you kindly in advance ... -
Django Channels Freezes when calling internal Django-Filters API
I am using django-nextjs which required me to install Django Channels. Now this works fine until my frontend makes an API call to a DRF APIView which in turn makes an API call to Django-Filters to return a queryset. This freezes the entire server until the connection times out. Do you have an idea how this could be fixed? My asgi.py import os from django.core.asgi import get_asgi_application from django.urls import re_path, path os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.production') django_asgi_app = get_asgi_application() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django_nextjs.proxy import NextJSProxyHttpConsumer, NextJSProxyWebsocketConsumer from django.conf import settings http_routes = [re_path(r"", django_asgi_app)] websocket_routers = [] if settings.DEBUG: http_routes.insert(0, re_path(r"^(?:_next|__next|next).*", NextJSProxyHttpConsumer.as_asgi())) websocket_routers.insert(0, path("_next/webpack-hmr", NextJSProxyWebsocketConsumer.as_asgi())) application = ProtocolTypeRouter( { # Django's ASGI application to handle traditional HTTP and websocket requests. "http": URLRouter(http_routes), "websocket": AuthMiddlewareStack(URLRouter(websocket_routers)), # ... } ) And here is my APIView with the internal API call to Django Filters class SearchAPI(APIView): permission_classes = [] def get(self, request, *args, **kwargs): received_params = {} ... full_request = f"{settings.BASE_URL}api/filter-recipes/?{col_to_search}__icontains={search_term}{additional_filters}" print('full_request: ', full_request) response = httpx.get(full_request) print('response: ', response) response = response.json() response = response["results"] if "results" in response else response ... return Response(json.dumps(final_response)) Everything freezes upon calling the get: 'response = httpx.get(full_request)', is there anyway I … -
Filter the logged in Users groups in before saving Django
Hi upon registering a new user all the groups are listed for the user to select from the drop down. I am trying to filter this to only the groups that the logged in user is part of. views.py from .forms import UserRegisterForm @login_required(login_url='login') def addUser(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save() group = form.cleaned_data['group'] group.user_set.add(user) return redirect('login') else: form = UserRegisterForm() return render(request, 'base/adduser.html', {'form':form}) forms.py from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): group = forms.ModelChoiceField(queryset=Group.objects.all(), required=True) class Meta: model = User fields = ['username', 'password1', 'password2', 'group'] adduser.html > {% extends 'main.html' %} > > {% block content %} <style> > .home-container{ display:grid; grid-template-columns: 1fr 4fr; > > } </style> <div class="home-container"> > > > > <div> > > </div> > <div> > {% include 'settingmenu.html' %} > > </div> > <div></div> > <div> > <form method="POST" action=""> > {% csrf_token %} > > {{form.as_p}} > > <input type="submit" value="Add User" /> > </form> > > > > </div> </div> {% endblock %} -
Why django admin is not reading the __str__ method?
I'm trying to add a str method in my models.py file to my administrative page show me the objects I've register with their own name and not like a 'UserObject(1)' But when I add this method that's what is happening: AttributeError at /admin/crud_app/user/ 'User' object has no attribute 'first_name' models.py -> from django.db import models class User(models.Model): """ A normal class that represents an User object, the attributes are those bellow: """ first_name = models.CharField(name="First Name", max_length=30) last_name = models.CharField(name="Last Name", max_length=30) cpf = models.CharField(name="CPF", max_length=30) age = models.IntegerField(name="Age") email = models.EmailField(name="email", max_length=30) def __str__(self): return self.first_name admin.py -> from django.contrib import admin from .models import User admin.site.register(User) I try to add the str method and I'm was expecting to recive the name that I give to my object registered instead of 'Name object(1)' -
How can I create an index with django that takes into account multiple columns and most importantly a 5 second interval
I want to create an interval for a table that says "each entry will be unique based on it's col a, col b, col c, and a 5 second interval" For example I want to be able to do something like this: class Meta: indexes = [ models.Index(fields=['col_a',]), models.Index(fields=['col_b',]), models.Index(fields=['col_c',]), models.Index(expression='five second interval') ] Is this possible? If so what's the right way to do something like this?