Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - inline formset validation
I'm trying to validate my inline formset cost value's to make sure that it adds up to 100. The formset is returned 5 times so foreach the value should be added until 100 is hit. If it's more or less than that show an error & not allow the user to hit the create button. Models.py class EstimatedBudgetForm(forms.ModelForm): def clean(self): # get forms that actually have valid data count = 0 for percentage in self.cost: try: if percentage.cleaned_data: count += percentage except AttributeError: # annoyingly, if a subform is invalid Django explicity raises # an AttributeError for cleaned_data pass if count != 100: raise forms.ValidationError('Percentage must equal 100%') Views.py EstimatedBudgetChildFormset = inlineformset_factory( Project, EstimatedBudget, fields=('project', 'item', 'cost', 'time'), can_delete=False, form=EstimatedBudgetForm, extra=5, widgets={'item': forms.Select(attrs={'disabled': True})}, ) -
image upload to server using django restful api from android app using retrofit
I have been unable to upload images from android app using retrofit to server using django api. When i try to send images from android app, no errors will be shown and it also does not hit the server but using postman it works perfectly fine. What could be the reasons behind it? -
fix error 404 image not found django-allauth
i have add custom model for user signup and i add Imagefield so when user upload his photo during signup its work and uploaded to my folder but when i try to get image for user and display photo in profile page it's say GET /images/modern-mosaic-wallpaper-rose-gold-black_53876-58064.jpg HTTP/1.1" 404 4835 my code | models.py : class User(AbstractUser): user_pic = models.ImageField(upload_to='images/',null=True, blank=True) forms.py : class CustomSignupForm(SignupForm): first_name = forms.CharField(required=True,label='First Name',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' Enter First Name '}) ) last_name = forms.CharField(required=True,label='Last Name',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' Enter Second Name '}) ) user_pic = forms.ImageField(required=True,label='Your photo') def save(self, request): user = super(CustomSignupForm, self).save(request) user.user_pic = self.cleaned_data['user_pic'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() return user profile_page.html : <img src="{{user.user_pic}}" style="width:100%;height:100%"> settings.py : ACCOUNT_FORMS = { 'signup': 'blog_app.forms.CustomSignupForm', } AUTH_USER_MODEL = 'blog_app.User' everything work , the image successfully uploaded but i cant get image for user it says error 404 not found but the image already in images folder how to display image for user ? -
How to cumsum two models related by an intermediate model using Django ORM
Problem Let's say I have one table called Price which is a timeseries with a timestamp, a value and the difference of previous day. To simplify the table I have put only the dates not the hours, mins, etc.: timestamp value difference 2021-01-21 500 500 2021-01-22 1000 500 2021-01-23 1500 500 2021-01-24 2000 500 2021-01-25 2500 500 Those values might be incorrect and a user might correct it at any point in time using a second table called CorrectedPrice. A user can correct the start value even before the date of the first Price value: timestamp value 2021-01-15 1000 2021-01-23 500 By merging those two informations the resulting queryset between date 2021-01-22 and 2021-01-26 should be: timestamp value 2021-01-21 1500 2021-01-22 2000 2021-01-23 1000 2021-01-24 1500 2021-01-25 2000 Django Models We have a Stock model: class Stock(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.Charfield(unique=True) A Price model: class Price(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) value = models.IntegerField() difference = models.IntegerField() # done with a signal on pre_save timestamp = AutoCreatedField() stock = models.ForeignKey(Stock, on_delete=models.CASCADE) and then we have the CorrectedPrice model: class CorrectedPrice(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) value = models.IntegerField() timestamp = AutoCreatedField() stock = models.ForeignKey(Stock, on_delete=models.CASCADE) What … -
Getting error "SuspiciousFileOperation" after Django Version Update Django: 3.1.9 from Django: 3.1.8
I am getting this error after updating to Django: 3.1.9, on Django: 3.1.8 it works fine. I have a Files model with a FileField as below: class JobFiles(BaseModel): category = models.CharField(max_length=50, choices=FILE_CATEGORY) job_file = models.FileField('JobFile', upload_to=user_directory_path) I specified the upload_to option so that it gets uploaded differently per Category: def user_directory_path(instance, filename): import uuid if not instance.job_file_name: instance.job_file_name = filename if instance.category == 'Job Card': return f'job_card/{uuid.uuid4()}' if instance.category == 'Photos': return f'job_card/photos/{uuid.uuid4()}' if instance.category == 'Other': return f'job_card/other/{uuid.uuid4()}' return f'job_card/other/{uuid.uuid4()}' The code generating the error (double checked the file exists and it is wrapped in a file object): from django.core.files import File def test() job_files = job_card.job_card_file or JobFiles(category='JobCard') # Get path to a temp file that was processed (existence and other checks already done) doc = '/tmp/mergedfile.pdf' with open(doc, mode='rb') as f: job_files.job_file = File(f) job_files.save() The error I am getting: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/code/job_cards/views.py", line 311, in job_card_maintenance_create job_files.save() File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 790, in save_base updated … -
How can use exclude query in django
I have 2 table orderProduct and orderRequest i want to exclude that order from orderProduct table which are in the orderRequest table, but it show the error 'ForwardManyToOneDescriptor' object has no attribute 'orderProduct' Models.py class OrderProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) description = models.CharField(max_length=90) quantity = models.IntegerField() order_cancel = models.BooleanField(default=False) class OrderRequest(models.Model): order_status = models.CharField(max_length=10) order = models.ForeignKey(Order, on_delete=models.CASCADE) view.py class OrderProduct_View(TemplateView): template_name = 'purchase/orderProduct.html' def get(self, request, *args, **kwargs): checkOrder = OrderRequest.objects.exclude( orderProduct_id__in=OrderRequest.order.orderProduct ) args = {'checkOrder': checkOrder} return render(request, self.template_name, args) -
How to add a user input folder in my webpage so that they can put notes inside it?
I am working on a web notes app. I want to create a folder based on user input so that they can manage what types of notes they want to put in it. Like in a usual notes app. Website layout: -
How to test a view that requires a user to be authenticated in Django?
I have the following view that requires a user to be authenticated to access it, otherwise redirects to the login page: In my urls.py file: from . import views urlpatterns = [ path("settings", login_required(views.Settings.as_view()), name="settings"), ] In my views.py file: class Settings(View): def get(self, request): return render(request, "project/settings.html") How can I test this view? Here is what I tried: class TestViews(TestCase): def setUp(self): self.user = User.objects.create( username="testUser", password="testPassword", ) def test_settings_authenticated(self): client = Client() client.login(username="testUser", password="testPassword") response = client.get("/settings") self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, "project/settings.html") But this returns a 302 status, implying the user was not authenticated. -
Setting up Heroku Postgres from SQLite3 at Django
I have recently hosted my CRM System at heroku. But since I was only using SQLITE3, the database encounters errors at heroku. how will I setup my settings.py to fix this? I have updated settings.py yet it shows NameError: name 'os' is not defined but whenever I put import os, it shows: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte please help me, here is the code for my settings.py: from pathlib import Path import os import django_heroku import dj_database_url import dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. # BASE_DIR = Path(__file__).resolve().parent.parent # This line should already exist in your settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # This is new: dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'm)3ag$=da^%ifkti+u!rg@!x3b_%my$*#6vorp1!@vdy!i^i*!' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Thrid party apps 'crispy_forms', "crispy_tailwind", # Local apps 'clients', 'agents' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', … -
Facebook Login By Using Custom User Model Django
I have a custom User model named Account. I have an activation system so by default is_active is False. In manual login, users receive an e-mail address for an activation link then login to their account. But also I added social media login. I use django-allauth for that. When I login with facebook, it says that user is inactive because my is_active is set to False by default. How can I solve this question and make the social account user to login to the website without any problem? Can i set the is_active=True only for social media users? or do i have to do something else? -
Can I add a form in django html?
I want to add comments form a specific html which has it's own views and models and I do not want to create a new html file like comment.html which will only display the form and its views. I want users to be able to comment right underneath a post, so that users don't have to click a button such as "add comment" which will take them to a new page with the "comment.form" and then they can comment. But I'm stuck. I can add comments manually from the admin page and it's working fine, but it seems that I have to create another url and html file to display the comment form and for users to be able to add comments(btw I'm trying to build a sports related website). Thanks in advance! My models.py: class Transfernews(models.Model): player_name = models.CharField(max_length=255) player_image = models.CharField(max_length=2083) player_description = models.CharField(max_length=3000) date_posted = models.DateTimeField(default=timezone.now) class Comment(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) transfernews = models.ForeignKey(Transfernews, related_name="comments", on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.transfernews.player_name, self.user.username) My forms.py : class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) My views.py : def addcomment(request): model = Comment form_class = CommentForm template_name … -
Data doesn't get submitted to database from Django forms using classed based views
I'm am trying to make a registration page for Companies and the whole flow is working fine using froms in Django. Though when I fill out the form with data and hit submit it redirects me to my index page and doesn't show any error. But when I check the database in /admin the object/data is not submitted. Any idea what the "error" could be? I'm using class based views and I've added my model in admin.py admin.site.register(Company) My urls.py path looks like this: path('createCompanyProfile/', CompanyFormView.as_view(), name = "createCompanyProfile"), models.py: class Company(models.Model): companyName = models.CharField(max_length = 145) description = models.TextField() websiteURL = models.CharField(max_length = 100) relationToDjango = models.TextField() phoneNumber = models.CharField(max_length = 11) email = models.CharField(max_length = 100) mainContact = models.CharField(max_length = 50) streetName = models.CharField(max_length = 45) houseNumber = models.CharField(max_length = 25) postalCode = models.CharField(max_length = 4) region = models.CharField(max_length = 45) def __str__(self): return '{} {} {} {} {} {} {} {} {} {} {}'.format(self.companyName, self.description, self.websiteURL, self.relationToDjango, self.phoneNumber, self.email, self.mainContact, self.streetName, self.houseNumber, self.postalCode, self.region) class CompanyForm(ModelForm): class Meta: model = Company fields = '__all__' views.py: class CompanyFormView(FormView): model = Company template_name = "company/createCompanyProfile.html" form_class = CompanyForm success_url = '/' def form_valid(self, form): return super(CompanyFormView, self).form_valid(form) createCompanyProfile.html <form … -
/ in urlpatterns django
I am a beginner in django and don't understand the meaning "/" in urlpatterns. Here is the urlpatterns in my project urls. My first app's name is first. urlpatterns = [ path('admin/', admin.site.urls), path('first', include("first.urls")) ] I found that it didn't work unless I amended it to following: urlpatterns = [ path('admin/', admin.site.urls), path('first/', include("first.urls")) ] I don't understand what the meaning of '/' is. I googled but did not find an answer. Could anyone help me on this? Another question is that the double quotes and single quote could be used either way. But is there any convention or better practice that I can follow to use single or double quote? Thanks a lot. -
How to send dictionary context while returning a redirect function to get context data when calling this function from an api?
I have a function which redirect to a url, this function have a context dict , i want to get this dict by calling this function from another api function call, please help me ,, my code is here web function def myfunction(request, id): context = dict() obj = Model.objects.get(id=id) obj.status = 'Draft' obj.save() # Success Message to Mobile App context['status'] = 'Success' context['message'] = 'Reset successfully' context['d'] = id context['Number'] = obj.no # i want to attach this context in return(not in the url like # kwargs or args but separately) so that i get context # when i call this function from another function return redirect('del_details',str(id)) API calling function class CallingAPI(APIView): permission_classes = (IsAuthenticated,) serializer_class = SomeSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) try: response = function1(request=request, id=serializer.data['id']) # here in response i want the context from function1 json_response = json.loads(response.content) if json_response['status'] == 'success': # Do something return JsonResponse(final_result, safe=False, status=status.HTTP_200_OK) except Exception as e: pass SO when i do response = function1(request=request, id=serializer.data['id']), i want the context dictionary in response and redirect will remain same. How to achieve it. Right now i am getting only <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/del_details/120/" in response, i need the … -
django Count on FK with Sum and filters
I have to find the number of participants where the sum of two fields is above a given field. Following models: class Examination(models.Model): total_score = models.FloatField(_('Total score'), blank=False, null=False, default=60) class ExamParticipation(models.Model): examination = models.ForeignKey(Examination, blank=False, null=False, on_delete=models.CASCADE, related_name='examination_participations') total_score = models.DecimalField(_('examination score'), max_digits=3, decimal_places=1, default=0) additional_score = models.DecimalField(_('additional score'), max_digits=3, decimal_places=1, default=0) So for a given Examination I have to count how many participants, where the sum of total_score and additional_core, have more or equal like total_score/2. Is this feasible with a queryset at all or do I have to loop over the results? I tried following query: def count_sufficient_participations(self): qs = self.values('examination_participations').order_by('examination_participations').annotate( ts=Sum(F('examination_participations__total_score') + F('examination_participations__additional_score')) ).annotate(cnt_suff=Count('examination_participations')).filter(ts__gte=30) but does not seem to work and I do not know how to replace 30 with the field total_score from examination. I want to have something like examination.cnt_suff for my template. Any help will be appreciated. -
USING A DATEPICKER WITH DJANGO AND CHART.JS
Good day, i am new to django. Can i be shown how to use a datepicker to show my chart.js for the specific date selected by a user? Can i be shown how to install a datepicker for this purpose?Below was my attempt and i have not been able to display any data. This is my model: class Complainer(models.Model): STATES = ( ('Abia', 'Abia'), ('Abuja', 'Abuja'), ('Adamawa', 'Adamawa'), ('Akwa-Ibom', 'Akwa-Ibom'), ('Anambra', 'Anambra'), ('Bauchi', 'Bauchi'), ('Bayelsa', 'Bayelsa'), ('Benue', 'Benue'), ('Borno', 'Borno'), ('Cross-River', 'Cross-River'), ('Delta', 'Delta'), ('Ebonyi', 'Ebonyi'), ('Edo', 'Edo'), ('Ekiti', 'Ekiti'), ('Enugu', 'Enugu'), ('Gombe', 'Gombe'), ('Imo', 'Imo'), ('Jigawa', 'Jigawa'), ('Kaduna', 'Kaduna'), ('Kano', 'Kano'), ('Katsina', 'Katsina'), ('Kebbi', 'Kebbi'), ('Kogi', 'Kogi'), ('Kwara', 'Kwara'), ('Lagos', 'Lagos'), ('Nasarawa', 'Nasarawa'), ('Niger', 'Niger'), ('Ogun', 'Ogun'), ('Ondo', 'Ondo'), ('Osun', 'Osun'), ('Oyo', 'Oyo'), ('Plateau', 'Plateau'), ('Rivers', 'Rivers'), ('Sokoto', 'Sokoto'), ('Taraba', 'Taraba'), ('Yobe', 'Yobe'), ('Zamfara', 'Zamfara') ) SECTOR = ( ('Federal Government', 'Federal Government'), ('State Government', 'State Government'), ('Local Government', 'Local Government'), ('Private Company', 'Private Company'), ('Public Company', 'Public Company'), ('Other', 'Other'), ) NATURE = ( ('Delay of Service', 'Delay of Service'), ('Non compliance with Regulation', 'Non compliance with Regulation'), ('Demand for Bribery', 'Demand for Bribery'), ('Vandalism', 'Vandalism'), ('Unrepaired or damaged infrastructure', 'Unrepaired or damaged infrastructure '), ('Insecurity', 'Insecurity'), ('Non … -
Update value and keep the key on python dictionary
I have a parking place app where I want to calculate the available days in a week, and the total available hours per day. I have different cities with different timeshifts, some have full time (for example 7:00-20:00) and others have separated time (for example 7:00-14:00 and 16:00-20:00). Here is the loop I tried: def get_available_hours(self): _dict = [] time = 0 query_set = TimeTableCity.objects.filter(city_id=self._city_id) for i in query_set: initial_hour_datetime = datetime.strptime(i.initial_hour, '%H:%M') end_hour_datetime = datetime.strptime(i.end_hour, '%H:%M') time = end_hour_datetime - initial_hour_datetime _dict.append({i.day_table.id: time.seconds / 3600}) time = 0 return _dict And the returned dict at the end is the following: [{4: 5.0}, {4: 4.0}, {5: 5.0}, {5: 4.0}, {1: 5.0}, {1: 4.0}, {2: 5.0}, {2: 4.0}, {3: 5.0}, {3: 4.0}] The key is the day of the week, and the value is the hours for that shift. Is there a way to sum the values for the same key? -
AbstractUser in Django is not authenticating
Django version 3.2 I have created a AbstractUser model for storing info of Bank's Customer . I am able to register the customer but it's not getting authenticated while login . In admin page the password is saved as plain text , which is not expected . It should be saved in hashed form by default in Django . Please give some directions to solve this . What I am doing wrong ? In settings.py I have added line : AUTH_USER_MODEL = 'banking.Customer' models.py : ''' This stores all customers of this bank . ''' class Customer(AbstractUser): #username = models.CharField(max_length=128, unique=True) #first_name = models.CharField(max_length=128) #last_name = models.CharField(max_length=128) #email = models.CharField(max_length=128) phone = models.CharField(max_length=128) #password = models.CharField(max_length=2048) dateJoined = models.DateTimeField(auto_now_add=True) # completed, pending, blocked, error verificationStatus = models.CharField(max_length=128) #USERNAME_FIELD = 'username' #REQUIRED_FIELDS = [] def __str__(self): return f"{self.username}, {self.first_name} {self.last_name}, {self.email}, {self.password}" views.py : def register(request): if request.method == "POST": # get the information from form print("POST request :" + str(request.POST)) userName = request.POST["userName"] firstName = request.POST["firstName"] lastName = request.POST["lastName"] email = request.POST["email"] phone = request.POST["phone"] password = request.POST["password"] # insert it in DB, keep in mind that username should be unique try: customer = Customer(username=userName, first_name=firstName, last_name=lastName, email=email, phone=phone, password=password, … -
How to integrate my Django Rest Framework with Angular?
How do I integrate my Django Apps with a new created Angular Project? For example one of my apps is called eapp and this is the app structure: newapp (folder) eapp (folder) migrations (folder) tests (folder) admin.py apps.py models.py serializers.py urls.py views.py newapp (folder) __init__.py asgi.py settings.py urls.py wsgi.py manage.py My models.py file in eapp only contains of two classes: from django.db import models class Energy(models.Model): edata = models.CharField(max_length = 200) ... def __str__(self): return self.edata class Freeze(models.Model): ... The Django Rest Framework for eapp has successfully been installed in my serializers.py, urls.py and views.py file. I have also created a new Angular Project in another Visual Studio Code. Who knows how what my next steps are, or where I can get some good info on how to integrate these two? -
Let user download files on React page sent from Django FileField connected to AWS S3 bucket
I have a React/Django website for registering job applications. The user upload pdf files on a React page. The files are then sent to a Django backend FileField which is connected to a AWS S3 bucket. On another React page I try to summerize the application. I recive the application info and the file from the FileFiled is now a reference to a AWS s3 site. How can I use this reference to let the user download the file on the React page? -
How to change the behaviour of unique true in django model?
Here I am not deleting the model objects from database. I am just changing the is_deleted status to True while delete. But while doing this unique=True gives error for the deleted objects so how can I handle this ? I want to exclude is_deleted=True objects from unique True. class MyModel(models.Model): name = models.CharField(max_length=20, unique=True) is_deleted = models.BooleanField(default=False) #views class MyViewSet(ModelViewSet): serializer_class = MySerializer queryset = MyModel.objects.all() def destroy(self, request, *args, **kwargs): object = self.get_object() object.is_deleted = True object.save() return Response(status=status.HTTP_204_NO_CONTENT) -
A section in a webpage is not getting displayed for using for loop in django
This is my view: def index(request): week_ago = datetime.date.today()-datetime.timedelta(days=7) read_blog = Post.objects.filter(time_upload__gte = week_ago).order_by('-read_count') params = { 'posts': Post.objects.all(), 'read_blogs': read_blog[:4], } return render(request,'index.html', params) This is my model: from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length = 50) overview = models.TextField() time_upload = models.DateTimeField(auto_now_add = True) author = models.ForeignKey(Author,on_delete = models.CASCADE) thumbnail = models.ImageField(upload_to='thumbnails') publish = models.BooleanField() categories = models.ManyToManyField(Categorie) mins_read = models.CharField(default=3, max_length= 3) read_count = models.IntegerField(default=0) class Meta: ordering = ['-pk'] def __str__(self): return self.title This is the portion of my index.html not rendering: {% extends 'base.html' %} {% block body %} {% load static %} {% for read in read_blogs %} <div class="mainsection-articles"> <div class="mainsection-articles-images"> <img src="{{read.thumbnail.url}}" alt="" style="width: 235px;"> </div> <div class="mainsection-articles-content"> <a href="../page1.html"> <h3> {{read.title}}</h3> </a> <span>Author:{{read.author}}|</span> <p>{{read.overview}}</p> <span>Date:{{read.time_upload}} </span><br> <a href="../blogpost.html">Read more...</a> </div> </div> {% endfor %} When I am inspecting using the browser, this whole section inside the forloop is not visible.Kindly help me out why only this portion is not rendering.Apart from this section every other section are visible and working perfectly. -
Visual Studio Code 'django-admin' command not recognized
'django-admin' is not recognized as an internal or external command, operable program or batch file... So I am getting this error in terminal. I am trying to build an app. First I opened a folder(page) in my computer D drive and then opened Visual Studio Code. From there I opened the folder(page) and from view I opened terminal. Then when I am trying to type django-admin myproject page. it is showing this error. -
nginx setup for Django Channels 3 using Daphne and Supervisor
I have created a Django application with channels. Now I am configuring it for production in AWS EC2. I can access the app when running the python manage.py runserver 0.0.0.0:8000. The apps that I deployed to AWS were using wsgi only and need only Gunicorn. But since channels use asgi the Daphne was used. It specifies few steps in the docs (https://channels.readthedocs.io/en/latest/deploying.html) /etc/supervisor/conf.d/asgi.conf [fcgi-program:asgi] # TCP socket used by Nginx backend upstream socket=tcp://localhost:8000 # Directory where your site's project files are located directory=/home/ubuntu/myproject # Each process needs to have a separate socket file, so we use process_num # Make sure to update "mysite.asgi" to match your project name command=/home/ubuntu/venv/bin/daphne -u /run/daphne/daphne%(process_num)d.sock --fd 0 --access-log - --proxy-headers myproject.asgi:application # Number of processes to startup, roughly the number of CPUs you have numprocs=1 # Give each process a unique name so they can be told apart process_name=asgi%(process_num)d # Automatically start and recover processes autostart=true autorestart=true # Choose where you want your log to go stdout_logfile=/home/ubuntu/log/asgi.out.log stderr_logfile=/home/ubuntu/log/asgi.err.log redirect_stderr=true /etc/nginx/sites-enabled/django.conf upstream channels-backend { server localhost:8000; } server { location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header … -
Django social-auth: How to handle Youtube (Google) Auth Error: AuthStateForbidden?
I am using django social-auth to authorize users in Google Analytics and Youtube. Hence one backend in 2 different templates is used. However, with Google Analytics everything works like charm, but when I try to authorize in Youtube in the end of the authentication process comes an error: social_core.exceptions.AuthStateForbidden: Wrong state parameter given. I have tried to remove already successfully authorized my app for Google Analytics Scopes from Google Account and authorize again for Youtube Scopes but it brings no difference. My youtube handler: class YouTubeLoginHandler(object): def __init__(self, client_secret): self.SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'] self.CLIENT_SECRETS_PATH = client_secret def init_youtube_api(self): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( os.path.abspath( os.path.join(os.path.dirname(__file__), self.CLIENT_SECRETS_PATH) ), scopes=self.SCOPES) flow.redirect_uri = 'http://localhost:8000/api/oauth/complete/google-oauth2/' authorization_url, state = flow.authorization_url( # Enable offline access so that you can refresh an access token without # re-prompting the user for permission. Recommended for web server apps. access_type='offline', # Enable incremental authorization. Recommended as a best practice. include_granted_scopes='true') return authorization_url My view in views.py @login_required def login_youtube(request): user = request.user youtube = YouTubeLoginHandler('client_secrets.json') authorization_url = youtube.init_youtube_api() return HttpResponseRedirect(authorization_url)