Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How can I define the ManyToManyField name?
I have this relationship Class Item(models.Model): pass Class Category(models.Model): items = models.ManyToManyField(Item) I can define the field name as items for category and access it via category.items but I want to define a field name for Item too as item.categories rather than the default item.category How can I achieve it? -
detail : "CSRF Failed: CSRF token missing." getting this on network when trying to create or delete or put data in angular 13 and DRF
i need to create source, delete it and update as well, butting getting the same error again and again. //component.html <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <div class="container mt-5"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search..." [(ngModel)]="filterTerm" /> </div> <ol> <li *ngFor="let source of sources$ | async | filter: filterTerm"> <div class="card"> <div class="card-body"> <h5 class="card-title">{{source.name}}</h5> <p>URL:- <a href ='{{source.url}}'>{{source.url}}</a></p> <a class="btn btn-primary" href='fetch/{{source.id}}' role="button" style="margin-left:5px ">Fetch</a> <button class="btn btn-primary" (click)="deleteSource(source.id)" style="margin-left:5px">Delete </button> <button class="btn btn-primary" (click)="editSource(source.id, source)" style="margin-left:5px ">Edit </button> <br> </div> </div> </li> </ol> </div> //service.ts export class SourcesService { API_URL = 'http://127.0.0.1:8000/sourceapi/'; constructor(private http: HttpClient) { } /** GET sources from the server */ Sources() : Observable<sources[]> { return this.http.get<sources[]>(this.API_URL,); } /** POST: add a new source to the server */ addSource(source : sources[]): Observable<sources[]>{ return this.http.post<sources[]> (this.API_URL, source); //console.log(user); } deleteSource(id: string): Observable<number>{ return this.http.delete<number>(this.API_URL +id); } // component.ts export class SourcesComponent implements OnInit { filterTerm!: string; sources$ !: Observable<sources[]>; // deletedSource !: sources; constructor(private sourcesService: SourcesService) { } // prepareDeleteSource(deleteSource: sources){ // this.deletedSource = deleteSource; // } ngOnInit(): void { this.Source(); } Source(){ this.sources$ = this.sourcesService.Sources() } deleteSource(id : string){ console.log(id) this.sourcesService.deleteSource(id).subscribe(); } I tried, providing the header and also tried the steps got in the question … -
Django - MySQL (1170, "BLOB/TEXT column 'object_path' used in key specification without a key length
I've updated the Django model field from CharField to TextField. I got the below error while applying migrations in MySQL. django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'my_column' used in key specification without a key length") Django version: 2.2.2 Note: This column in included in unique_together in Meta. -
How to optimize N+1 SQL queries when serializing a post with mptt comments?
Good afternoon. I have the following serializer for a detailed post: class ArticleDetailSerializer(serializers.ModelSerializer): author = ArticleAuthorSerializer(read_only=True) comments = CommentSerializer(many=True, read_only=True) class Meta: model = Article fields = '__all__' Comment Serializer: class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' def get_fields(self): fields = super(CommentSerializer, self).get_fields() fields['children'] = CommentSerializer(many=True, required=False, source='get_children') return fields When working with a list of comments, I get 2 sql queries if I work with get_cached_trees() class CommentListAPIView(generics.ListAPIView): serializer_class = serializers.CommentSerializer queryset = Comment.objects.all().get_cached_trees() But how do you get the same thing to work for an article with a list of comments? class ArticleDetailAPIView(generics.RetrieveAPIView): serializer_class = serializers.ArticleDetailSerializer queryset = Article.custom.all() lookup_field = 'slug' def get_queryset(self): queryset = self.queryset.prefetch_related(Prefetch('comments', queryset=Comment.objects.all().get_cached_trees())) return queryset I used prefetch_related() but it didn't work. I used Prefetch(), it gave me an error: 'list' object has no attribute '_add_hints' I seem to be lost in the ability to optimize the mptt comments for the article. But if you use the same comments, rendering according to the documentation in the Django template, then this problem is not observed. I ask for your help, dear programmers and experts. -
Django login/ Payload
This is weird. I have created login functions so many times but never noticed this thing. when we provide a username and password in form and submit it. and It goes to server-side as a Payload like this csrfmiddlewaretoken: mHjXdIDo50tfygxZualuxaCBBdKboeK2R89scsxyfUxm22iFsMHY2xKtxC9uQNni username: testuser password: 'dummy pass' #same as i typed(no encryption) I got this in the case of Incorrect creds because the login failed and it won't redirect to the other page. but then I tried with Valid creds and I set the Preserve log turned on in the Chrome network tab. then I checked there and still, I can see the exact entered Username and password. for the first time, I thought i might have missed some encryption logic or something else i dont know. but then i tried with multiple Reputed tech companies and i can still see creds in the payload. Isn't it wrong? It's supposed to be in the encrypted format right? -
Django 'model' object is not iterable when response
i hvae 2 model. And the two models are connected to the ManyToManyField. models.py class PostModel(models.Model): id = models.AutoField(primary_key=True, null=False) title = models.TextField() comments = models.ManyToManyField('CommentModel') class CommentModel(models.Model): id = models.AutoField(primary_key=True, null=False) post_id = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField() and serializers.py class CommentModel_serializer(serializers.ModelSerializer): class Meta: model = MainCommentModel fields = '__all__' class PostModel_serializer(serializers.ModelSerializer): comment = MainCommentModel_serializer(many=True, allow_null=True, read_only=True) class Meta: model = MainModel fields = '__all__' and views.py @api_view(['GET']) def getPost(request, pk): post = PostModel.objects.filter(id=pk).first() comment_list = CommentModel.objects.filter(post_id=post.id) for i in comments_list: post.comments.add(i) serializer = PostModel_serializer(post, many=True) return Response(serializer.data) There is an error when I make a request. 'PostModel' object is not iterable and The trackback points here. return Response(serializer.data) I tried to modify a lot of code but I can't find solutions. Please tell me where and how it went wrong -
Django session variable returns None?
I want to get value of j in test function, but it returns None, How i get value of this session variable. This is index function where session variable is created and passing it. def index(request): j = '' if request.method == "POST": form = InputForm(request.POST) if form.is_valid(): form.save() try: ids = form.cleaned_data['git_Id'] print(ids) obj = sql() query = f""" SELECT request_id FROM request_form_db.request_form_mymodel where git_Id= '{ids}' ; """ print(query) p = obj.fetch_query(query) print("Query Result", p) for i in p: print("Result[0] : ", i[0]) print("Result : ", p) i = i[0] j = i approve_url = f"http://127.0.0.1:8000/form/test?request_id={i}" print("Url : ", approve_url) form = InputForm() else: form = InputForm() print('J : ', j) request.session['j'] = j print('Request ID Sent : ', j) return render(request, 'home.html', {'form': form}) This is test function where i want to getting value of j, but here it returns None. def test(request): pro = request.session.get('j') print("Request ID from Index View : ", pro) if request.method == "POST": form = TestForm(request.POST) if form.is_valid(): print("Form is Valid") selected = form.cleaned_data.get('myfield') print(selected) else: rq = request_id["request_id"] s = sql() query = f"""update request_form_db.request_form_mymodel set is_approved=1 where request_id = '{rq}' """ print(query) s.update_query(query) print("Updated Successfully") form = TestForm() else: form = … -
Why django form post with errors updates instance
I have a standard user update form like @login_required() def personal(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) if user_form.is_valid(): user = user_form.save() update_session_auth_hash(request, user) messages.success(request, 'Your personal data has been changed successfully!') return redirect('profile') else: user_form = UserForm(instance=request.user) context = { 'form': user_form, } return render(request, 'personal.html', context) The problem here is in the line user_form.is_valid(). It runs validation logic which collects an error when username is already taken by another user. In this case we have ValidationError raised but the instance in this form is updated nevertheless due to code in django's construct_instance function logic: def construct_instance(form, instance, fields=None, exclude=None): """ Construct and return a model instance from the bound ``form``'s ``cleaned_data``, but do not save the returned instance to the database. """ ... f.save_form_data(instance, cleaned_data[f.name]) ... I found this behavior very strange. How can I avoid updating user's instance fields with wrong values if I need, say, display initial user's username on the top of my page? -
Django QuerySet .order_by() method
I have this code down here and from my understanding order_by over writes the default behavior of the ordering option in the model’s Meta. see the documentation here https://docs.djangoproject.com/en/4.1/ref/models/querysets/#order-by my question is what criteria does the order_by() in this case use to order the QuerySet if there are no fields provided? Does it make a difference having it there? order.discounts.filter(voucher_id=OuterRef("pk")) .order_by() .values("voucher_id") .annotate(Sum("amount")) .values("amount__sum") ) -
Failed to load resource: net::ERR_CONNECTION_REFUSED 127.0.0.1:8000/store/products/1/images/:1 Failed to load resource:
I am trying to connect two server 127.0.0.1:60000 and localhost:8001 for connect two server and run localhost:8001 file its connect with 127.0.0.1:60000 port, but its give me #Failed to load resource: net::ERR_CONNECTION_REFUSED here is my code **settings.py** this is seetings.py enter image description here enter image description here i expect enter image description here this is output -
How to learn Django and do project in Django
Previous two months I am learning Django and I do some projects like CRUD, TODO-LIST, and some more basic project. But after this, I want to make a contract management project so I perform tasks like adding a user session and doing some code in view.py. I get so difficult so please suggest me lecture or tutorial there I can learn (how to code in view.py ). thanks, guys for helping me.