Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
social_django TypeError at /social/complete/facebook/ a bytes-like object is required, not 'tuple'
I'm using social_django for facebook login. I wanted to have profile pics of facebook when users login with facebook. However, I'm having this error; TypeError at /social/complete/facebook/a bytes-like object is required, not 'tuple' I've tried many solutions on web but those didn't help. Thanks for any help in advanced. Settings.py #social_django AUTHENTICATION_BACKENDS = ( 'social_core.backends.github.GithubOAuth2', #github 'social_core.backends.twitter.TwitterOAuth', #twitter 'social_core.backends.facebook.FacebookOAuth2', #facebook 'django.contrib.auth.backends.ModelBackend', #default django backend # For Google Authentication 'social.backends.google.GoogleOpenId', 'social.backends.google.GoogleOAuth2', 'social.backends.google.GoogleOAuth', 'apps.users.backend.EmailOrUsernameModelBackend', # loging with email or username ) #social_django SOCIAL_AUTH_FACEBOOK_KEY = '218187263221168' # App ID SOCIAL_AUTH_FACEBOOK_SECRET = '05c80f6c47c0a12aa43fc0dcda3abd90' # App Secret SOCIAL_AUTH_FACEBOOK_SCOPE = [ 'email' , 'user_location', 'user_hometown', 'user_birthday', 'user_friends', 'public_profile', ] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id,name,email, gender, birthday, link, location, hometown, first_name, last_name, picture' } SOCIAL_AUTH_ADMIN_USER_SEARCH_FIELDS = ['username', 'first_name', 'email'] #social_django SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'apps.users.pipeline.save_account', 'apps.users.pipeline.save_profile_picture', ) #social_django SOCIAL_AUTH_STRATEGY = 'social_django.strategy.DjangoStrategy' SOCIAL_AUTH_STORAGE = 'social_django.models.DjangoStorage' Model.py class Account(AbstractBaseUser): email = models.EmailField(max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last_login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) company = models.CharField(default='', max_length=200, help_text='In order to share the application with other users; you need to provide a valid company information', blank=True, null=True) … -
Getting Maximum date from Django Model Query
Hello I have a Student model in Django which has following fields Id, Status, Marks, End Date. When I am doing following query- records = list(Students.objects.filter(status__in=["Active"]) .values('id', 'marks', 'end_date') Then this is the value that I am getting - [{'id':'450', 'marks':'30', 'end_date':datetime.datetime(2021, 2, 3, 0, 0, tzinfo=<UTC>)}, {'id':'450', 'marks':'60', 'end_date':datetime.datetime(2021, 2, 7, 0, 0, tzinfo=<UTC>)}, {'id':'450', 'marks':'80', 'end_date':None}, {'id':'452', 'marks':'51', 'end_date':datetime.datetime(2021, 3, 1, 0, 0, tzinfo=<UTC>)}, {'id':'452', 'marks':'27', 'end_date':datetime.datetime(2021, 3, 3, 0, 0, tzinfo=<UTC>)}] Now, my requirement is to get sum of all marks and max date for same Ids. For exa for above result set the output that I want is this - [{'id':'450', 'marks':'170', 'end_date':datetime.datetime(2021, 2, 7, 0, 0, tzinfo=<UTC>)}, {'id':'452', 'marks':'78', 'end_date':datetime.datetime(2021, 3, 3, 0, 0, tzinfo=<UTC>)}] I have tried the following code to get this output - records = list(Students.objects.filter(status__in=["Active"]) .values('id', 'end_date') .annotate(marks=Coalesce(Sum('marks'), 0), )) Above code is giving me sum value but I am not able to get Max date. I tried adding end_date=Coalesce(Max('end_date__date'), 0) into annotate function but this is throwing this error - AttributeError: 'str' object has no attribute 'tzinfo' Anyone have idea how to get the Max date using annotate method or is there any other way of doing it? Thanks in … -
Traying to authentication and give user certain permission, depending on the type of user. But noting is happening
Traying to authentication and give user certain permission, depending on the type of user. But noting is happening. I try to limit access to certain functions on the site, depending on the type of user. But when I set a condition, nothing happens on the page: This is my model.py from django.contrib.auth.models import AbstractUser from django.db import models from django.urls import reverse user_type_choice = (('1', 'majstor'), ('2', 'korisnik')) class CustomKorisnici(AbstractUser): user_type = models.CharField(max_length=100,blank=True,choices=user_type_choice) username = models.CharField(max_length=100,unique=True) last_name = models.CharField(max_length=100) first_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=100) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) email = models.EmailField(max_length=100,unique=True) In the settings, I set: AUTH_USER_MODEL. AUTH_USER_MODEL ='korisnici.CustomKorisnici' this is my login.html page. This part works ok. {% extends "nav_footer.html" %} {% load static %} {% block content %} <div class="form-group"> <div class="container"> <div class="form"> <form method="post"> {% csrf_token %} {{ form.as_p }} <button id="btn" class="btn" type="submit">Login</button> </form> </div> </div> </div> </div> {% endblock %} **In my home.html page, I set condition for Users and here is a problem. ** {% if user.is_authenticated and user.user_type == "korisnik" %} <div class="col-md-4"> <a class="nav-link" href="{% url 'post_page' %}">All posts</a> </div> {% endif %} First I set a condition if user.is_authenticated and this is working fine. … -
Not able to update model data although form(request.POST) data is correct. Not going inside form.is_valid() if condition or form_save isn't working?
I am unable to update record of Candidate table. I am allowing to view contents of Candidate table on webpage, in the template i have added a link at the end of each record to update the record. Update logic is inside updatecandidate view function. But it is not working as expected. I have debug the form(request.POST) data which is fine. Please help me with error in this view function.I am a beginner in web development. from django import forms from django.forms import ModelForm from .models import Candidate class CandidateForm(ModelForm): class Meta: model = Candidate fields = "__all__" SKILL_CHOICES = ( ('Java','JAVA'), ('Python','PYTHON'), ('Full stack','FULL STACK'), ('Backend','BACKEND'), ) GRADE_CHOICES = ( ('Is1','IS1'), ('Is2','IS2'), ('IS3','IS3'), ) SCREENING_CHOICES = ( ('pending','PENDING'), ('wip','WIP'), ('complete','COMPLETE'), ) widgets = { 'Skill_Category': forms.Select(choices=SKILL_CHOICES,attrs={'class': 'form-control'}), 'Grade': forms.Select(choices=GRADE_CHOICES,attrs={'class': 'form-control'}), 'Screening_Phase': forms.Select(choices=SCREENING_CHOICES,attrs={'class': 'form-control'}), 'Final_status': forms.Select(choices=SCREENING_CHOICES,attrs={'class': 'form-control'}), }' View.py def updatecandidate(request,id): updateemp = Candidate.objects.get(id = id) form = CandidateForm(request.POST,instance=updateemp) print(form['Candidate_Name'].value()) print(form['Skill_Category'].value()) print(form['Account'].value()) print(form['Grade'].value()) print(form['Role'].value()) print(form['Billing_Date'].value()) print(form['OnBoard_Date'].value()) print(form['Screening_Phase'].value()) print(form['Final_status'].value()) print(form.is_valid) if form.is_valid(): form.save() messages.success(request,"Record Updated Successfully..!") else: messages.error(request,"No Update done") return render(request,'recruit_app/edit.html',{'editupdaterecord':updateemp}) def edit(request,id): display = Candidate.objects.get(id=id) print(display) return render(request,'recruit_app/edit.html',{'editupdaterecord':display}) edit.html {% extends 'recruit_app/main.html' %} {% block content %} <form method = "post" action = "/recruiter/search/edit/update/{{editupdaterecord.id}}"> {%csrf_token%} <table style = "width:1"> … -
Is this view in django secure?
I am building a RESTAPI in Django using the following library called drf-firebase-token-auth. The client sends a get request with the token_id available in the Authorization header, and the library is expected to handle authentication in Firebase automatically. But the problem is if I do a simple get request without headers like curl <url+endpoint> the library doesn't verify if there's a an Authorization header and try to get a token for verification as if the request happens successfully as if drf-firebase-token-auth didn't raised it to be a problem. So I handled an exception whereas if the get request doesn't have an an authorization header, then raise an exception. But is it secure? from datetime import datetime from rest_framework import status from rest_framework.decorators import ( api_view, ) from rest_framework.response import Response # Create your views here. @api_view(["GET"]) def check_token(request): # if token is valid response with current server time try: if request.META["HTTP_AUTHORIZATION"]: date = datetime.now() return Response( data="Server time is: " + str(date), status=status.HTTP_200_OK ) except: return Response(data="Authorization header unavailable") -
DoesNotExist: Getting "Group matching query does not exist." error while saving a UserCreationForm of Django
I'm trying to save UserCreationForm of Django's built in auth application's form, using following in forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import * class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] My unauthenticated decorator is: def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') else: return view_func(request, *args, **kwargs) return wrapper_func And views function looks like: @unauthenticated_user def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + username) return redirect('login') context = {'form':form} return render(request, 'accounts/register.html', context) Complete Traceback is: Traceback (most recent call last): File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/jatinsinghbhati/Documents/workspaces/pollsite/accounts/decorators.py", line 9, in wrapper_func return view_func(request, *args, **kwargs) File "/Users/jatinsinghbhati/Documents/workspaces/pollsite/accounts/views.py", line 26, in registerPage user = form.save() File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/contrib/auth/forms.py", line 138, in save user.save() File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/contrib/auth/base_user.py", line 67, in save super().save(*args, **kwargs) File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/db/models/base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/db/models/base.py", line 801, in save_base post_save.send( File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 177, in send return [ File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 178, in <listcomp> … -
I'm having problem with accessing my django admin model
Error Showing: TypeError at /admin/store/order/23/change/ __str__ returned non-string (type NoneType) Request Method: GET Request URL: http://localhost:8000/admin/store/order/23/change/ Django Version: 3.0.5 Exception Type: TypeError Exception Value: __str__ returned non-string (type NoneType) Exception Location: C:\Users\BHAVIN\Envs\test\lib\site-packages\django\forms\models.py in label_from_instance, line 1219 Python Executable: C:\Users\BHAVIN\Envs\test\Scripts\python.exe Python Version: 3.8.0 Code In my model.py: class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) digital = models.BooleanField(default=False,null=True, blank=True) def __str__(self): return str(self.customer) @property def shipping(self): shipping = False orderitems = self.orderitem_set.all() for i in orderitems: if i.product.digital == False: shipping = True return shipping @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total -
About values('created_at__day') and values('created_at__week')
I wrote this code to sum up the daily and weekly counts with multiple data registered. What do the 2,3,18,22,27 in created_atday and 7,8,9,13 in created_atweek represent? Also, is there any way to make it easier to understand, such as 2021/3/5 for day and 2021/3/6- for week? I would appreciate it if you could tell me more about this. Data.objects.values('created_at__day').annotate(Sum('count')) Data.objects.values('created_at__week').annotate(Sum('count')) in the case of created_at__day "data": [ { "created_at__day": 2, "count__sum": 1004 }, { "created_at__day": 3, "count__sum": 491 }, { "created_at__day": 18, "count__sum": 1221 }, { "created_at__day": 22, "count__sum": 1201 }, { "created_at__day": 27, "count__sum": 999 } ], in the case of created_at__week "report": [ { "created_at__week": 7, "time__sum": 1221 }, { "created_at__week": 8, "time__sum": 1201 }, { "created_at__week": 9, "time__sum": 1663 }, { "created_at__week": 13, "time__sum": 999 } ], -
get all columns of 2 related models in django models
I am trying to get all the fields of Services and Suppliers as querySet in view class supplierMaster(models.Model): supplierId = models.AutoField(primary_key=True) supplierName = models.CharField(max_length=25) status = models.ForeignKey(statusMaster, on_delete=models.CASCADE) createdOn = models.DateTimeField(auto_now_add=True) def __str__(self): return self.supplierName class servicesMaster(models.Model): serviceId = models.AutoField(primary_key=True) serviceName = models.CharField(max_length=50) supplierId = models.ForeignKey(supplierMaster, on_delete=models.CASCADE) status = models.ForeignKey(statusMaster, on_delete=models.CASCADE) createdOn = models.DateTimeField(auto_now_add=True) def __str__(self): return self.serviceName -
Django automatically reload page files changes not working with django-livesync, how to solved the issue?
I have shown many posts in StackOverflow that those developer using "django-livesync" module to reload the pages and I tried same way but it's not reloading when I change any files. I followed, https://github.com/fabiogibson/django-livesync and How to automatically reload Django when files change? those techniques are failed that's why posting it again because I didn't see any solution anymore. I tried, 1st pip install django-livesync 2nd added "livesync" in INSTALLED_APPS before 'django.contrib.staticfiles' 3rd added middleware 'livesync.core.middleware.DjangoLiveSyncMiddleware', finally python manage.py runserver the server is running but reloading not working. Whenever I change any templates files, views, etc page not reloading automatically. below the project structure, and requirements.txt files for each version my goal is to reload the Django server http://127.0.0.1:8000/ automatically whenever I do python manage.py runserver. I will be very appreciated if get a good answer, Thanks. -
The right architecture to create a semi Jupiter notebook clone with Django and React
I am building a web app that lets a user upload a dataset and apply many data science procedures and tasks like EDA, data processing, visualization, and creating models. You can imagine it as a dashboard for repetitive data science tasks so it will be event-based like button clicks so on and not like Jupiter notebook way. So my question is, how to manage such a work flow? after a user uploads a document (dataset) many requests will take place to transform and apply a new action on the data, as the procedure might take a long time due to the long processing time, is there an efficient way/architecture to design such a system? and how to handle many operations on the same file without I/O errors? I have come across Django Channels and it seems to be a good solution since it provides async/sockets-based connections that will give enough time for each request and not be bounded by the http timeout. One workflow that is going to take place in the project is the following: - upload dataset - get all columns - get datatypes - get dataset description/info - modify datatypes - create new column set - agg … -
Directory structure for Django Python SQlite Project for Excel upload and Download
I am creating a project which uses Django Framework and SQLite for backend. I will be uploading and downloading excel documents. What should be the project directory structure. Kindly help -
How to create a form that update several objects?
I have several customers and users in my project. I can assign a customer to a user with a form. You can look to my question that I answered from here Now, I listed countries of the customers. I want to create a form that when a user click the button next to country and select the username it will assign to selected user. Assigned operation is actually update a customer's user field. How can I do that? views.py def country_customer_list(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) customer_list = Customer.objects.filter(company=userP[0].company.comp_name) countries = Customer.objects.values_list('country', flat=True).distinct() context = { 'customer_list': customer_list, 'countries': countries } return render(request, 'country_customer_list.html', context) country_customer_list.html <table id="multi-filter-select" class="display table table-striped table-hover grid_" > <thead> <tr> <th>Country</th> <th>Operations</th> </tr> </thead> <tbody> {% for country in countries %} <tr> <td>{{country}}</td> <td> <div class="row"> {% if customer.user == null %} {% else %} {% endif %} <div id="demo{{ forloop.counter }}" class="collapse"> {% if customer.user == null %} {% comment %}<form method="post"> {% csrf_token %} {{ form|crispy }} <input type="hidden" name="customer_id" value="{{ customer.id }}"> <button type="submit" class="btn btn-success ">Assign</button> </form>{% endcomment %} {% else %} {# Assigned to {{ customer.user.first_name }} {{ customer.user.last_name }}#} {% endif %} </div> </div> </td> </tr> {% … -
My Django Form Doesn't Add My Images To The Database
I Tried To Add An Image To My Database But I Can Only Insert It Manually In My Admin Panel It Doesn't Add It Automatically From My Form This Is My models.py option1photo = models.ImageField(null=True, blank=True) option2photo = models.ImageField(null=True,blank=True) option3photo = models.ImageField(null=True,blank=True) And My forms.py class AddpollForm(forms.ModelForm): class Meta: model = PollOptions fields = ['option1photo','option2photo','option3photo'] And My views.py polloptions_form = AddpollForm() if request.method == 'POST': polloptions_form = AddpollForm(request.POST) if polloptions_form.is_valid(): polloptions = polloptions_form.save(commit=True) return redirect('home') -
uWSGI resets worker on lifetime reached causes downtime
I configured my workers to have max-worker-lifetime=3600. It runs Django But What I see is that every 3600 seconds, both workers terminate together, and I have downtime of about 15 seconds and all requests fail with 502 from the remove server. These are the logs: Everything normal 00:00:00 worker 1 lifetime reached, it was running for 3601 second(s) 00:00:00 worker 2 lifetime reached, it was running for 3601 second(s) 00:00:01 HTTP 502 (on the remote server) 00:00:01 HTTP 502 (on the remote server) ... 00:00:01 HTTP 502 (on the remote server) 00:00:11 HTTP 502 (on the remote server) 00:00:11 Respawned uWSGI worker 1 (new pid: 66) 00:00:11 Respawned uWSGI worker 2 (new pid: 67) Everything goes back to normal I'm not sure why it has this behavior. This is the configuration used (only relevant parts): UWSGI_MASTER=true \ UWSGI_WORKERS=2 \ UWSGI_THREADS=8 \ UWSGI_LISTEN=250 \ UWSGI_LAZY_APPS=true \ UWSGI_WSGI_ENV_BEHAVIOR=holy \ UWSGI_MAX_WORKER_LIFETIME=3600 \ UWSGI_RELOAD_ON_RSS=1024 \ UWSGI_SINGLE_INTERPRETER=true \ UWSGI_VACUUM=true -
Django translate sentence with variable from .po files onto template
I want to translate a sentence that contains a variable by only changing the .html or the .po file. So the template looks something like this: <!-- Just for simplicity, I put price = 20.0 --> {% blocktrans with price=20.0 %} ${{ price }}/month {% endblocktrans %} and the .po file looks like this: msgid "$%(price)s/month" msgstr "每月 $%(price)s" Therefore, the output that I expect is '每月 $20.0', but the output that I got is '$20.0/month'. Is it because of syntax fault? I am using django 1.8.X (not really sure which) for extra info. I appreciate the help! -
python manage.py collectstatic not update files
I want to update my static file on AWS server and this is the setting which i have done on setting.py, my static folder is out of main app where is manage.py file File stu: manage.py db.sqlite3 main_app(folder) static(folder) AWS_ACCESS_KEY_ID = '---------------------' AWS_SECRET_ACCESS_KEY = '-----------------' AWS_STORAGE_BUCKET_NAME = 'agents-docs-django' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' MEDIAFILES_LOCATION = 'media' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I have run this command python manage.py collectstatic but output this: 0 static files copied, 122 unmodified. I have made change in one file in static/js/File_name.js but that is not modified ! -
How to correctly provide a file path in JS xhttp.open()?
I'm trying to change data on a page, without the need to refresh. Using Python/Django/JS Following this: https://www.freecodecamp.org/news/ajax-tutorial/ I receive the following error when pressing the button to change the text on the page. : Not Found: /Budgeting/content.txt HTTP/1.1 404 In the above article it says: The file content.txt should be present in the root directory of the Web Application. I tried placing it inside of the root directly, but problem still persists and so I tried putting "content.txt" into every single directory of the Web Application. It still is unable to find the file. Directory structure with content.txt everywhere: hmtl file with JS: {% extends "base.html" %} {% block page_content %} {% load static %} <div id="foo"> <h2>The XMLHttpRequest Object</h2> <button type="button" onclick="changeContent()">Change Content</button> </div> <script> function changeContent() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("foo").innerHTML = this.responseText; } }; xhttp.open("GET", "static/content.txt", true); xhttp.send(); } </script> {% endblock page_content %} Also tried: {% extends "base.html" %} {% block page_content %} <div id="foo"> <h2>The XMLHttpRequest Object</h2> <button type="button" onclick="changeContent()">Change Content</button> </div> <script> function changeContent() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 … -
How to list countries of customers in Django?
I have several users and these users have several customers. Every customer has a country attribute. I want to listing customer's country in my project. I tried it with a for loop but when several customers have same countries it is listed same countries several times. I want to listed all countries just one time. How can I do that? Here are my codes views.py def country_customer_list(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) customer_list = Customer.objects.filter(company=userP[0].company.comp_name) context = { 'customer_list': customer_list, } return render(request, 'country_customer_list.html', context) models.py class Customer(models.Model): customer_name = models.CharField(max_length=20) country = models.CharField(max_length=20) .. email = models.CharField(max_length=30) country_customer_list.html <table id="multi-filter-select" class="display table table-striped table-hover grid_" > <thead> <tr> <th>Country</th> <th>Operations</th> </tr> </thead> <tbody> {% for customer in customer_list %} <tr> <td>{{customer.country}}</td> <td> ... </td> </tr> {% endfor %} </tbody> </table> -
django two filter with different key on merge with same key name
In django i have two query like : First = User.objects.filter(id=data.get('id')).values('first_id','first_name') Second = User.objects.filter(id=data.get('id')).values('second_id','second_name') combined_results = list(chain(competitorFirst, competitorSecond)) After this i am getting output like: {'first_id': '1', 'first_name': 'Hornets'} {'second_id': '2', 'second_name': 'corto'} what i actually want is like: {'id': '1', 'name': 'Hornets'} {'id': '2', 'name': 'corto'} can anyone please help how can i solve this . -
Django - permissions depends on subscription type
I make a project with subscription functionality. So users can choose from such subscriptions: Starter Premium Super etc. So when they use Payment Widget and server gets callback with successful status of payment I need to change "Role" or "Group" for this user in some "Permissions Model". So I consider it like a separate model with a user as a foreign key. So it looks like: User model: username password is_active Permissions model: username (Foreignkey to User model) some permission some another permission As example, every user can create an object of Apartment model. It looks like: Apartment model: full address short address So I want to limit users in creating this objects. E.g. user with "Starter" status can add only 2 apartments, "Premium" - 5 apartments and "Super" - 10 apartments objects. So that's very simple example of how permissions should work. How can I achieve such functionality? I know that Django has Roles and Groups, but is it appropriate for my goals? -
Django middleware is looped when using process_view
Django middleware is looped when using process_view I am trying to use the method to redirect a process during middleware. Middleware from django.urls import reverse from django.shortcuts import redirect, render class CustomMiddleware: 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): return redirect(reverse('check_license')) Urls path('check-license', views.check_license, name='check_license') View def check_license(): return render(request, 'check_license.html') -
Unable to install firebase-admin pip package for python django in Apple M1 chip
Unable to install firebase-admin in Apple M1 Chip System System Configuration System OS: macOS Bigsur(11.2.2) chip: Apple M1 python version: 3.9.2 Pip Version: 20.0.1 Djnago: 3.1.7 I create virtual env for my project using below steps install virtualenv using pip install virtualenv virtualenv venv -p python3.x (whichever you want) source /your_project/venv/bin/activate your venv will activate and then you can install requirements with the help of pip After this i try to install firebase-admin pip install firebase-admin and i get error like below File "/private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-build-env-aapo6r5y/normal/lib/python3.9/site-packages/cffi/api.py", line 48, in init import _cffi_backend as backend ImportError: dlopen(/private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-build-env-aapo6r5y/normal/lib/python3.9/site-packages/_cffi_backend.cpython-39-darwin.so, 2): no suitable image found. Did find: /private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-build-env-aapo6r5y/normal/lib/python3.9/site-packages/_cffi_backend.cpython-39-darwin.so: mach-o, but wrong architecture /private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-build-env-aapo6r5y/normal/lib/python3.9/site-packages/_cffi_backend.cpython-39-darwin.so: mach-o, but wrong architecture File "/private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-install-yurwgn0k/grpcio_2bb9c0d1fcb8462591aa5aa845bcb162/src/python/grpcio/_parallel_compile_patch.py", line 54, in _compile_single_file self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) File "/private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-install-yurwgn0k/grpcio_2bb9c0d1fcb8462591aa5aa845bcb162/src/python/grpcio/commands.py", line 250, in new_compile return old_compile(obj, src, ext, cc_args, extra_postargs, File "/opt/homebrew/Cellar/python@3.9/3.9.2_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/distutils/unixccompiler.py", line 120, in _compile raise CompileError(msg) distutils.errors.CompileError: command '/usr/bin/clang' failed with exit code 1 ERROR: Failed building wheel for grpcio ERROR: Command errored out with exit status 1: /Volumes/DATA-D/user/Project/project_name/Api/fitquid/venv/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-install-yurwgn0k/grpcio_2bb9c0d1fcb8462591aa5aa845bcb162/setup.py'"'"'; file='"'"'/private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-install-yurwgn0k/grpcio_2bb9c0d1fcb8462591aa5aa845bcb162/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-record-jmxgwm9r/install-record.txt --single-version-externally-managed --compile --install-headers /Volumes/DATA-D/Drashti/Project/Fitquid/Api/webapis/fitquid/venv/include/site/python3.9/grpcio Check the logs for full command output. If try to insall pip … -
How to stop Django from hanging after page refresh using channels?
Using channels it connects properly when the page loads the first time but then hangs on refresh. Not sure why this is happening. I've placed the code below to see what might be happening? # index.html <script> let socket = new WebSocket('ws://127.0.0.1:8001/ws/'); socket.onmessage = () => { console.log("Connected"); }; socket.onclose = () => { console.log('Websocket closed'); } </script> # app/consumer.py from json import dumps from time import sleep from channels.generic.websocket import WebsocketConsumer class WSConsumer(WebsocketConsumer): def connect(self): self.accept() self.send(dumps({'message': 'connected'})) for i in range(1000): self.send(dumps({'message': i})) sleep(2) #app/routing.py from django.urls import path from app.consumers import WSConsumer ws_urlpatterns = [ path('ws/', WSConsumer.as_asgi()) ] #core/asgi.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter from channels.routing import URLRouter from django.core.asgi import get_asgi_application from app.routing import ws_urlpatterns os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") django.setup() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack(URLRouter(ws_urlpatterns)), }) # core/urls.py ... path('test/', views.IndexView.as_view()), ... In my settings I've added channels just below the .sites app but above everything else and I've added the ASGI_APPLICATION and running the application with python manage.py runserver 127.0.0.1:8001 -
Django multiple reshresh from view
I have some values in Django and I refresh them every 5 seconds on the page. I am using the ajax code below for this. But I have about 5 such values. I wonder what's the best way to do this? view: def ajax_system(request): system=get_system() return JsonResponse(system, safe=False) template: <script> $(document).ready( function() { setInterval(function(){ $('#ajaxsystem').load('/ajaxsystem'); }, 5000) }); </script>