Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Failing to launch, at=error code=H10 desc="App crashed" | django
This is the message I see in my logs. The code in my log file is also accurate as it is supposed to be. Also I have gunicorn installed in my VENV. Can someone help me deply this django app on heroku. -
Django error when accessing many to many through field of not managed model
I am getting this weird error which I am unable to sort out myself: 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache' Relevant parts of code are these: models.py: class Section(models.Model): type = models.IntegerField(blank=True, null=True) child=models.ManyToManyField( 'self', through='SectionParent', through_fields = ('parent_section_id', 'section_id'), ) class Meta: managed = False db_table = 'section' class SectionParent(models.Model): section = models.ForeignKey(Section, on_delete=models.CASCADE, related_name="m2m_child") parent_section = models.ForeignKey(Section, on_delete=models.CASCADE, related_name="m2m_parent") class Meta: managed = False db_table = 'section_parent' views.py: def navigation(request, section_id=None): # Load species if no id is provided if not section_id: sections = Section.objects.using('app-db').filter(type=SectionType.speciesCategory.value[0]).first() # Load children of current section else: sections = Section.objects.using('app-db').filter(id = section_id).first() print(sections.child()) <-------------- ERROR HERE return HttpResponse("test") I tried to modify models.py many times including adding related_name, replacing 'self' with 'Section' and other things, changing name of the relationship (child), but nothing seems to sort this out. I think it might be related to the fact that the model runs over existing database (hence managed = false), as I never got such an error with migrations enabled. -
Django: While loop doesn't work correctly
i'm buildint a warehouse management application, i have a product model and an placement for each product, every placement has a volume, once i put a product in a placement, the volume of this placement must be reduced. The problem is when the app finds a placement for the product, the placement volume stay the same models.py class Emplacement(models.Model): address = models.CharField(max_length=25, blank=True) volume = models.DecimalField(max_digits=10, decimal_places=2, null=True) class Product(models.Model): name = models.CharField(max_length=100) quantity = models.PositiveIntegerField() is_disponible = models.BooleanField(default=False) volume = models.DecimalField(max_digits=20, decimal_places=2, null=True) emplacement = models.ForeignKey(Emplacement, on_delete=models.CASCADE, null=True) views.py def product_detail(request, pk): product = get_object_or_404(Product, id=pk) if request.method == 'POST': form = ValidateProductForm(request.POST, instance=product) if form.is_valid(): product = form.save(commit=False) product.volume = form.cleaned_data['longueur'] * form.cleaned_data['largeur'] * form.cleaned_data['hauteur'] product.is_disponible = True all_emplacements = Emplacement.objects.all() i=1 while i <= product.quantity: for emplacement in all_emplacements: if product.volume < emplacement.volume: product.emplacement = emplacement emplacement.volume -= product.volume i+=1 product.save() return redirect('print-barcode', product.id) else: form = ValidateProductForm(instance=product) context = { 'product': product, 'form': form, } return render(request, 'dashboard/product_detail.html', context) -
Connection refused setting up Nginx + Gunicorn/Django REST
I have a setup with Nginx as web server, Gunicorn as application server serving a Django REST API, all of this inside a docker container. Within the container, I launch gunicorn using this command: gunicorn --bind 0.0.0.0:8000 cdm_api.wsgi -t 200 --workers=3 and I am able to access to the API running for instance: curl -d "username=<user>&password=<pass>" -X POST http://127.0.0.1:8000/api/concept However, when I run the same from outside the container I get: curl: (7) Failed to connect to 127.0.0.1 port 8000: Connection refused Nginx is listening to port 80 inside the container which maps to port 8080 outside the container in localhost. I am able to access nginx but it seems nginx is unable to act as reverse proxy and redirect calls to 8000 (outside the container) to 8080 (inside the container). Here is my nginx conf file: server { listen 80; listen [::]:80; server_name 127.0.0.1; location /api/ { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_connect_timeout 360s; proxy_read_timeout 360s; } location / { root /usr/share/nginx/html; index index.html index.htm; } } Let me know if more information is needed. Thanks in advance! -
PYTHON 3.6.0 & DJANGO 3.5.0 'module' object is not iterable when running django website to the server
So i'm gonna run my Django project with python manage.py runserver but suddenly there comes an error like these: Exception in thread django-main-thread: Traceback (most recent call last): File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\urls\resolvers.py", line 590, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\management\base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\urls\resolvers.py", line 597, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'project_settings.urls' does not appear to have any patterns in it. If you see valid patterns in the file … -
Is there a way I can pass the context using return redirect in Django?
I wanted to pass the context using return redirect since using return render will send the post again when refreshing the page. This is my code for my return render: context = { 'file_path': file_path+'reviews_processed.csv', 'file_name': 'reviews_processed.csv', } messages.add_message(request, messages.SUCCESS, 'Processing done!') return render(request, 'vlookup/vlookup.html', context) and this is what I am trying to achieve: # return redirect(vlookup, context) Thanks! -
No such file or directory: 'profile_pics/img.jpg'
When a user attempts to upload a profile picture this error is displayed. However the image is successfully uploaded to the database and displayed in the app. I believe the error is something to do with the redirection after the form submits but I couldn't figure it out. I recently set my app up with aws s3 buckets so that might also have something to do with it but the images are successfully uploaded and pulled from the bucket so likely un related. view: def profile(request): if request.method == 'POST': p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if p_form.is_valid(): p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'p_form': p_form } return render(request, 'users/profile.html', context) model: class Profile(models.Model): image = models.ImageField(default='default.jpg', upload_to='profile_pics') .... def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile,self).save(*args, **kwargs) img = Image.open(self.image.name) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Update Profile</legend> {{ p_form|crispy }} </fieldset> <div class="form-group"> <button class="action-btn" type="submit">Update</button> </div> </form> -
Dynamically add a particular field by button in django?
I have a form, and i need to keep a function like when user click on "Add button" a particular field needs to created again below it. Likewise new field should be created on each click. On a research i found that, we can use def __init__(self, *args, **kwargs): method can be used to do that, but how to do that for a particular field ? Am planning to follow this question, and it has function to create dynamic forms but i need dynamic fields not the whole form. And i cant use formsets, as its create whole form i belive ! -
Check if User sending request is in different model
I'm trying to create an API using the REST Framework. I ran into a little problem. I want to be able to get a list of events for a specific user by sending a request to the API. Is there a possibility to check if the User sending the request is in the team the event belongs to when an event list is requested? class Teams(models.Model): name = models.CharField(max_length=100) description = models.TextField(max_length=1000, blank=True) Users = models.ManyToManyField(User, blank=True) class Event(models.Model): created = models.DateTimeField(auto_now_add=True) eventTime = models.DateTimeField() title = models.CharField(max_length=100, default='') description = models.TextField(max_length=1000, blank=True) group = models.ForeignKey(Teams, on_delete=models.CASCADE) owner = models.ForeignKey(User, on_delete=models.CASCADE) those are the realtionships between the models i implemented so far -
Django Model Inheritance to miultiple apps
class People(models.Model): # Utility Fields - auto fill # Timestamp # Base Fields # Methods, e.g save, get_absolute_url class Meta: abstract = True App clients: inherit from People model + its own Fields Vendor clients: inherit from People model + its own Fields Q1: Where should i place the code for People model, since i want to use it for more than 2 apps? Q2: Is this practice acceptable? Q3: Will it work in production environment efficiently? -
Does Django support custom language codes?
I need longer language codes for my project than two or five character long ones. By default Django support languages which have language code like "en" for English and "en-GB" for English (British). Is there way to use longer language codes (8 characters). This is needed for my project which uses Glottolog cataloque https://glottolog.org/glottolog/language for languages. I have tried add LANGUAGES = [("aari1239", "Aari"),] in project settings. With this language I can create po-files. But when I try to switch language with POST-request to /i18n/setlang/ default language English is set to language. -
Django DetailView don't show data in template
Hello I'm just starting use the CBV in Django. My ListView working normal it can get the id in models except DetailView. It don't show the detail data.[https://drive.google.com/file/d/17yeU-LdvV_yLjnBB2A2gYt5ymSeKvPAR/view?usp=sharing][1] Here the code: models.py: class School(models.Model): name = models.CharField(max_length=125) principal = models.CharField(max_length=125) location = models.CharField(max_length=125) def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=70) age = models.PositiveIntegerField() school = models.ForeignKey(School,related_name='students',on_delete=models.CASCADE) def __str__(self): return self.name views.py: class School_List(ListView): context_object_name = 'schoollist' model = School class School_Detail(DetailView): contex_object_name = 'schooldetail' model = Student template_name = 'basicapp/School_detail.html' detail.html: {% block content %} <h1>Site showing School Detail</h1> <div class="container"> <div class="p-5 text-white bg-dark rounded-3 container"> <p>Name: {{schooldetail.name}}</p> <p>Principal: {{schooldetail.principal}}</p> <p>Location: {{schooldetail.location}}</p> <h2>Student: </h2> {% for student in schooldetail.students.all %} <p>{{student.name}} who is {{student.age}} years old</p> {% endfor %} </div> </div> {% endblock %} Thank you -
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'User.Users' (django)
I want to get User in shell, i have custom User and UserMnager models. this is my code- > from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractUser from django.core.validators import validate_email from django.utils.translation import gettext_lazy as _ class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): validate_email(email) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class Users(AbstractUser): username = models.CharField(max_length=30, unique=True,verbose_name=_("ზედმეტსახელი")) email = models.EmailField(_('ემაილი'), unique=True) first_name = models.CharField(max_length=30, verbose_name=_("სახელი")) last_name = models.CharField(max_length=50, verbose_name=_("გვარი")) mobile = models.CharField(max_length=9, verbose_name=_("მობილური")) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.get_full_name() My user model's name is User's' and manager's name is UserManager. i thinked this is problem but no. also i have AUTH_USER_MODEL = 'User.Users' in settings.py in shell i call --> from django.contrib.auth import get_user_model and after i run Users.objects.all() -> NameError: name 'Users' is not defined and User.objects.all() -> AttributeError: Manager isn't available; 'auth.User' has … -
Django retrieve filter value in views.py
I would like to prompt the user a dropdown box with all the values of a specific attribute, and retrieve this value in views.py to use it as function argument (to filter the output of a view function). Example: models.py class User(models.Model): name = models.CharField(max_length=30) email = models.CharField(max_length=30) address = models.CharField(max_length=30) def __str__(self): return self.name views.py def users(request): users= User.objects.all() context = {'users': users} return render(request, 'users.html', context) users.html {% block content %} <div> <table style="width:100%" class="table table-hover table-sm table-stripped"> <thead class="thead-dark"> <tr> <th>Name</th> <th>E mail</th> <th>Address</th> </tr> </thead> {% for i in users%} <tr> <td>{{i.name}}</td> <td>{{i.email}}</td> <td>{{i.address}}</td> </tr> {% endfor %} </table> </div> {% endblock content%} I would like to display in my html a dropdown with all the User.name values, and when selected use the selected_user value as an argument in views.users() to filter the displayed table. Any idea on how to proceed ? -
Why is my django code for POST Method not working?
I am working on a django website and I am trying to receive data from the user through POST Method. The error message is : MultiValueDictKeyError at /prediction/ 'date1' Request Method: GET Why is the request Method still GET even though I have POST in my views.py? Views.py : from django.shortcuts import render from apple.models import predictions # Create your views here. def home_view(request): pre = predictions.objects.filter(date='2021-01-15') return render(request, 'homepage.html', {'prediction': pre}) def read(request): final_date = str(request.POST["date1"]) price = predictions.objects.filter(date=final_date) return render(request, 'results.html', {'price':price}) This is my 2nd HTML page Results.html : <!DOCTYPE html> <html> <head> <link href='https://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Arimo' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Hind:300' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'> <title>Prediction Page</title> </head> <body> <h1>"The Predicted price for this date is:" + "{{price}}"</h1> </body> </html> <style> @import url(https://fonts.googleapis.com/css?family=Open+Sans); html { width: 100%; height: 100%; overflow: hidden; } body { width: 100%; height: 100%; font-family: 'Open Sans', sans-serif; background: #331952; color: #fff; font-size: 18px; text-align: center; letter-spacing: 1.2px; } </style> This is the main HTML Page - homepage.html ( from where 'date1' is coming from ) : <!DOCTYPE html> <html> <head> <link href='https://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Arimo' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Hind:300' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'> <title>Apple Stock … -
Tried to update field with a model instance, <SimpleLazyObject:<<>>. Use a value compatible with CharField
I am trying to over ride the save method in my model to store the currently loged in user. I am using the django-current user to get the authenticated user. I wrote this code from django_currentuser.middleware import ( get_current_user, get_current_authenticated_user) from django_currentuser.db.models import CurrentUserField uploaded_by = models.CharField(max_length=255, blank=True, null=True, editable=False) def save(self, *args, **kwargs): user = get_current_authenticated_user() self.uploaded_by = user super(Citation, self).save(*args, **kwargs) But I am getting this error Tried to update field professional.Citation.uploaded_by with a model instance, <SimpleLazyObject: <CustomUser: staff@gmail.com>>. Use a value compatible with CharField. Please suggest me what should I do as I want to store the currently loged in user in the model save method and aslo keep this field non editable. -
How to prevent Django Crashing when Database Schem becomes changed in PgAdmin?
we are currently developing dashboards for a hospital with Django. For this we connect to a Postgres database (read only) with Django and create a monitoring for the data. We have read information about the database tables with: python manage.py inspectdb The problem is that the hospital sometimes adds new columns in the Postgres DB and sometimes deletes columns. If only new columns are added, our Django application still works. But if a column is deleted, nothing is visible on the dashboard anymore. We would like to handle this in such a way that if e.g. column 4 is missing in the database then all visualizations that require column 4 are not displayed, but all other charts are still displayed. How can we avoid a crash / nothing displayed when only one column is deleted? We tried already something like this, which is not working: class Test(models.Model): col1 = models.CharField(primary_key=True, max_length=10) try: col2 = models.CharField(max_length=10, blank=True, null=True) except: pass ... class Meta: managed = False db_table = 'test' Thank you very much for giving us any advices with your experience! -
Sending CSV to client over SSE on file generation
I'm learning Django on the fly so sorry if this is a stupid question, I think the answer is no. I'm wanting to push a generated CSV file to the client and download it automatically after it's finished. I was originally going to create a view for this, but I'm unable to call a view function from an external function. Views passes form data to an external function to process. Views.py: def viewsFunc(request): if request.method == "POST": csvUpload = pd.read_csv(request.FILES['filename']) userName = request.POST['Username'] password = request.POST['Password'] x = threading.Thread(target=externalScript.externalFunc, args=[csvUpload, userName, password]) x.setDaemon(False) x.start() return render(request, 'app/htmlPage.html') externalScript.py: def externalFunc(csvUpload, userName, password): 'do stuff & sends data to client, create CSV' send_event('test', 'message', {'text': data}) As you can see, I'm unable to return response from here outside of views.py so I'm not sure if it's possible or what best practice would be. Best case scenario is I pass the CSV to the client without saving to the server. -
How can I define a django model's field default value to be another field value?
In my model I have these two fields: start_bid = models.IntegerField(default=0) max_bid = models.IntegerField(default="the start_bid value") The start_bid will be added by the user once through Django ModelForm. And the max_bid may change and may not. So I need the first value of 'max_bid' to be the start_bid value entered by the user, then if it changes it will be updated. In brief, I need the initial value of max_bid to be equal to the start_bid! Any suggestions? -
Displaying number of messages sent by each category of users
This is what message_user_id contains: message_user_id = Message.objects.all() This is my context dictionary in admin.py: 'msg' : message_user_id, This is my Message class in models.py: class Message(models.Model): message_text = fields.EncryptedTextField(blank=True, null=True) conversation_id = models.ForeignKey(Conversation, on_delete=models.CASCADE) origin_user = models.ForeignKey(UserInfo, on_delete=models.CASCADE, blank=False, default=None) timestamp = models.DateTimeField(default=datetime.now, blank=True) This is UserInfo class: class UserInfo(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) is_buyer = models.BooleanField(default=False) is_seller = models.BooleanField(default=False) is_professional = models.BooleanField(default=False) There are different roles for users that they can choose from while sign up. That information stays in UserInfo table which I'm referencing to as a foreign key in origin_user field in Message class. origin_user in Message contains the same information as id in UserInfo. I want to display the number of messages sent by each category of users. How do I achieve this?. -
How to store all IP addresses that related to user in django? [closed]
I want to store all IP addresses of each user in the database, I want each time to keep the IP before the change and append the next one to the same field, for exemple I want a list that take all IP from the creationg of Profile. I collect IP adresses using this middelware from dashboard.models import Profile from django.utils.deprecation import MiddlewareMixin class SaveIpAddressMiddleware(MiddlewareMixin): def process_request(self, request): # sourcery skip: use-named-expression x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') if request.user.is_authenticated: profile = Profile.objects.get(user=request.user) profile.ip_address = ip profile.save() model.py from django.db import models from django.contrib.auth.models import User from .formatChecker import ContentTypeRestrictedFileField # Extending User Model Using a One-To-One Link class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(blank=True, max_length=150) ip_address = models.GenericIPAddressField(null=True, max_length=30) avatar = ContentTypeRestrictedFileField(max_upload_size=10485760, null=True, verbose_name="",default='default.jpg', blank= True, content_types=['image/png', 'image/jpeg']) def __str__(self): return self.user.username -
How to access array of files in request with Django Rest Framework
I'm sending a request from a React frontend to Python backend, in this request i'm sending a FormData() with an array of images, like this: const data = new FormData() images.forEach(image => { data.append('images', image.arquivo) }) data.append('product', JSON.stringify(product)) return recuperarInstanciaAxios(true).post(`${recuperarUrlBackend()}/products/`, data) But I'm not being able to access this array of pictures in Python. Through PyCharm evaluate, request.FILES shows me a dict with an array 'images' within. But when I do request.FILES['images'] it returns me a single file. This is the python code: def create(self, request): try: productData = json.loads(request.data['product']) serializer = ProductSerializer(data=productData ) if serializer.is_valid(): product = serializer.save() files = request.FILES['images'] for image in files: product_image= {'image': image, 'product': product.id} image_serializer = ProductImage(data=product_image) if image_serializer .is_valid(): image_serializer .save() else: raise IntegrityError('Error :' + serializer.errors.__str__()) return Response(serializer.data, status=status.HTTP_201_CREATED) else: raise IntegrityError('Error:' + serializer.errors.__str__()) except IntegrityError as exc: print(exc) return Response(exc.__str__(), status.HTTP_412_PRECONDITION_FAILED) It gives me an error because files is not iterable. Am I accessing the array in a wrong way? -
Django how to prevent brute force attack by showing captcha in login page after few failed attempt?
I know there have few package available like django-defender, django-axes etc for prevent brute force attack. I am thinking to prevent brute force attack using Django session or somethings like this without help of any package. I want to count failed login attempt in my views then it will show the captcha after number of failed login attempts. So it will be simple two step: step1) it will count the failed login attempts. step2) It will show the captcha after number of failed login attempts here is my views.py : def login_view(request): if request.method == 'POST': username = request.POST.get('username') password =request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.add_message(request, messages.INFO,'Login Sucessfull') else: messages.info(request, "wrong username or password") -
Google OAuth RefreshError even with Refresh Token present in the Django app
My app running on Django with Django allauth allows signup/login only via Google OAuth. Therefore when a user is registered, his social oauth details are saved to All-auth Social Accounts model and the token data saved in Social Application Tokens model. We want the users to be logged-in as long as possible, without granting/revoking access regularly. Question 1: The default expiry is set as 1 hour from the registration time. How can I extend this programmatically and for how long (can it be never-expire?) Currently, a user logged in at 5:00 and I get the following data from credentials.to_json(): { "token": "ya29.A0ARrdaM8YXPM35RXPv7UK-pXLZvWG49T-MgCZ5wMse2ADMXOZJOWFJKMaq1PkobADLptM5YX5mnrliS2yCCESqCk0NTaZJkfe6inK94j6WQMFZWIT_xRyBTOX4W3dUEiuLhHFpQcD5vS-x_Y22pUzxwgI23pp", "refresh_token": "1//0gYC8oucHhTBVCgYIARAAGBASNwF-L9IrCG7c5IJCBMVznUrytGEFsJbsObAFvmNBoQbHHGA1KESyBWgmudEVogbes8ski87q_5g", "client_id": "blablabla.apps.googleusercontent.com", "client_secret": "xyzsecret"} No other data is returned. At 6:05, the credentials.to_json() is exactly the SAME AS ABOVE. But to fetch any Google/Youtube API data, I get the following error in server logs: google.auth.exceptions.RefreshError: The credentials do not contain the necessary fields need to refresh the access token. Question 02: When there's a Refresh Token available already, why the error? As per the docs, it refreshes the token automatically few minutes before the expiry. What am I missing? I already had "access_type": "offline" in the providers settings. I also tried adding "prompt": "consent", but no … -
How do I connect to any network printer from server and give multiple print job?
I will try to describe my problem as story. I have one computer in my house and that is connected to internet. My uncle has one printer which is on my Uncle's house (100 miles away from our house). That is also connected to internet. I have one Django app which is hosted on AWS. I want to click on print button on hosted Django app. Which will print 100 pdfs on my uncle's printer automatically.(Assume uncle's printer is connected to internet) I have IP address of my uncle's printer. How can I print 100 pdfs from my uncle's printer from hosted django app?