Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show a field seperately in drf
I have Reviews & Ratings serializer. I want to show the total count of reviews in response. The current implementation I am getting review count but it shows on all review response like below: [ { "review_count": 2, "user": "don sebastian", "rating": 3.9, "review": "Rating for pendant 1 by Don", "created_at": "2022-11-27", "updated_at": "2022-11-27" }, { "review_count": 2, "user": "Jackson Patrick Gomez", "rating": 4.5, "review": "cool review Pendant 1", "created_at": "2022-11-27", "updated_at": "2022-11-29" } ] What I want to get is like this review_count seperatley [ "review_count": 2, { "user": "don sebastian", "rating": 3.9, "review": "Rating for pendant 1 by Don", "created_at": "2022-11-27", "updated_at": "2022-11-27" }, { "user": "Jackson Patrick Gomez", "rating": 4.5, "review": "cool review Pendant 1", "created_at": "2022-11-27", "updated_at": "2022-11-29" } ] #Serializer.py class ReviewSerializer(ModelSerializer): user = SerializerMethodField() review_count = SerializerMethodField() class Meta: model = ReviewRatings fields = ["review_count", "user", "rating", "review", "created_at", "updated_at"] def get_user(self, obj): return f"{obj.user.first_name} {obj.user.last_name}" def get_review_count(self, obj): -
Web page I am scraping requires credit card details to work. Any idea how I can keep my credit card info secure?
Hello I have a Django/postgres backend service that starts jobs with my webscraper service running puppeteer/express. Additionally, all these services are running on Dokku. The webscraper goes and purchase products from websites and thus need to enter my credit card number each time. Kind of scared about storing my credit card number some where and what service to give it to. I have never done this before. Should have I just hash the credit card number and store it in an environment variable or is there any better ideas? -
Software for creating interactive forms [closed]
my problem is in relation with structuring text. i am searching for a opportunity that helps me structuring text. It should be able to create a fillable form and generate an PFD out of this. Hope you have any idea... -
Problem of signature with webauthn on django with djoser
I'm working at the moment on an implementation of webauthn on a project. The main point is to give the possibility to user to use FaceId or fingerprint scan on their mobile on the website. I tried the djoser version of webauthn but I wanted to give the possibility to user that already have an account so I took the implementation of webauthn of djoser and I updated it to make it working with already created account. I can ask for the signup request of a webauthn token and create the webauthn token with the front (Angular) where I use @simplewebauthn/browser ("@simplewebauthn/browser": "^6.3.0-alpha.1") . Everything is working fine there. I use the latest version of djoser by pulling git and the version of webauthn is 0.4.7 linked to djoser. djoser @git+https://github.com/sunscrapers/djoser.git@abdf622f95dfa2c6278c4bd6d50dfe69559d90c0 webauthn==0.4.7 But when I send back to the backend the result of the registration, I have an error: Authentication rejected. Error: Invalid signature received.. Here's the SignUpView: permission_classes = (AllowAny,) def post(self, request, ukey): co = get_object_or_404(CredentialOptions, ukey=ukey) webauthn_registration_response = WebAuthnRegistrationResponse( rp_id=settings.DJOSER["WEBAUTHN"]["RP_ID"], origin=settings.DJOSER["WEBAUTHN"]["ORIGIN"], registration_response=request.data, challenge=co.challenge, none_attestation_permitted=True, ) try: webauthn_credential = webauthn_registration_response.verify() except RegistrationRejectedException as e: return Response( {api_settings.NON_FIELD_ERRORS_KEY: format(e)}, status=status.HTTP_400_BAD_REQUEST, ) user = User.objects.get(username=request.data["username"]) user_serializer = CustomUserSerializer(user) co.challenge = … -
Django json response stay in the same page
I'm making a like button for a post in django. What I need is that when the like button is clicked, the function is executed, but I need the page not to be reloaded (To later use javascript). To do that I return a jsonresponse() instead of a return render. But the real problem is that it redirects me to the page that I show in the photo. The page is not reloaded. as I want it. but I don't want it to show me the blank page with the jsonresponse data (like this photo).I want to stay in the same page without reload. Thanks in advance! My view function: def liking (request, pk): posts = get_object_or_404(Post, id = pk) if request.user in posts.likes.all(): posts.likes.remove(request.user) else: posts.likes.add(request.user.id) likes_count = posts.likes.all().count() print(f'likes_count = {likes_count}') data= { 'likes_count': likes_count, } #return redirect ('index')# This is commented return JsonResponse(data, safe=False, status=200 ) -
Products are not displayed when simple search on django
I do search on Django and faced with a problem: products are not displayed. I dont understand why views class SearchView(ListView): template_name = 'store/products.html' def get_queryset(self): query = self.request.GET.get('search', '') if query: products = Product.objects.filter(Q(name__icontains=query) | Q(description__icontains=query)) else: products = Product.objects.all() return products search template <form class="form-inline mb-3" action="{% url 'search' %}" method="get"> <div class="form-group col-8 col-md-10 pl-0"> <input class="form-control w-100" type="search" placeholder="Поиск по сайту" name="search"> </div> <div class="form-group col-4 col-md-2 pl-0"> <button class="btn btn-info" type="submit">Найти</button> </div> </form> products template {% extends 'base.html' %} {% block title %} List {% endblock %} {% block content %} <body style="background-color: whitesmoke;"> {% for product in products %} <main class="container mt-3" style="text-align: center; max-width: 500px;"> <div style="border: 5px solid white; background-color: white;"> <a href="{% url 'product_detail' product.id %}"> <img src="{{ product.image.url }}" style="width:15vh; height:auto;"><br> </a> <p style="font-size: 20px">{{ product.name }}</p> <p style="font-size: 22px">{{ product.price }} руб.</p> <form method="post" action="{% url 'cart_add' product.id %}"><br> <p style="display: none"></p> {{ form }} {% csrf_token %} {% if request.user.is_authenticated %} <input type="submit" value="Add to cart"> {% else %} <p></p> {% endif %} </form> </div> </div> </div> </main> {% endfor %} </body> {% endblock %} I did the same search and all good. I think problem with templates … -
create Model objects inside another models's Adminview
I'm trying to generalize access permissions to certain Nodes for each of my Groups. I have an Access Model model with three different fields: access_type, group and node. Each group can have either Source, Destination or Bidirectional Access to a node which has a name: class Access(models.Model): class AccessType(models.TextChoices): BIDIRECTIONAL = "bi", "Bidirectional" SOURCE = "src", "Source" DESTINATION = "dst", "Destination" access_type = models.CharField(max_length=3, choices=AccessType.choices) group = models.ForeignKey(Group,on_delete=models.CASCADE, related_name='GroupAccess') node = models.ForeignKey(DicomNode, on_delete=models.CASCADE) name = models.CharField(unique=True, max_length=128, null = True) Similar to the common permission view inside the adminView I'd like to create Access objects inside the GroupView, so that they are created with the group which I am inside at the moment. Also, I'd like them do be displayed on the left side with all available Accesstypes and nodes, seperated with an '|' just like all the available permissions: enter image description here I have done the same already with a form to add existing users to a group: class GroupForm(forms.ModelForm): users = forms.ModelMultipleChoiceField( label='Users', queryset=User.objects.all(), required=False, widget=admin.widgets.FilteredSelectMultiple( "users", is_stacked=False)) class Meta: model = Group exclude = () # since Django 1.8 this is needed widgets = { 'permissions': admin.widgets.FilteredSelectMultiple( "permissions", is_stacked=False), } class MyGroupAdmin(GroupAdmin): form = GroupForm list_display … -
how to add pagination in Django?
I want to apply pagination on my data I tried to watch lots of videos and read lots of articles but still can't solve my problem. This is my Views. def car(request): all_products = None all_category = category.get_all_category() categoryid = request.GET.get('category') if categoryid: all_products = Product.get_all_products_by_id(categoryid) else: all_products = Product.get_all_products() data = {} data['products'] = all_products # all products data['category'] = all_category # all category all_products = Product.get_all_products() data['product'] = all_products ] return render(request, 'car.html', data) as you can see I made some changes in above code but its make no diffrence def car(request): all_products = None all_category = category.get_all_category() categoryid = request.GET.get('category') if categoryid: all_products = Product.get_all_products_by_id(categoryid) else: all_products = Product.get_all_products() #pagination paginator = Paginator(all_products,2) **Changes** page_number=request.GET.get('page') **Changes** finaldata=paginator.get_page(page_number) **Changes** data = {'all_products':finaldata,} **Changes** data['products'] = all_products #all products data['category'] = all_category #all category all_products = Product.get_all_products() data['product'] = all_products return render(request, 'car.html', data) I want to display 4 products per page I tried to apply data limit query that work but that not a genuine approach to display data. I read many articles and watch YouTube video. but can't find any solution. which videos and articles I watched there pagination method is totally different they use pagination with … -
Django form with multi input from loop save only last record to database
I have a problem with saving data from a form in django. Only the last record is saved. I generate a list of dates (days of the month) in the view and display it in the form in templates along with the fields next to the type. Everything is displayed correctly in templates, but when I submit to, only the last record from the form appears in the save view. What am I doing wrong, can someone help? forms.py ''' class DoctorsSchedule(forms.ModelForm): # work_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-21:00') # official_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-19:00') class Meta: model = DoctorSchedule fields = ['date', 'day_type', 'work_hours', 'scheme', 'official_hours'] ''' model.py ''' class DoctorSchedule(models.Model): id = models.AutoField(primary_key=True, unique=True) date = models.DateField(blank=True, null=True) day_type = models.CharField(max_length=255, blank=True, null=True, default='Pracujący') work_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-21:00') scheme = models.CharField(max_length=255, blank=True, null=True, default='20') official_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-19:00') def __str__(self): return self.date ''' view.py ''' def terminarz(request): today = datetime.now() now = date.today() locale.setlocale(locale.LC_TIME, 'pl_PL') def months(): months = {'1': 'Styczeń', '2': 'Luty', '3': 'Marzec', '4': 'Kwiecień', '5': 'Maj', '6': 'Czerwiec', '7': 'Lipiec', '8': 'Sierpień', '9': 'Wrzesień', '10': 'Październik', '11': 'Listopad', '12': 'Grudzień'} return months ##################### days of month list ###################################### def days_of_month_list(): … -
Using Django Bad Request
I'm new in Django and Rest Framework and I didn't find how to do that: Filter an endpoint request without argument to return Bad Request. Example: get_foo/?foo_id= Return: { "status": 400, "error": "Bad Request" } At this time, a get request without argument gives all the values from the database. It's a big DB, so I have to do this filter. -
How can I toggle databases in Django?
Django's settings.py file has a DATABASES dictionary that stores configuration information for any number of database backends: # settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'test': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'testing', 'USER': 'bert', 'PASSWORD': '***', 'HOST': 'remotemysql.com', 'PORT': '3306', }, 'dev': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'development', 'USER': 'ernie', 'PASSWORD': '***', 'HOST': 'remotemysql.com', 'PORT': '3306', }, ... } I would expect the Django authors to have included a method to easily switch among these configuration options, such as a separate variable somewhere USE_THIS_DB = 'test'; in order to easily switch between testing, development, production, etc. databases. I can't find this option. The only information I can find about switching databases is to manually rename the different configuration options in DATABASES so that the one I want to use is called default, which seems unnecessarily clunky, error-prone, and non-portable. Is there no way to more elegantly switch Django among different databases at startup? -
How to do a good callback function with django rest framework
I would like to write an api with django rest framework, I got some issues with my callback function. I can get the access code, but how to give it to my app? This is my callback function : @api_view(['GET']) def callback(request): if request.method == 'GET': code = request.GET.get("code") encoded_credentials = base64.b64encode(envi.SECRET_ID.encode() + b':' + envi.SECRET_PASS.encode()).decode("utf-8") token_headers = { "Authorization": "Basic " + encoded_credentials, "Content-Type": "application/x-www-form-urlencoded" } token_data = { "grant_type": "authorization_code", "code": code, "redirect_uri": "http://127.0.0.1:800/callback" } test = "test :" + code return JsonResponse(test, safe=False) And this is my view where I try to do some stuff (I use spotify's API, with spotipy), I need to get the users name or mail : @api_view(['GET']) @permission_classes([permissions.IsAuthenticated]) def test(request): if request.method == 'GET': test = "test " + request.user.username scope = "user-read-private" sp = getScope(scope) print(sp.current_user()) urn = 'spotify:artist:3jOstUTkEu2JkjvRdBA5Gu' sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=envi.SECRET_ID, client_secret=envi.SECRET_PASS, redirect_uri=envi.SPOTIPY_REDIRECT_URI)) artist = sp.artist(urn) print(artist) user = sp.current_user() return JsonResponse(user, safe=False) def getScope(spotipyScope): token = SpotifyOAuth(scope=spotipyScope,client_id=envi.SECRET_ID, client_secret=envi.SECRET_PASS, redirect_uri=envi.SPOTIPY_REDIRECT_URI) spotifyObject = spotipy.Spotify(auth_manager= token) return spotifyObject When I do a get on 127.0.0.1:8000/test/, I have a new page on my browser, from spotify, I connect my account, and then, it redirects me on 127.0.0.1:8000/callback/?code=some_code How can I give it to … -
LoginRequiredMiddleware - redirection to previous page after allauth path not working
I implemented LoginRequiredMiddleware so that when user connect to any page of the app, they are redirected to the login_page. Once the login, or sign they are redirected to the page they previoulsy landed on. To do that I am using a path variable (code at the end) which is then used in both login and register views. This work fine for classic the login and register. However, I have also implemented allauth and when a user sign up with, say Google, the redirection to previous page is not happening and the user is redirect to LOGIN_REDIRECT_URL. This is because I haven't created a specific view for google sign up. I suppose there is 2 options from there: create a google sign up view and use the path variable - I am not sure how to (the biggest problem); There is an easier around the problem. middleware.py import re from django.conf import settings from django.shortcuts import redirect from django.contrib.auth.views import redirect_to_login from django.urls import reverse .. class LoginRequiredMiddleware: pass def __init__(self, get_response): self.get_response = get_response def __call__ (self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): assert hasattr(request,'user') path = request.path_info.lstrip('/') print(path) if not request.user.is_authenticated: if … -
Django: Is it possible to upload a file from a known local path with a button click only?
I need users to upload a particular system file and handle it in a views.py. Since I already know the absolute path of the file I need from the user's computer (e.g. '/Users/JohnDoe/Application\ Support/blah/blah.plist'), I'm wondering if it's possible to achieve this with a single click, without having to have the user select the file from file picker UI. If this is not possible, is it possible to set the starting location of file picker UI to pre-select the file when it opens? Despite spending a lot of time researching, I wasn't able to find an example suiting my needs given the unique use case. -
Imap not login with godaddy domain (imaplib.error: b'[AUTHENTICATIONFAILED] Authentication failed.)
the imap.py connect function work with gmail but not with other like godaddy code is here ` def connect(self, username, password): self.server = self.transport(self.hostname, self.port) if self.tls: self.server.starttls() typ, msg = self.server.login(username, password) if self.folder: self.server.select(self.folder) else: self.server.select() ` i got imaplib.error: b'[AUTHENTICATIONFAILED] Authentication failed. error try to connect with imap through login but got error Authentication failed imaplib.error: b'[AUTHENTICATIONFAILED] Authentication failed.' -
How do I create a profile by fetching data from an html form ? (Using JS, Django in backend)
I tried to fetch the data from the below file and display as a profile on a different page named 'startups.html'. Every person who fills the following profile form, his/her profile should be displayed on the 'startups.html' page. <form action="startups" name="createprofile" method="get" onclick="prof()"> {% csrf_token %} Company Image<input type="image" id="c_img" name="c_img" > Company Name<input type="text" id="c_name" name="c_id" > Startup or Investor <input type="text" id="c_type" name="c_type" > Username<input type="text" id="username1" name="username1" > Password<input type="text" id="password1" name="password1" > Confirm Password<input type="text" id="con_pass1" name="con_pass1" > <button type="submit" id="profile_sub" onclick="prof()">SUBMIT</button> <!-- <button type="submit" id="createprof_submit"><a href="" action="/startups" name="startups">SUBMIT</a></button>--> </div> </form> -
Problem with annotate Sum When Case after django upgrade
So I have a problem with upgrading django. models.py: class TrackReport(BaseMixin): value = models.PositiveIntegerField() archive = models.ForeignKey("Archive", related_name="track_reports", on_delete=models.PROTECT) date = models.DateField(db_index=True) Query: qs = Archive.objects qs = qs.annotate( filtered_by_date_min=Sum( Case(When(track_reports__date__gte=date_min, then=Value(1)), default=Value(0), output_field=IntegerField()) ) ).filter(filtered_by_date_min__gt=0) python 3.8, django 1.12, postgres 15 no problem python 3.11 django 4.1.2, postgres 15: ../../mambaforge/envs/new_sponsordata_arm/lib/python3.11/site-packages/django/db/models/sql/query.py:1289: in build_lookup lookup_class = lhs.get_lookup(lookup_name) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = Sum(CASE WHEN <WhereNode: (AND: In(Col(archive_trackreport, archive.TrackReport.type), ['FACEBOOK_POPULARITY']))> THEN Value(1), ELSE Value(0)) lookup = 'gt' def get_lookup(self, lookup): > return self.output_field.get_lookup(lookup) E AttributeError: 'IntegerField' object has no attribute 'get_lookup' ../../mambaforge/envs/new_sponsordata_arm/lib/python3.11/site-packages/django/db/models/expressions.py:377: AttributeError I know it's been ages but did anything change? -
Categorie sorting HTML JINJA
I have some problem with fronend, select tag html code. I have creating sorting option. All is working fine if it is like a list or block (depending from villing), but then i truing to make a dropdown and add select tag all categorys gone , only ALL STATUS. Could you please explain me there is my mistake and why ? MY HTML <div class="top-selector-right"> <select name="status-candidate"> {% if stat_selected == 0 %} <div class="top-selector-right"> <option><a class="nav-link"><i class="fa-solid fa-bars"></i> ALL STATUS</a></option> </div> {% else %} <div class="top-selector-right"> <option><a class="nav-link" href="{% url 'candidates' %}"> ALL STATUS</a></option> </div> {% endif %} {% for s in status %} {% if s.pk == stat_selected %} <option><a class="nav-link" href="{{ s.get_absolute_url }}">{{ stat.ff_status_id }}</a></option> {% else %} <option><a class="nav-link" href="{{ s.get_absolute_url }}">{{ stat.ff_status_id }}</a></option> <!-- <a class="nav-link" href="{{ s.get_absolute_url }}"><i class="fa-solid fa-ellipsis-vertical"></i> {{ s.ff_status }}</a>--> {% endif %} {% endfor %} </select> </div> My views.py def show_status(request, np_ff_status_id): new_candidates = NewPlacement.objects.filter(np_ff_status_id=np_ff_status_id) status = SatusActivity.objects.all() context = { 'new_candidates': new_candidates, 'status': status, 'stat_selected': np_ff_status_id, } return render(request, 'placements/candidates.html', context=context) models.py Just part of the models.py class SatusActivity(models.Model): NEW = 'New placement' CANCELED = 'Canceled' CONTACTED = 'Contacted' WAITING = 'Waiting answer for the client' ACCEPTED = 'Accepted' … -
Postgres GinIndex doesn't improve performance
I'm trying to improve search query time by using postgres ginindex. but it doesn't do anything and query time is the same with or without index. It's the first time I'm using index and I'm not sure what I'm doing wrong. models.py class Book(models.Model): author = models.ManyToManyField(Author, related_name='books') category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=1000) description = models.TextField(max_length=3000) price = models.DecimalField(max_digits=6, decimal_places=2) publisher = models.CharField(max_length=1000) language = models.CharField(max_length=200) pages = models.PositiveSmallIntegerField() isbn = models.CharField(max_length=13, validators=[MaxLengthValidator(13)]) cover_image = models.ImageField(upload_to='books/images', null=True) publish = models.BooleanField(default=True) favorite = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='favorite_books', blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = BookManager() def __str__(self): return self.title class Meta: indexes = [ GinIndex(fields=['title'], name='book_title_idx') ] views.py def get_queryset(self): query = self.request.query_params.get("search", None) if query: books = Book.objects.annotate( search=SearchVector("title", "author__name"), ).filter(search=query) print(books.explain(analyze=True)) return books else: return self.queryset I also added BtreeGinExtension to the migration file -
Setting context variables through javascript on selectize
ASK: On selecting value ABC in the first dropdown, the context variable dummy_id should be set to the value nonstandard however in my case the value to the context variable is not being passed by javascript and on the python view getting no value for dummy_id [HTML] Dropdown 1: <select id="service" name="service" class="form-control full_100_percent_width"> <option value="">Service</option> <option value="xyz" {% if service == 'xyz' %}selected{% endif %}>XYZ</option> <option value="abc" {% if service == 'abc' %}selected{% endif %}>ABC</option> </select> [HTML] Dropdown 2: <select id="subList" name="dummy_id" class="form-control full_100_percent_width"> <option value="">All Values</option> <option value="nonstandard" {% if dummy_id == 'nonstandard' %} selected="selected" {% endif %}>NonStandard</option> <option value="standard" {% if dummy_id == 'standard' %} selected="selected" {% endif %}>Standard</option> </select> JS: $("#service").change(function() { var svc = $(this).val() var selectized = $('#subList').selectize(); if(svc == "abc") { selectized[0].selectize.setValue('nonstandard'); selectized[0].selectize.disable(); } else { selectized[0].selectize.setValue(''); selectized[0].selectize.enable(); } }); How can I assign dummy_id the value through JS incase if we select abc on the dropdown 1. Thanks Tried using selectize as well document.getElementById but nothing seems to be setting the value for the context variables. var input = document.getElementById("subList") input.innerHTML = 'nonstandard' -
DJANGO Admin Panel is not showing
I am using GUNICORN and DJANGO TENANT. All urls are working fine for the project except the admin url. I am not able to access the admin portal for the public schema or any of the tenants. I also have swagger set up which is working fine as well. I do not get any errors, Just that the was no response. See Screenshot attached below. SEE RESPONSE HERE Expected to see the Django Admin Portal. -
Django - How to call a function with arguments inside a template
I have the following function-based view: def get_emails(request, HOST, USERNAME, PASSWORD): context = { 'FU_HOST': settings.FU_HOST, 'FU_USERNAME': settings.FU_USERNAME, 'FU_PASSWORD': settings.FU_PASSWORD, 'FV_HOST': settings.FV_HOST, 'FV_USERNAME': settings.FV_USERNAME, 'FV_PASSWORD': settings.FV_PASSWORD, 'USV_HOST': settings.USV_HOST, 'USV_USERNAME': settings.USV_USERNAME, 'USV_PASSWORD': settings.USV_PASSWORD, } m = imaplib.IMAP4_SSL(HOST, 993) m.login(USERNAME, PASSWORD) m.select('INBOX') result, data = m.uid('search', None, "ALL") if result == 'OK': for num in data[0].split(): result, data = m.uid('fetch', num, '(RFC822)') if result == 'OK': email_message_raw = email.message_from_bytes(data[0][1]) email_from = str(make_header(decode_header(email_message_raw['From']))) email_addr = email_from.replace('<', '>').split('>') if len(email_addr) > 1: new_entry = EmailMarketing(email_address=email_addr[1], mail_server='X') new_entry.save() else: new_entry = EmailMarketing(email_address=email_addr[0], mail_server='X') new_entry.save() m.close() m.logout() messages.success(request, f'Subscribers list sychronized successfully.') return redirect('subscribers') I'd like to place 3 buttons on my front-end that call this same function with different arguments each time, for example one button get_emails(FU_HOST, FU_USERNAME, FU_PASSWORD), the other button get_emails(USV_HOST, USV_USERNAME, USV_PASSWORD). How can one achieve this in Django? My credentials are stored in .env file. -
django - saving files to mongodb
For uploading files into mongo db I've got code in my CreateView (post method) as follows: fs = GridFS(mydatabase) file_in = self.request.FILES['query_file'] file_id = fs.put(file_in, filename='test') My problem is after run I get entry in db.files collection but no entry in db.chunks. Whats's going on? -
how to return a list of selected by user values using ArrayAgg in Django?
I am trying to write a query where I get the list of all matched filters per product. I managed to write an annotation that creates a list and puts all matching filters: def filter_data(request): client_type = request.GET.getlist('client_type[]') product_list = product_list.annotate(client_type_product_count=Count('client_type', filter=Q(client_type__title__in=client_type)), client_type_title=ArrayAgg('client_type__title', distinct=True)).exclude(client_type_product_count__exact=0) The only thing I want to change is that in this array is that I will only see matched filters that the user selected. Right now I can see all of them (no matter what user selects I always see all matching filters per product. For instance, I have a product that matches client_type1, client_type2 and client_type3 filters. Right now it shows me all 3 matches in a list. What I want is if the user selects client_type1 the list will only include client_type1 in a list (not all of them). If user selects client_type1 and client_type2 then it will show me only these 2 matched filters etc. How can I do something like that? -
how to implement drf simple jwt authentication in django channels
I want to implement my django rest framework user authentication app in django channels I was created one user authentication app in django rest framework and I want to implement these app into django channels