Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Type hinting for Django Model subclass
I have helper function for Django views that looks like this (code below). It returns None or single object that matches given query (e.g. pk=1). from typing import Type, Optional from django.db.models import Model def get_or_none(cls: Type[Model], **kwargs) -> Optinal[Model]: try: return cls.objects.get(**kwargs) except cls.DoesNotExist: return None Supose I have created my own model (e.g. Car) with its own fields (e.g. brand, model). When I asign results of get_or_none function to a varibale, and then retriveing instance fields, I get annoying warning in PyCharm of unresolved reference. car1 = get_or_none(Car, pk=1) if car1 is not None: print(car1.brand) # <- Unresolved attribute reference 'brand' for class 'Model' What's the propper type hinting to get rid of this warning? -
Django - Order by custom function
I have multiple projects in my subprogram, each with a different cost which I'm calculating in a custom function in my project model. How can I create a subprogram function that returns a list of projects ordered by the costs function in the projects model? Is this possible todo? Subprogram model: class Subprogram(models.Model): title = models.CharField(max_length=100) def projects_sorted(self): return self.project_set.all().order_by('costs') Project Model: name = models.CharField(verbose_name="Name", max_length=100) subprogram = models.ForeignKey(Subprogram, on_delete=models.CASCADE) def costs(self): costTotals = 0 costs = self.costs_set.all() for bcost in costs: costTotals += bcost.cost return costTotals -
Error loading shared library libjpeg.so.8 in Python Django project with Docker
I'm getting this error and have no idea how to fix this. I've tried to install libraries like jpeg-dev zlib-dev libjpeg-turbo-dev then reinstall Pillow library which is needed for Django Simple Captcha and also install libjpeg-turbo8 via Ubuntu command prompt but it has no effect. I'm using Windows 10. Error: Attaching to website_app_1 app_1 | [2021.06.12 11.36.10] INFO: Watching for file changes with StatReloader app_1 | Exception in thread django-main-thread: app_1 | Traceback (most recent call last): app_1 | File "/usr/local/lib/python3.9/threading.py", line 954, in _bootstrap_inner app_1 | self.run() app_1 | File "/usr/local/lib/python3.9/threading.py", line 892, in run app_1 | self._target(*self._args, **self._kwargs) app_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper app_1 | fn(*args, **kwargs) app_1 | File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run app_1 | self.check(display_num_errors=True) app_1 | File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 419, in check app_1 | all_issues = checks.run_checks( app_1 | File "/usr/local/lib/python3.9/site-packages/django/core/checks/registry.py", line 76, in run_checks app_1 | new_errors = check(app_configs=app_configs, databases=databases) app_1 | File "/usr/local/lib/python3.9/site-packages/django/core/checks/urls.py", line 13, in check_url_config app_1 | return check_resolver(resolver) app_1 | File "/usr/local/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver app_1 | return check_method() app_1 | File "/usr/local/lib/python3.9/site-packages/django/urls/resolvers.py", line 412, in check app_1 | for pattern in self.url_patterns: app_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ app_1 | res = … -
How to upload profile image in DRF (without creating a separate endpoint if possible) using Postman
I am trying to create an API to do al kind of creation in my models like(Roles, departments, user, profile etc) but I'm kinda stuck here how to upload image for profile avatar using Postman raw body. Can someone take me through this would be appreciated. Here is my profile model class Profile(HRMBaseModel): profile_avatar = models.ImageField(upload_to='profile_avatars/', blank=True, null=True) full_name = models.CharField(_('full name'), max_length=150, blank=True) father_name = models.CharField(_('father name'), max_length=150, blank=True) dob = models.DateField(max_length=10, blank=True, null=True) personal_email = models.EmailField(_('personal email'), blank=True, null=True) . . . roles = models.ManyToManyField(Role) departments = models.ManyToManyField(Department) nationality = models.ManyToManyField(Nationality) . . . def __str__(self): return str(self.full_name) Here is my serilzer with create method. class ProfileSerializer(serializers.ModelSerializer): roles = serializers.SlugRelatedField( many=True, slug_field="role_name", allow_null=True, required=False, queryset=Role.objects.all() ) departments = serializers.SlugRelatedField( many=True, slug_field="department_name", allow_null=True, required=False, queryset=Department.objects.all() ) user = UserSerializer(many=False) nationality = NationalitySerializer(many=True, required=False) class Meta: model = Profile fields = ( 'user', 'full_name', 'father_name', 'blood_group', 'personal_email', 'employee_id', 'dob', 'current_address', 'permanent_address', 'country', 'state', 'city', 'zip_code', 'roles', 'departments', 'nationality', . . . ) def create(self, validated_data): _roles = validated_data.pop('roles') _departments = validated_data.pop('departments') _nationalities = validated_data.pop('nationality', None) user_data = validated_data.pop("user") profile_data = { //Here profile_avatar should go "full_name": f"{user_data.get('first_name')} {user_data.get('last_name')}", "father_name": validated_data.get("father_name"), "dob": validated_data.get("dob"), "personal_email": validated_data.get("personal_email"), "current_address": validated_data.get("current_address"), "permanent_address": validated_data.get("permanent_address"), "country": validated_data.get("country"), … -
module 'accounts.views' has no attribute 'signup'
File "/Users/work/Projects/blog/myblog/urls.py", line 22, in <module> path('post/<int:pk>/signup/', views.signup, name="signup"), AttributeError: module 'accounts.views' has no attribute 'signup' I am trying to do a registration by mail using this guide https://shafikshaon.medium.com/user-registration-with-email-verification-in-django-8aeff5ce498d myblog/views.py import json from urllib import request from django.views import View from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Post, Comment from .forms import CommentForm from django.contrib.auth import get_user_model from django.contrib.auth.models import User from django.contrib.auth.tokens import default_token_generator from django.contrib.sites.shortcuts import get_current_site from django.core.mail import EmailMessage from django.http import HttpResponse from django.shortcuts import render from django.template.loader import render_to_string from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode UserModel = get_user_model() from .forms import SignUpForm from .tokens import account_activation_token def signup(request): if request.method == 'GET': return render(request, 'signup.html') if request.method == 'POST': form = SignUpForm(request.POST) # print(form.errors.as_data()) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your account.' message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) def activate(request, uidb64, token): try: uid … -
save() got an unexpected keyword argument, but i didn't change save method
save() got an unexpected keyword argument 'link' I read that error can appear when change save() method, but i didn't change it. My model: class Article(models.Model): link = models.CharField(max_length=50) title = models.CharField(max_length=50) author = models.CharField(max_length=20) body = models.CharField(max_length=5000) It is line where error: Article.save(link=title, title=title, author=author, body=body) -
Using a Python dictionary with multiple values, how can you output the data in a table with Jinja's for loops?
I am using Django to make an API request for current standings in a league table. I would like to display this data as a table in HTML. Here is the code I am using in views.py to make the Python dictionary. # Receive the json response response = json.loads(connection.getresponse().read().decode()) # Declare the dict to use current_table = {"position": [], "team":[], "points":[]} # Loop over 20 times as there are 20 teams in the league for x in range(20): team = response["standings"][0]["table"][x]["team"]["name"] points = response["standings"][0]["table"][x]["points"] current_table["position"].append(x + 1) current_table["team"].append(team) current_table["points"].append(points) return render(request, "predict/index.html", { "table": current_table, }) The raw output of the dict in the terminal and with {{ table }} using jinja is {'position': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 'team': ['Manchester City FC', 'Manchester United FC', 'Liverpool FC', 'Chelsea FC', 'Leicester City FC', 'West Ham United FC', 'Tottenham Hotspur FC', 'Arsenal FC', 'Leeds United FC', 'Everton FC', 'Aston Villa FC', 'Newcastle United FC', 'Wolverhampton Wanderers FC', 'Crystal Palace FC', 'Southampton FC', 'Brighton & Hove Albion FC', 'Burnley FC', 'Fulham FC', 'West Bromwich Albion FC', 'Sheffield United FC'], 'points': [86, 74, 69, 67, 66, 65, … -
Is there a Django plugin for Pycharm/Intellij?
I am working on a blog in django.So is there any Plugin for Pycharm or Intellij idea for django like VS code has? -
Django: sqlite3.OperationalError: no such table: auth_user and django.db.utils.OperationalError: no such table: auth_user
I am trying to create a new login ID in django. I have deleted the database file but it is still showing two errors: sqlite3.OperationalError: no such table: auth_user django.db.utils.OperationalError: no such table: auth_user I have tried doing makemigrations, migrate, makemigrations appname, migrate appname, migrate --run-syncdb, and migrate --database=database-name. But even after doing those, it still shows the same errors. Here is the console screen: (django_ai) C:\gsData\Workspace\venv\django_ai\src>python manage.py createsuperuser C:\gsData\Workspace\venv\django_ai\src Closest Word: Error in the try statement. Random Restart: Error in the try statement. 2021-06-12 16:16:09.640665: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found 2021-06-12 16:16:09.641185: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine. List Trainer: [####################] 100% Traceback (most recent call last): File "C:\gsData\Workspace\venv\django_ai\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\gsData\Workspace\venv\django_ai\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: auth_user The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\gsData\Workspace\venv\django_ai\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\gsData\Workspace\venv\django_ai\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\gsData\Workspace\venv\django_ai\lib\site-packages\django\core\management\base.py", line 354, in … -
Django Exception: 'TemplateDoesNotExist at /'
I'm new to Django and trying to convert a HTML template to Django project. This is my directory structure: . └── MyProject ├── db.sqlite3 ├── main │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ └── __init__.cpython-38.pyc │ ├── models.py │ ├── __pycache__ │ │ ├── admin.cpython-38.pyc │ │ ├── apps.cpython-38.pyc │ │ ├── __init__.cpython-38.pyc │ │ ├── models.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── views.cpython-38.pyc │ ├── static │ │ ├── assets │ │ │ ├── css │ │ │ │ ├── bootstrap.css │ │ │ │ ├── framework.css │ │ │ │ ├── framework-rtl.css │ │ │ │ ├── icons.css │ │ │ │ ├── night-mode.css │ │ │ │ ├── style.css │ │ │ │ └── style-rtl.css │ │ │ ├── images │ │ │ │ ├── 1920x1080 │ │ │ │ │ ├── img1.html │ │ │ │ │ ├── img2.html │ │ │ │ │ └── img3.html │ │ │ │ ├── avatars │ │ │ │ │ ├── avatar-1.jpg │ │ │ │ │ ├── avatar-2.jpg │ │ │ │ │ ├── avatar-3.jpg │ │ │ │ │ ├── avatar-4.jpg … -
DoesNotExist at /addToCart/1 User matching query does not exist
D:\DjangoDemos\venv\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = await sync_to_async(response_for_exception, thread_sensitive=False)(request, exc) return response return inner else: @wraps(get_response) def inner(request): try: response = get_response(request) … except Exception as exc: response = response_for_exception(request, exc) return response return inner ▶ Local vars D:\DjangoDemos\venv\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars D:\DjangoDemos\CartApp\views.py, line 15, in addToCart user = User.objects.get(id=uid) … ▶ Local vars D:\DjangoDemos\venv\lib\site-packages\django\db\models\manager.py, line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) … ▶ Local vars D:\DjangoDemos\venv\lib\site-packages\django\db\models\query.py, line 435, in get raise self.model.DoesNotExist( … ▶ Local vars -
django-allauth signup() missing 1 required positional argument: 'model'
As you can imagine i'm new to django. İ tried to use allauth package for signup-in issues. After studying bunch of basic tutorials etc. the basic configuration started to function just fine but i needed custom signup process for my project. So i started to dig more and implemented this topic to my code -- [1]: django-allauth: custom user generates IntegrityError at /accounts/signup/ (custom fields are nulled or lost) After the implementation i started to debug various issues caused by django-version difference but eventually i ve got the following error: TypeError at /accounts/signup/ signup() missing 1 required positional argument: 'model' Request Method: POST Request URL: http://localhost:8000/accounts/signup/ Django Version: 3.2.3 Exception Type: TypeError Exception Value: signup() missing 1 required positional argument: 'model' the topics and pastebin links that i've found are not working anymore. thats why i'm stucked with this error. i think im missing something basic but cant figure it out. Here are my model-form-settings and adapters below: models.py from djmoney.models.fields import MoneyField from django.db import models from django.contrib.auth.models import User from django_countries.fields import CountryField from phonenumber_field.modelfields import PhoneNumberField from django.dispatch import receiver from django.db.models.signals import post_save from django.contrib.auth.models import AbstractUser from django.conf import settings class CtrackUser(AbstractUser): date_of_birth = models.DateField(help_text='YYYY-MM-DD … -
curl: (3) Port number ended with '.'
curl: (3) Port number ended with '.' (env) (base) 192:core prashantsagar$ curl -X POST -d "client_id=CTrbHZNtiS2VrbN9iVaVzPRHU13sHdHZd6bbMoKZclient_secret=YQ0gtl7UXAJZK596bPetswWYYYyiG8Zq1zZcTytvs1f0t3cPMX2d0fTJbgNVq9eZ3qOvDTL0MekujuHvkaeiFn5ALjQ7yBKO3XYJWzXKQ4vqA4670krGm6KXf6wc2F33grant_type=password&username=sagar@fmail.com.com&password=sagar" http://localhost:127.0.0.1:8000/auth/token/ curl: (3) Port number ended with '.' -
I am trying to deploy django application using heroku but getting error?
Build is successdul and it is producing application error, i have set up host name and debug=False as suggested but it is still causing error in opening the browser window, i am new to heroku so please suggest what needs to be done to make it work my settings.py """ Django settings for djangoTut project. Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent print(BASE_DIR) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = mysecretkey # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['djangoblog-project.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', ] 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', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'djangoTut.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'djangoTut.wsgi.application' … -
How to make simple python UDP socket server?
I am trying to make a python socket server based on UDP. The point is that we need to receive data from the Java client socket server and the python UDP protocol socket server must throw JSON data to React in the front. I have the level of knowledge to make a simple UDP chat server, so I'm worried a lot now. I am currently reading the django channels official documentation. Does django-channeles provide easy configuration to use UDP protocol as well? -
how do I solve Django TypeError - post() got multiple values for argument 'slug'?
I am creating a e commerce website and I am a beginner in Django and Python My cart name is "Kart" The cart is an cart object in session. It store the cart in session. it Works in main shop page but it is not working in product_details(productView) The views.py logic adds the product in cart but it dose not redirect to product page as a post request. I have to click on address bar and reload again to get back to product page. Product details page Views.py class productView(View): def post(request, slug ): product = request.POST.get('product') remove = request.POST.get('remove') kart = request.session.get('kart') if kart: quantity = kart.get(product) if quantity: if remove: if quantity <=1: kart.pop(product) else: kart[product] = quantity-1 else: kart[product] = quantity+1 else: kart[product] = 1 else: kart = {} kart[product] = 1 request.session['kart'] = kart return redirect('product-view', slug=slug) def get(self,request, slug): product = Product.objects.filter(product_slug=slug) return render(request, 'T_kart/ProductView.html', {'product': product[0]}) urls.py from django.contrib import admin from django.urls import path from . import views app_name = 'T_kart' urlpatterns = [ path('', views.index.as_view(), name="T-kart-Home"), path('product-<slug:slug>/', views.productView.as_view(), name="product-view"), path('kart/', views.kart.as_view(), name="kart"), path('checkout/', views.checkout, name="checkout"), path('search/', views.search, name="search"), path('wishlist/', views.wishlist, name="wishlist"), ] Template (html) <div style="display: flex; align-items: center; justify-content: center; margin-top: … -
django text box in user get value of quantity automatic mutipication and insert the database
your quantity in user insert the value and database insert the all pen rate=3 basic quantity =90 and user quantity get value of user and automatic multiply by rate and save into database -
Attritube error when importing local python file
I would like some help in figuring out an issue. The code below is attempting to import a file called game_getter.py to access it's all_games dictionary variable. from django.db import models from catolog import game_getter # Create your models here. class Game(models.Model): url_clue = ["//images.igdb.com"] for game in game_getter.all_games: title = game_getter.all_games[game][0] if url_clue in game_getter.all_games[game][1]: cover_art = game_getter.all_games[game] else: pass if game_getter.all_games[game][2] == None: pass else: storyline = game_getter.all_games[game][2] if game_getter.all_games[game][3] == None: pass else: storyline = game_getter.all_games[game][3] genre_pac = game_getter.all_games[game][4] def __str__(self): return self.title class UserSearch(): user_input = str At the bottom of this next session I used a return on the dictionary object all_games. I've even tried making it a global variable and the computer still won't see it. # Create a search def search_query(user_input, exp_time): # Generate token if needed generate_token(exp_time) #establish client_id for wrapper client_id = "not my client_id" wrapper = IGDBWrapper(client_id, token) # Query the API based on a search term. query = wrapper.api_request( 'games', # Requesting the name, storyline, genre name, and cover art url where the user input is the search tearm f'fields name, storyline, genres.slug, cover.url; offset 0; where name="{user_input}"*; sort first_release_date; limit: 100;', # Also sorted by release date with … -
need help to render graph inside web page on date range picker in Djanog
i created form in my html form to pick date range using daterangepicker and passed same to views.py in DJANGO. After clicking submit button (POST), views.py function being called thru url.py and got the DB query result and reruns JsonResponse. now issue is my web page is geeting redirected to new web page. but i want to stay in same webpage and get the graph to display. HTML page is <div> <form action="/reportgeneration" method="POST"> {% csrf_token %} <input type="text" name="daterange" /> <input type="submit" value="Submit"> </form> </div> <div id="EnegryChart"></div> <script> var start = moment().subtract(29, 'days'); var end = moment(); $(function () { $('input[name="daterange"]').daterangepicker({ opens: 'left', showDropdowns: true, "drops": "auto", startDate: start, endDate: end, locale: { format: 'YYYY-MM-DD' }, ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] } }, function (start, end, label) { console.log("A new date selection was made: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD')); }); }); </script> and my URL.py is urlpatterns = [ ........ path('reportgeneration', views.reportgeneration), ..... and views.py is def reportgeneration(request): ........ if request.method == "POST": date_range = request.POST.get('daterange').split(" - ") … -
URL to work with parameter and without parameter in Django
I am using Django for my project, and I want to render thank-you page. But it should be with or without parameters. urls.py urlpatterns = [ .... path(r'thank-you?t=<type>?n=<name>', thank_you_view, name='thank-you'), .... ] it is working fine for urls like :http://127.0.0.1:8080/thank-you%3Ft=teacher%3Fn=Ajay,%20Gaikwad Template make use of parameters. but not working for url without parameters like : http://127.0.0.1:8080/thank-you Default template will be rendered here. also I tried some regex path(r'thank-you(?t=<type>?n=<name>|'')', thank_you_view, name='thank-you'), But it not working. views.py def thank_you_view(request, *args, **kwargs): context = {kwargs['type']: kwargs['name']} return render(request, "light/thank-you.html", context=context) -
Django and BeautifulSoup timeout error while scraping
I have a scraper inside my views.py which gets movie and actor data and downloads their pictures from IMDB and inserts them into the Database. Occasionally when I try to scrape some movies(especially ones with higher quality images) I run into nginx timeout error. I've tried to get a log from my code and I found out that as soon as my script gets to the point where it should download high-quality images it crashes and gives me the timeout error. I've tried setting different timeouts for my soup(ranging from 10 to 30) like below but it didn't seem to work: image_url = soup.find('img', class_='ipc-image').get('src') img_obj = requests.get(image_url, headers=headers, timeout=20) img = Image.open(BytesIO(img_obj.content)) img_title = to_url(title) img.save('media/' + img_title + '.webp') I also tried combining it with time.sleep(10) but still I would get the same error. My script works fine for almost 50% of movies but gives me a timeout error for the rest. What else can I do to prevent this from happening? Thanks in advance for your help. -
Problem with django social login allauth : redirects to http://127.0.0.1:8000/accounts/social/signup/# if email exists
I am creating a blog app using django. Now when someone manually registers an account with a particular email and then go back to the login page and try to login using google allauth, it redirects to http://127.0.0.1:8000/accounts/social/signup/# What can I do to connect both the accounts? Using process='connect in the href does not help as it always takes me to that page -
I have passed __all__ in fields of meta class and still i am getting back only one field. suggest a better way to fix it I want all the field there
I have included the serializer as well as the views.py, I am new so it might be possible that i made a very silly mistake here, which I am not able to figure out, please review this code and make me understand how to resolve this issue. serializer.py class ServiceSerializer(serializers.RelatedField): def to_representation(self, value): return value.name class Meta: model = Service fields = ('name') class SaloonSerializer(serializers.Serializer): services = ServiceSerializer(read_only = True, many=True) class Meta: model = Saloon fields = ( 'name', 'services' ) Here in the field of SaloonSerializers I have tried multiple things like only name field but still if get just one output which i have attache at the end of this post. views.py @api_view(['GET']) def saloon_list(request): if request.method=="GET": saloons = Saloon.objects.all() serializer = SaloonSerializer(saloons, many=True) return Response(serializer.data) output: [ { "services": [ "Cutting", "Shaving", "Eye Brow", "Waxing", "Facial massage" ] }, { "services": [ "Cutting", "Shaving", "Facial massage" ] } ] -
I am trying to get the social authentication working wirh DRF
I am trying to use custom user model with dj_rest_auth. here is the repo Problem one: The dj_rest_auth return the reponse as { "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjIzNTY5MzM2LCJqdGkiOiI3YTk1ZjJhM2Y2ZTE0ZmVlOWQzMjEwMDZkMmJiZDk5MSIsInVzZXJfaWQiOjZ9.4yjIBxXhe5grxCe18huamgj1qP44A-zOkUHxZ61wXao", "refresh_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYyMzU2OTMzNiwianRpIjoiODFlYzdkNjVjZjQzNDI4NjlhYjYzODI4MWUxNDQ4MjUiLCJ1c2VyX2lkIjo2fQ.1p3_Vw8OYoa64B93wHiEEiyKH3oT8M-3FGrivZmvWaA", "user": { "pk": 6, "email": "test@gmail.com" } } But I want to return all the necessary fields as the user object. How can I get that. Problem two: I can register the user by using the path('api/auth/registration/', include('dj_rest_auth.registration.urls')), but I can't login with same credentials using path('api/auth/', include('dj_rest_auth.urls')), It gives me that { "non_field_errors": [ "Unable to log in with provided credentials." ] } *** Please also suggest me should I use dj_rest_auth or should I use other library to make it working with custom user model. -
Wagtail - one "profile" page per user
I am creating website, where center of everything will be creating profile. Profile has lot of properties (imagine dating site for example), rich text and images. I was thinking of creating page type for this purpose (maybe ProfilePage), containing all information of the user. Any user will be able to register and then create it's own profile. I have lot of experience with django, no experience with wagtail and I am wondering, if there's easy way to hook it all up so that it's all nice and user friendly through wagtail admin interface? Another approach I though of was to put most of things into custom User model and then edit those properties directly through admin, but this still doesn't solve some rich content (profile can contain rich text and images). Or does it?