Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I authorize a Google user in Python backend with ID token coming from iOS application?
Following the documentation here, I am trying to authenticate a user in my iOS app and pass their ID token to my backend. The backend handles the Google API interactions for the iOS app. I am missing how to actually authenticate that user in the backend. I read over the docs here regarding ID tokens but I am confused on where the service account comes into play. Current endpoint: @api_view(['POST']) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) def google_token_info(request): try: token_obj = json.loads(request.body) token = token_obj['id_token'] id_info = id_token.verify_oauth2_token(token, requests.Request(), settings.IOS_CLIENT_ID) # create session here - how? While testing I had authentication set up via my backend. I had code like this: def google_auth(request): web_flow = flow.Flow.from_client_secrets_file(creds, scopes=scopes) web_flow.redirect_uri = request.build_absolute_uri(reverse('api.auth:oauth_callback')) auth_url, state = web_flow.authorization_url(access_type='offline', include_granted_scopes='true', prompt='consent') request.session['state'] = state return redirect(auth_url) def oauth_callback(request): success_flow = flow.Flow.from_client_secrets_file(creds, scopes=scopes, state=request.session.get('state')) success_flow.redirect_uri = request.build_absolute_uri(reverse('api.auth:oauth_callback')) auth_response = request.build_absolute_uri() success_flow.fetch_token(authorization_response=auth_response) credentials = success_flow.credentials if not request.session.get('google_credentials'): request.session['google_credentials'] = _credentials_to_dict(credentials) return redirect(reverse('api.auth:success')) Which setup session credentials for the user. I'm assuming I need something similar, but I am unsure how to create a session without actual credentials. -
Django Editing JsonResponse
How I can add "points = " to this JsonResponse in Django? My code look like this: return JsonResponse(data=points, safe=False, json_dumps_params={'indent': 1}) Result : [ { "x": 0, "y": 1 }, { "x": 0.315397047887207, "y": 0.694608645422627 } ] what I want to do : points=[ { "x": 0, "y": 1 }, { "x": 0.315397047887207, "y": 0.694608645422627 } ] -
How to filter only request.user in online_users
I am Building a BlogApp and I am stuck on a Problem What i am trying to do I am trying to access only request.user online status in template. BUT it is showing all the active users. What i am doing I am using online_users_activity to know which user is online. The Problem It is showing all the users that are online. views.py def online(request,user_id): user_status = online_users.models.OnlineUserActivity.get_user_activities(timedelta(hours=87600)) users = (user for user in user_status) context = {'users':users} return render(request, 'online.html', context) I don't know what to do. Any help would be Appreciated. -
Using Salesforce Custom Fields from Heroku Connect in a Django app
I have a Heroku app which uses Heroku Connect to connect to my Salesforce org. I created a custom object in Salesforce and that data is syncing successfully to Heroku. I also have a Django app I am building to serve as the front end of my heroku app, which uses a Postgres database. The problem is that in Salesforce, custom objects and custom fields are appended with __c and there's no way to get around that, but in Django, __ cannot be used as in a Object/Table name or a field name. Below is my models.py class in Django: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class MyCustomObject__c(models.Model): # New class that matches the name of the object I created in Salesforce name = models.TextField() # Unrestricted text def __str__(self): return self.name # return name when MyCustomObject__c.objects.all() is called However, when I run python manage.py makemigrations to create that table in Django, I get the error: blog.MyCustomObject__c: (models.E024) The model name 'MyCustomObject__c' cannot contain double underscores as it collides with the query lookup syntax. Does anyone know how I could access the data for a Custom Object that's stored in … -
Handling Form to submit API call and display API result in the same page
I'm starting with Django journey and I'm quite confused about what I have to do here. I appreciate any help. So, basically, I'm using Form to get data and from that data, I will use a specific solution API to create a site using the information from this form. I would like to get the data from this form, create the site using the APIs, but I would like to get the API result data and display the content on the same form page but below the submit bottom. I was able to create the basic form, get the necessary data and create the site using API call, but I have no idea what I have to do to get the API result and display it in case of success. `` from django import forms from django.core.exceptions import ValidationError class SiteForm(forms.Form): site_name = forms.CharField(max_length=100, label="Site Name", widget=forms.TextInput(attrs={'placeholder': 'Demo API'})) country = forms.CharField(label="Country", widget=forms.TextInput(attrs={'placeholder': 'Country',})) time_zone = forms.CharField(max_length=100, label="Timezone", widget=forms.TextInput(attrs={'placeholder': 'City'})) location = forms.CharField(max_length=200, label="Location", widget=forms.TextInput( attrs={'placeholder': 'Street'})) I don't know if this is the best code, but the POST is working at least, I can create my site using the API call. My views.py from django.shortcuts import render import requests, … -
Django Errors, Login and Signup forms works with standard methods but not with Class Based Views
I wanted to ask you for your help. I wanted to rewrite my authentication with Class Based Views. I found several tutorials, they are all telling the same. urls.py: # Authorization: path('signup/', views.SignUpView.as_view(), name='signup'), path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView, name='logout'), views.py: class SignUpView(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('home') template_name = 'registration/signup.html' And this is part of my signup.html: <div class="jumbotron jumbotron-fluid vertical-center"> <div class="container"> <div class="d-flex justify-content-center"> {% if error %} <div style="text-align: center;"> <div class="alert alert-danger" role="alert">{{ error }}</div> </div> {% endif %} <div class="row w-75"> <div class="col-md-12"> <h1>Sign Up:</h1><br> <form method="post"> {% csrf_token %} <div class="form-group"> <label for="exampleInputEmail1">Username:</label> <input type="text" class="form-control" name="username" aria-describedby="emailHelp" placeholder="Enter username. It will be visible for others." required> </div> <br> <div class="form-group"> <label for="exampleInputPassword1">Password:</label> <input type="password" class="form-control" name="password1" id="exampleInputPassword1" placeholder="Password. Please make it strong and unique." required> </div> <br> <div class="form-group"> <label for="exampleInputPassword1">Confirm Password:</label> <input type="password" class="form-control" name="password2" id="exampleInputPassword1" placeholder="Repeat password from above." required> </div> <br> <button type="submit" class="btn btn-lg btn-success">Sign Up</button> </form> </div> </div> </div> </div> </div> And it is not working. I can see in console that POST 200 was sent but there is no redirect to home page. When I try to login nothing is happening. Also no errors are … -
'QuerySet' object has no attribute 'email'
I found an error of QuerySet object has no attribute 'email'.. i tried my best to solve the problem but don't able to find a solution.. from django.http import HttpResponse from loginsystem.models import newUser from django.contrib import messages from django.core.exceptions import MultipleObjectsReturned def login(request): if request.method=='POST': try: userdetails=newUser.objects.filter(email=request.POST['email'] , password=request.POST['password']) print("username=", userdetails) request.session['email']=userdetails.email return render(request, 'home.html') Thanks -
Django field with setter won't update even when I change the setter
To begin I will provide a background on my project / the problem I am having. The question is at the end as it makes more sense with the information first. Thank you for reading. I have a Django model which is based around tracking stock data. The first thing I do in this model is assign a score to instances of my Equity model, based on data from an Article model. def fundamental_list(self): l_fund = [] filtered_articles = Article.objects.filter(equity__industry = self.industry) for filtered_article in filtered_articles: if(filtered_article.equity.equity_name == self.equity_name): l_fund.append([filtered_article.get_fun_score(), filtered_article.get_date(), filtered_article.id, filtered_article.title, filtered_article.get_source(), filtered_article.is_this_month()]) else: if (filtered_article.read_through == -1): l_fund.append([float(-1)*filtered_article.get_fun_score(), filtered_article.get_date(), filtered_article.id, filtered_article.title, filtered_article.get_source(), filtered_article.is_this_month()]) if (filtered_article.read_through == 1): l_fund.append([filtered_article.get_fun_score(), filtered_article.get_date(), filtered_article.id, filtered_article.title, filtered_article.get_source(), filtered_article.is_this_month()]) return l_fund I then initially assigned a weighted_score to my Equity as follows (in order to rank them). weighted_strength_minus = models.FloatField(db_column='weighted_strength_minus', default=0) def set_weighted_strength_minus(self): sys.stdout.flush() weight = 0.40 fundamental_data = self.fundamental_list() sentiment_data = self.sentiment_list() num_entries = len(fundamental_data) if (num_entries != 0): total = 0 for i in range(num_entries): total += (weight**i)*(fundamental_data[i][0]-sentiment_data[i][0]) total = total*(1-weight)/(1-weight**num_entries) self.weighted_strength_minus = total return total else: self.weighted_strength_minus = 0 return 0 However, this weighted_strength incorporated too much data and I only wanted to use data from the past two weeks … -
Django: cannot annotate using prefetch calculated attribute
Target is to sum and annotate workingtimes for each employee on a given time range. models: class Employee(models.Model): first_name = models.CharField(max_length=64) class WorkTime(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name="work_times") work_start = models.DateTimeField() work_end = models.DateTimeField() work_delta = models.IntegerField(default=0) def save(self, *args, **kwargs): self.work_delta = (self.work_end - self.work_start).seconds super().save(*args, **kwargs) getting work times for each employee at a given date range: queryset = Employee.objects.prefetch_related( Prefetch( 'work_times', queryset=WorkTime.objects.filter(work_start__date__range=("2021-03-01", "2021-03-15"])) .order_by("work_start"), to_attr="filtered_work_times" )).all() trying to annotate sum of work_delta to each employee: queryset.annotate(work_sum=Sum("filtered_work_times__work_delta")) This causes a FieldError: Cannot resolve keyword 'filtered_work_times' into field. Choices are: first_name, id, work_times How would one proceed from here? Using Django 3.1 btw. -
unable to add rows and columns in spreadsheet in dash-plotly in django
I am trying to add rows and columns in spreadsheet in Django using Plotly-dash library but ,I am unable to add these in spreadsheet. I follow this link https://dash.plotly.com/datatable/editable (Uploading Data, uploading and removing rows and columns ). Can someone help me with code? Thanks in advance! -
Django related objects in hierarchy
I've got some models which relations like this: attribute: str name attribute_value: foreign attribute float value product: ManyToMany attribute_value page: ManyToManyField product Is there a way to search for a page that has products with attribute_value.attribute.pk == x and attribute_value.value == y? I've read about related objects but can I use them in this kind of relation, should I use some inner join or is there any other way I could use Django to filter it easily? -
How to select HTML Table rows by checkbox and adding to database?
Here is my Template : {% for pr in productlist %} <ul> <li><input type="checkbox" name="mylistch" value="{{ pr.productid }}"></li> <li><input type="hidden" name="mylist" value="{{ pr.productname }}"></li> <li><input type="number" name="mylist" id="prqty"/></li> </ul> {% endfor %} result is : 1 product1 23 2 product2 44 3 product3 23 4 product44 56 5 product5 12 6 product6 9 7 product7 76 Here i can get list of items via : pd = request.POST.getlist("mylist") and get selected items by checkbox via: pn = request.POST.getlist("mylistch") and View is : pch = request.POST.getlist('mylistch') pnch = iter(pch) pr = request.POST.getlist('mylist') pri = iter(pr) for pid, pname, ptotal in zip(pnch , pri , pri): models.Sellinvoiceitems.objects.create( productid=pid productname=pname, totalnumber=ptotal, sellinvoice = invoice, stockid = stock ) My problem is when i checked ids 4 , 5 , 6 via checkbox it returned ids 1 ,2 ,3. for each list it just returned first elements. how can i get id 4 ,5 ,6 which selected by checkboxes? -
uWSGI error when deploying Django app on Heroku
I'm trying to deploy a DRF app on Heroku but it keeps erroring out when building wheel for uWSGI. I'm on Heroku stack: Heroku-20 the latest The log on the command line appears like this: remote: Building wheel for uWSGI (setup.py): started remote: Building wheel for uWSGI (setup.py): finished with status 'error' remote: ERROR: Command errored out with exit status 1: remote: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-_2lmfods/uWSGI/setup.py'"'"'; __file__='"'"'/tmp/pip-install-_2lmfods/uWSGI/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-8jh6k5it remote: cwd: /tmp/pip-install-_2lmfods/uWSGI/ remote: Complete output (221 lines): remote: /app/.heroku/python/lib/python3.8/distutils/dist.py:274: UserWarning: Unknown distribution option: 'descriptions' remote: warnings.warn(msg) remote: running bdist_wheel The full log on command line is too long to post here. But further down the log there is this warning: remote: plugins/python/python_plugin.c: In function ‘uwsgi_python_worker’: remote: plugins/python/python_plugin.c:1961:3: warning: ‘PyOS_AfterFork’ is deprecated [-Wdeprecated-declarations] remote: 1961 | PyOS_AfterFork(); remote: | ^~~~~~~~~~~~~~ remote: In file included from /app/.heroku/python/include/python3.8/Python.h:144, remote: from plugins/python/uwsgi_python.h:2, remote: from plugins/python/python_plugin.c:1: remote: /app/.heroku/python/include/python3.8/intrcheck.h:18:37: note: declared here remote: 18 | Py_DEPRECATED(3.7) PyAPI_FUNC(void) PyOS_AfterFork(void); A little further down I get the failed message: remote: plugins/router_basicauth/router_basicauth.c:73:5: error: ‘struct crypt_data’ has no member named ‘current_salt’ remote: 73 | cd.current_salt[0] = ~cpwd[0]; remote: | ^ remote: ---------------------------------------- remote: ERROR: Failed building wheel … -
Using custom manager for many-to-many relations?
I have two classes (Book and Question) that are linked by a ManyToMany relationship. In particular, I typically call book.questions.all() to get all the questions in a book. Now, for my Question class, I have a custom manager active_objects, which basically only return questions that are active. What I'm trying to do is when I call book.questions.all(), I only want to return the active questions of the book using my custom manager. I was looking at previous SO questions which recommended using base_manager_name but this doesn't seem to work for me. Upon checking the documentation, they said base_manager_name does not work for ManyToMany relationships (https://docs.djangoproject.com/en/3.1/topics/db/managers/). Does anyone have a good way to do this? Class Question(models.Model): objects = models.Manager() # The default manager. active_objects = CustomManager() # custom manager. books = models.ManyToManyField(Book, related_name='questions') class Meta: base_manager_name = 'active_objects' class Book(models.Model): pass -
Why modelformset always returns error "this field is required"?
I try to render modelformset in a template manually and when I hit submit button it gives an error saying that "This field is required.". I create modelformset like this: from django.forms import modelformset_factory ImageFormset = modelformset_factory(PostImages, fields=('image',), extra=0, can_delete=True) formset = ImageFormset(queryset=post.postimages_set.all()) And when I render modelformset like this, everything works: {{ formset.management_form }} {{ formset.as_p }} But when I render it like this I get an error: {{ formset.management_form }} {% for f in formset %} <img src="/media/{{ f.image.value}}" style="max-width: 400px;" alt=""> {{ f.image }} {{ f.DELETE }} {% endfor %} -
Django redirects or react history?
For some time I've been developing a django rest/react app. I'm still a newbie in this topic and most of the time I apply just-working solutions to my project. Gradually I'm lerning new things. There is this topic that bothers me. In my app I have this like 'main view' with a nav bar and a drawer (simply from material-ui). In drawer I've declared some buttons for navigation. Now the only view/layout changing is this empty space excluding nav bar and drawer (on the left). So it's facebook-like layout (with only middle part changing when navigating trough main stream or groups/pages). Those buttons in drawer use history.push() from react, as it was easiest to apply, but I wonder is it the right way ? Django has it's redirections, shouldn't I use those ? There is not much of a comparison between history and redirect. Something interesting I've found is: React-Router - Link vs Redirect vs History . Also, I've implemented a simple login and django auth, but with axios.posting I'm able to trace this this request in browsers network. Is there a better, or more important a safer way of requesting ? -
View.py changes not updating on Django site
New Django user. Hello world. Got it to work. "Hello, world!" in the browser. I went back into views.py and updated the line to read "Hello, world! You're at the index." and saved it. Refreshing the browser (F5) does not show the change. Even Ctrl-F5 doesn't refresh it. I'm running ./manage.py runserver, and it recognizes that the file was changed and reloads the site: /home/pi/pidjango/doorbell/views.py changed, reloading. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). March 14, 2021 - 14:00:19 Django version 3.1.7, using settings 'pidjango.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. But refreshing the browser still shows the old line. I have to reboot the computer in order to see the change. But it does change, so I know the file is the correct one in the correct spot. I'm not even sure what this is called. It's some kind of cache that's not flushing, so I researched Django caching and couldn't find anything that helped. I'm running '''DEBUG = True''', so you'd think this would be a pretty common thing to do. This is on a headless Raspberry Pi, connected by SSH, so there's no local … -
communication feature in django / vuejs
I have been asked for a project to developp a communication feature for a website that is implemented in vue.js for the front-end and Django in back-end. The goal would be to have a video,voice and chat options and to have an option of constant surveillance like a baby monitor would do on one end. I have researched many options and found that WebRTC might solve this issue. However I am still looking for diverse already made options that would avoid me too much implementation work. Does somebody has a good advice or know some tools that could help me ? Thank you very much and have a great day! -
Pass parameters from Django template to view
I am pulling data from an API and passing it through to my template. I would like to give users a few options and to do so I need to pass those options from my template to the params for the API in my view. What is the best way to go about doing that? For instance, I am rendering a game schedule and I need to change the value for "league" or "date" in the params via a button click. view params = {"league": "nba", "date": "2021-03-14"} results = requests.request("GET", URL, headers=headers, params=params).json() -
Django: Add class to a div depending on a variable
I'd like to declare in the template a variable that allows me to position an image inside a section on the left or the right. I just don't understand how can I do it on the variable side. Here's my current code, main.html : {% with img_left=False %} {% include 'section-service.html' %} {% endwith %} section-service.html: <div class="sect_service-inside {% if img_left=True %} serv_img-left {% else %} serv_img-right {% endif %}"> <div id="here_img">...</div> <div id="here_text">...</div> </div> but I get the error Could not parse the remainder: '=True' from 'img_left=True' Note that I'll use this section multiple times in the main.html page, that's why I'd like to have the variable left-right. -
How to aggregateSUM all keyvalues(=cost) from a field(payment) (one to one relationship) of a model(Session)
I would like to traverse a (one to one relationship) field of session. Specifically the payment and for each Session-payment aggregate Sum all the payment.cost Something like for each session-payment (if payment exists) aggrSum all the cost VALUES. in my views.py (sthing gotta change) "TotalCost": ( sessions.values_list("payment").aggregate(Sum("cost")) ), models.py. (these are my stable files) class Payment(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) payment_req = models.BooleanField(default=False) cost = models.FloatField(blank=True, validators=[validate_positive]) invoice = models.CharField(max_length=100) user_id = models.ForeignKey(User, on_delete=models.CASCADE) # session_id = models.OneToOneField(Session, on_delete=models.CASCADE) def __str__(self): return str(self.id) class Session(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) payment = models.OneToOneField(Payment, on_delete=models.CASCADE) user_comments_ratings = models.TextField() def __str__(self): return f"Id = {self.id}" -
How to set custom model manager as a default model manager in Django?
I have multiple apps and models in Django project. Now i want to use custom model manager in all apps models. i don't want to write custom model manager query inside of every single model. I just want to know is that possible to set custom model manager as default models manager for all apps? manager.py class CustomQuerySet(models.Manager): def get_queryset(self): return super(CustomQuerySet, self).get_queryset().filter(status=True) -
Change the color of the icon in jquery (django project)
I added to the wish list for products.(django project) Users click on a heart-shaped icon if they add a product to this list. If a user has already added this product to the list, the heart icon is red, and if this product is not in the user's favorites list, the heart icon is white. I want to change the color of the icon each time I remove or add it to the list. In the code I wrote, this operation is done only once, and if it clicks again at the same time, there will be no change in color. {% if request.user in product.favourite.all %} <a href="{% url 'home:favourite' product.id %}" class="favourite-product fa-btn{{ product.id }}" data-id='{{ product.id }}' data-text="remove"> <i class="fa fa-heart test{{ product.id }}" style="color:red"></i></a> {% else %} <a href="{% url 'home:favourite' product.id %}" class="favourite-product fa-btn{{ product.id }}" data-id='{{ product.id }}' data-text="add"> <i class="fa fa-heart test{{ product.id }}" style="color:#eee;"></i></a> {% endif %} # ajax $(document).on('click', '.favourite-product', function (e) { e.preventDefault(); const likeText = $(`.fa-btn${product_id}`).attr("data-text"); const trim = $.trim(likeText) $.ajax({ url: $(this).attr('href'), type: 'GET', data: { 'product': product_id }, success: function (response) { if (trim === 'add') { $(`.test${product_id}`).css({"color": "red"}); } else { $(`.test${product_id}`).css({"color": "#eee"}); } }, error: … -
When I run my django project, I face this issue. Kindly help me to resolve this
Traceback (most recent call last): File "C:\Users\SARAVANAN\Envs\test8\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) -
Django: Specific unique_together condition
I have a model Article: class Article(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user)) class Meta: unique_together = ('author', 'title') The method get_sentinel_user: def get_sentinel_user(): return get_user_model().objects.get_or_create(username='deleted')[0] Thus, using on_delete=models.SET(get_sentinel_user), I save posts after deleting the author (if he agrees to this, I ask him in a separate form). And instead of a real author, I set a "stub"-user as the author for his posts. In such a situation, there is a problem with the uniqueness condition. If two users had articles with the same title and then one of them was deleted, then an error will occur when trying to delete the second user. Accordingly, I would like this error to be absent. So that the uniqueness condition applies only to real users and their articles. class Meta: constraints = [ models.UniqueConstraint( name='unique_combiantion_article_name_and_author', fields=['title', 'author'], condition=~models.Q(author__username='deleted') ) ] But then I made sure that this does not work, we cannot use author__username. Right now I'm thinking about just overriding validate_unique method. But first I would like to ask for advice. Maybe there is some other solution for this problem. Thanks for any help.