Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to connect 2 many to many fields in Django
I have 2 many to many fields in models and i want to connect them to each other i mean if i connect user in Admin Model with Counter Party i cant see that in Counter Party admin How can i do that? When im trying to do that it shows only in 1 model models.py class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='Пользователь') user_counter = models.ManyToManyField('CounterParty', blank=True, verbose_name='Контрагенты пользователя') def __str__(self): return f'{self.user}' class CounterParty(models.Model): GUID = models.UUIDField(default=uuid.uuid4, editable=True, unique=True) name = models.CharField(max_length=150, verbose_name='Наименование') customer = models.BooleanField(default=False, verbose_name='Заказчик') contractor = models.BooleanField(default=False, verbose_name='Подрядчик') counter_user = models.ManyToManyField(User, blank=True, related_name='counter_user', verbose_name='Пользователи контрагента') class Meta: verbose_name = 'Контрагент' verbose_name_plural = 'Контрагенты' def __str__(self): return admin.py from django.contrib import admin from .models import CustomUser, CounterParty, ObjectList, SectionList from authentication.models import User from authentication.admin import UserAdmin class CustomUserInLine(admin.StackedInline): model = CustomUser can_delete = False verbose_name_plural = 'Пользователи' class CustomUserAdmin(UserAdmin): inlines = (CustomUserInLine,) @admin.register(CounterParty) class CounterPartyAdmin(admin.ModelAdmin): pass admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) user admin counter party admin -
How to deal with json response in django from external API
I am currently building a simple dashboard in Django using data from external API like Amazon SP-API. My main question is how do you keep data in models as all the response are in JSON format. Do you store them as JSON Field or serialize all fields into separate columns in SQL Database? I am iterating over 100 accounts using different refresh tokens. Currently created model with separate columns but some of JSON's are nested multiple times and processing and saving them to database is cpu consuming. -
How to prevent multiple queries by inlines in Django admin?
I fought with this all day yesterday, but can't really find a way out. I've got three models where A is related to C through B. The A-admin inlines B which has the FK to C. The admin inlines are causing queries per item which is incredibly slow. Making the offending fields raw_id_only does help (readonly even further), but that is not what I'm trying to do. I read in a few bug tickets, that this intended behaviour, because they don't want to keep the queryset for the choices in memory. But I do want that. Just I'm not sure where to start. I'd like to create a dict of all C (just id and str actually) in the A-admin once and then pass it to each of the inline admins forms instead of it causing another query. How could I pull this off? Here is the ticket that describes the behaviour in detail: https://code.djangoproject.com/ticket/31295 Thank You! -
How to catch all `select2:open` events in the Django 4 admin site?
I just can't seem to catch the select2:open events that should be triggered by Select2 dropdowns used by Django ForeignKey fields with the autocomplete feature enabled. Here is the code I'm currently running to catch those events (I am trying to automatically set the focus to the child search bar whenever a Select2 is open): -- autofocus_select2_searchbars.js /** * Add an event listener to all the select2 widgets on the page so that * when they are opened, the search input is automatically focused. */ function setFocusOnSearchBarsWhenSelect2WidgetsAreOpen() { console.log('setFocusOnSearchBarsWhenSelect2WidgetsAreOpen'); $(document).on('select2:open', () => { console.log('select2:open'); document.querySelector('.select2-container--open .select2-search__field').focus(); }); } $(document).ready(function () { setFocusOnSearchBarsWhenSelect2WidgetsAreOpen(); }); and I am calling this in change_form.html so it gets applied to every change view in the admin: -- myproject/templates/admin/change_form.html {% extends "admin/change_form.html" %} {% load i18n admin_urls static %} {% block admin_change_form_document_ready %} {{ block.super }} <script src="https://code.jquery.com/jquery-3.6.3.slim.min.js" integrity="sha256-ZwqZIVdD3iXNyGHbSYdsmWP//UBokj2FHAxKuSBKDSo=" crossorigin="anonymous"></script> <script> {% include "./shared/autofocus_select2_searchbars.js" %} </script> {% endblock admin_change_form_document_ready %} The problem is that the select2:open event never gets fired. -
How to avoid duplicates when Prefetch m2m related objects with soft deletable models?
I want to get list of accounts with not deleted relations. Models class User(models.Model): accounts = models.ManyToManyField( to='billing.Account', through='custom_auth.UserAccount', through_fields=('user', 'account'), related_name='users', ) deleted = models.DateTimeField( verbose_name=_('Deleted at'), blank=True, null=True, db_index=True ) objects = UserQuerySet.as_manager() class UserAccount(models.Model): user = models.ForeignKey( to='custom_auth.User', on_delete=models.CASCADE) account = models.ForeignKey( to='billing.Account', blank=True, null=True, on_delete=models.CASCADE) deleted = models.DateTimeField( verbose_name=_('Deleted at'), blank=True, null=True, db_index=True ) class Account(models.Model): _users = models.ManyToManyField('custom_auth.User', blank=True) User Manager class UserQuerySet(models.QuerySet): def prefetch_accounts_for_api(self, request): accounts_qs = Account.objects.all() user_account_qs = UserAccount.objects.filter( user=request.user, account_id=OuterRef('pk'), deleted__isnull=True )[:1] accounts_qs = accounts_qs.filter( useraccount=user_account_qs ) return self.prefetch_related(Prefetch( 'accounts', queryset=accounts_qs, to_attr='enabled_accounts' )) The problem is that when there are two rows in useraccount table (1 deleted and 1 not deleted) and i execute the query: User.objects.all().prefetch_accounts_for_api(request) User have duplicate of not deleted account relation in enabled_accounts attribute. How can i get only one actual account in enabled_accounts? Using PostgreSQL and Django 3.1.7 -
typerror at sign,sign() got an unexpected error 'name'
Photo of errorviews.py error is showing on line 40 and raised during homes.views.signurls.py models.pysettings.py sign.htmlFUll sign.html My admin is showing correctly that I have successfully but my sign in details are not able to reach it. I even tried removing name then the error was showing in password.I searched every single possible outcome on overstack to correct the problem.I cant understand what is going on.pls help me I was making a website and i just want details of my signin from website to go to my admin page my admin page is working completey fine i m just not abled to connect then properly -
How can python generate Dorpbox auth tokens after expire?
In my python website, I added dropbox refresh token, App key and Secret key. And in settings.py file I generate access token from these details. Now, my question is that how it will get new auth token after refresh token after expire it . Settings.py loads only one time when build is done and project starts. after expire token, it giving errors. -
how to handle concurrency of bookmark system in django?
I tried to implement bookmark system for product, when users click bookmark button, it will be recorded in his bookmark table, and update bookmark count field in Product Model. However I faced DB Lock when there is too many request at the same time. Also, I realized that when users add or delete bookmark at the same time, there will be concurency issues like, users can not read Product Information or Bookmark count or DB Lock.. How to handle concurrency in my situation? I know the exclusive lock but it will lower the performance.. please help me.. here are my codes class Bookmark(models.Model): _id = models.AutoField(primary_key=True, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='bookmark_user') def __str__(self): return str(self.user) class BookmarkItems(models.Model): _id = models.AutoField(primary_key=True, editable=False) user = models.CharField(max_length=255, null=True, blank=True) image = models.CharField(max_length=255, null=True, blank=True) bookmark = models.ForeignKey(Bookmark, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def image_preview(self): if self.image: return mark_safe('<img src="{0}" width="75" height="75" />'.format(self.image)) else: return '(No image)' def __str__(self): return str(self.product) @api_view(['POST']) @permission_classes([IsAuthenticated]) def addBookmark(request): user = request.user user_id = request.data['user'] product_id = request.data['product_id'] image = request.data['image'] product = Product.objects.get(_id=product_id) with transaction.atomic(): bookmark = Bookmark.objects.get_or_create(user=user) Product.objects.filter(_id=product_id).update( bookmark_count = F('bookmark_count') + 1 ) BookmarkItems.objects.create( user = user_id, image = image, bookmark=bookmark[0], … -
PyCharm - Auto-reloading Django dev server after template changes
How to make my PyCharm to reload Django dev server after i make changes in templates? It reloads on save on every other changes but not for template changes. server is starting by docker compose up We are using Django 3.2.16 entrypoint.sh: exec gunicorn app.wsgi:application --config gunicorn.py --reload settings.py [...] 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", "app.context_processors.get_version", "app.context_processors.get_env", ] }, } ] [...] -
Django static files are not found inside docker container
I am building a Django app with Docker. I run the command collectstatic in my entrypoint when database is ready. When I check my container, the /static/ folder is empty. Thus, Nginx cannot load the static files. # settings.py STATIC_URL = '/static/' STATIC_ROOT = '/static/' Here is my docker-compose file version: "3.9" services: db: image: postgis/postgis:14-3.3 container_name: db volumes: - ./data/db:/var/lib/postgresql/data env_file: - prod.env backend: container_name: backend build: dockerfile: ./django/Dockerfile command: gunicorn api.wsgi:application --bind 0.0.0.0:8000 volumes: - static:/usr/src/app/static ports: - "8000:8000" env_file: - prod.env depends_on: - db nginx: container_name: nginx build: dockerfile: ./nginx/Dockerfile volumes: - static:/usr/src/app/static ports: - "80:80" depends_on: - backend restart: always redis: container_name: redis restart: unless-stopped image: redis:alpine expose: - 6379 worker: container_name: worker build: dockerfile: ./django/Dockerfile command: celery -A api worker -l INFO volumes: - static:/usr/src/app/static env_file: - prod.env depends_on: - db - backend - redis volumes: static: My Nginx configuration: upstream api { server backend:8000; } server { listen 80; location / { proxy_pass http://api; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /usr/src/app/static/; } } backend Dockerfile: # syntax=docker/dockerfile:1 FROM python:3 WORKDIR /usr/src/app RUN apt-get update RUN apt-get install -y libgdal-dev gdal-bin netcat ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 COPY /django/requirements.txt … -
I want the number of unread messages to be displayed next to the menu in django admin panel
i need show number unread messages to be displayed next to the menu in django admin panel or show new user added site like this -
boto3 list items of s3 bucket and give path
I need to list all the items in my media/uploads/ folder on my s3 bucket. I've tried several answers from similar questions but was unable to implement the code snippets. I'm confused how to set up the boto3 connection and so far did not get a list. I work with django. In the end I need a list of the latest items. But getting a list of all the items in that folder would already help a lot. Here is my storage system: settings.py STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" AWS_STORAGE_BUCKET_NAME = "feedingcycle" AWS_S3_REGION_NAME = "eu-central-1" AWS_ACCESS_KEY_ID = "xxxx" AWS_SECRET_ACCESS_KEY = "xxxx" AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" import boto3 bucket_name = AWS_STORAGE_BUCKET_NAME def keys(bucket_name, prefix='/', delimiter='/'): prefix = prefix.lstrip(delimiter) bucket = boto3.resource('s3').Bucket(bucket_name) return (_.key for _ in bucket.objects.filter(Prefix=prefix)), print(keys) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" MEDIAFILES_FOLDER = "media" DEFAULT_FILE_STORAGE = "custom_storages.MediaFileStorage" The def keys is not working in there. I also don't get any error messages... Can I set up the whole thing also in my settings or do I have to make a new .py or model for that? Best wishes, Amber -
expected token 'end of statement block', got '='
I am trying to assign value to a dictionary in Jinja2 and its not working properly and showing error. expected token 'end of statement block', got '=' My Code: {% set sequence = ['a1', 'b1']%} {% set dic = {} %} {% for filter in search_result.filters %} {% for seq_key in sequence %} {% if seq_key == filter.key %} {# here i wish to create a dictionary where key= seq_key and value = filter_object#} {% do dic[seq_key]=filter %} {% endif %} {% endfor %} {% endfor %} -
Filter nested serializer model field (exclude particular field)
I am new to Django and I am trying to exclude a model field in nested serializer. modals.py class Blog(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=30) class Comment(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name="comment") comment_bdy = models.CharField(max_length=30) completed = models.BooleanField(default=False) serializers.py class BlogCommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ("id", "comment_body") class BlogSerializer(serializers.ModelSerializer): comment = BlogCommentSerializer(many=True) class Meta: model = ("id", "title", "description", "comment",) I am trying to exclude comment which have completed=True . I have tried many times like :- class BlogCommentSerializer(serializers.ModelSerializer): def to_representation(self, data): data = data.filter(completed=False) return super(BlogCommentSerializer, self).to_representation(data) But It showing AttributeError: 'CommentReply' object has no attribute 'filter' then I tried using class BlogSerializer(serializers.ModelSerializer): def get_comment(self, instance): comment_instance = instance.comment_set.exclude(completed=True) return BlogSerializer(comment_instance , many=True).data It also didn't work. What I am trying to do I am trying to exclude comments which are completed=True Any help would be much Appreciated. -
How can I merge different Db Models into one?
I have an old Django Project, which I started when I was a beginner. So far it worked but, due to some code refactoring I would like to do, I would like to change the original database models. Basically, I originally made many different models, each one for a user type. old models: class CustomUser(AbstractUser): user_type_data = ( ('admin', 'Admin'), ('instructor', 'Instructor'), ('student', 'Student'), ('renter', 'Renter'), ) user_type = models.CharField( max_length=20, choices=user_type_data, default=1) class Admin(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) date_of_birth = models.DateField(null=True, blank=True) fiscal_code = models.CharField(max_length=50, null=True, blank=True) phone = models.CharField(max_length=50, null=True, blank=True) picture = models.ImageField( blank=True, null=True, default='default.png') address = models.CharField(max_length=100, blank=True, null=True) cap = models.CharField(max_length=10, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) province = models.CharField( max_length=100, choices=PROVINCE_CHOICES, blank=True, null=True) country = CountryField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) def __str__(self): return self.user.username class Meta: ordering = ['last_name'] class Instructor(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) date_of_birth = models.DateField(null=True, blank=True) fiscal_code = models.CharField(max_length=50, null=True, blank=True) phone = models.CharField(max_length=50, null=True, blank=True) picture = models.ImageField( blank=True, null=True, default='default.png') address = models.CharField(max_length=100, null=True, blank=True) cap = models.CharField(max_length=10, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) province = models.CharField( max_length=100, … -
How to upload a file on click of a button in Django?
I have a requirement to upload a zip file on click of an upload/save button. Then when the user clicks on run button the uploaded file should get processed. I have created a basic form and could write code for uploading a file on click of submit as shown in below if request.method=='POST': upload_request=UploadFile() upload_request.file=request.FILES['file_upload'] upload_request.save() Template: <form method="post" enctype="multipart/form-data"> {% csrf_token%} <input type="file" required name="file_upload" id="choose_upload_file" value="" accept=".zip,.rar,.7z,.gz,"></br> <input type="submit" class="btn btn-secondary btn-block" value="upload" id="file_upload1"> </form> But How to have a save functionality (File should be uploaded) before submitting the form? I am new to Django, Please give me some insights. -
how to create a qr-code an sone of one of the fields based on the other when creating an object?
I want to creato objects through admin-pannel Django, I enter a value for a parameter and I want a qr code to be generated based on this value, my code: class People(models.Model): name = models.CharField(max_length=500, unique=True) qr_code = models.ImageField(upload_to="img/qr_codes/", verbose_name="QR-code", null = True) def save(self, *args, **kwargs): qr = qrcode.QRCode(version=2, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=1) qr.add_data(self.name) qr.make(fit=True) qr.make_image().save(f'img/qr_codes/{self.name}.png' self.qr_code = self.name+'.png' super().save(*args, **kwargs) This code return error [Errno 2] No such file or directory: 'img/qr_codes/somename.png' Im trying to use signal @receive but it isn't help for me -
How to use "Prefetch()" with "filter()" to reduce `SELECT` queries to iterate 3 or more models?
I have Country, State and City models which are chained by foreign keys as shown below: class Country(models.Model): name = models.CharField(max_length=20) class State(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=20) class City(models.Model): state = models.ForeignKey(State, on_delete=models.CASCADE) name = models.CharField(max_length=20) Then, when I iterate Country, State and City models with prefetch_related() and all() as shown below: # Here # Here for country_obj in Country.objects.prefetch_related("state_set__city_set").all(): for state_obj in country_obj.state_set.all(): # Here for city_obj in state_obj.city_set.all(): # Here print(country_obj, state_obj, city_obj) Then, 3 SELECT queries are run as shown below. *I use PostgreSQL and these below are the query logs of PostgreSQL and you can see this answer explaining how to enable and disable the query logs on PostgreSQL: But, when I iterate with filter() instead of all() as shown below: # Here for country_obj in Country.objects.prefetch_related("state_set__city_set").filter(): for state_obj in country_obj.state_set.filter(): # Here for city_obj in state_obj.city_set.filter(): # Here print(country_obj, state_obj, city_obj) Then, 8 SELECT queries are run as shown below instead of 3 SELECT queries: So, I use Prefetch() with filter() to reduce 8 SELECT queries to 3 SELECT queries as shown below: for obj in Country.objects.prefetch_related( Prefetch('state_set__city_set', # Here queryset=State.objects.filter(), to_attr='result' ), ).filter(): print(obj.result) But, the error below occurs: django.core.exceptions.FieldError: Cannot … -
Is it possible to user this code like the first one instead of second?
def create_new(request): if request.method == 'POST': form = ArticleForm(request.POST) form.id_author = request.user.id if form.is_valid(): form.save() return redirect('home') return render(request, 'main/create_new.html') def create_new(request): if request.method == 'POST': form = ArticleForm(request.POST) if form.is_valid(): article = form.save(commit=False) article.author = request.user article.save() return redirect('home') return render(request, 'main/create_new.html') Is it possible to change the 2nd code into the first code?? it shows some kind of error -
Django Admin: Prevent initial value from changing
I currently have: def formfield_for_dbfield(self, db_field, request, obj=None, **kwargs): if db_field.name == "username": initial_username = obj.username if obj else generate_patient_number() kwargs["initial"] = initial_username kwargs["disabled"] = True kwargs[ "help_text" ] = "<span style='color: red;'>Number might change. Please look at banner once saved</span>" return super().formfield_for_dbfield(db_field, request, **kwargs) However, once a new instance is created, the value that was displayed initially changes. Is there a way to prevent this? -
How to resolve "Exception while resolving variable 'name' in template 'unknown'." error thrown while logging API calls?
My Django logging config: def get_config(log_dir, level="INFO"): return { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': "[%(asctime)s] %(levelname)s [%(name)s: %(funcName)s: %(lineno)s] %(message)s", 'datefmt': "%Y-%m-%dT%H:%M:%S%z" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'null': { 'level': level, 'class': 'logging.NullHandler', }, 'console': { 'level': level, 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'django_log_file': { 'level': level, 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(log_dir, 'django.log'), 'maxBytes': 16777216, # 16megabytes 'formatter': 'verbose' }, 'django_errors_file': { 'level': 'ERROR', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(log_dir, 'django.errors.log'), 'maxBytes': 16777216, # 16megabytes 'formatter': 'verbose' }, 'db_log_file': { 'level': level, 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(log_dir, 'dbs.log'), 'maxBytes': 16777216, # 16megabytes 'formatter': 'verbose' }, 'apps_log_file': { 'level': level, 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(log_dir, 'apps.log'), 'maxBytes': 16777216, # 16megabytes 'formatter': 'verbose' }, 'myapp_ui_log_file': { 'level': level, 'class': 'logging.handlers.TimedRotatingFileHandler', 'when': 'midnight', 'filename': os.path.join(log_dir, 'myapp_ui.log'), 'interval': 1, 'backupCount': 7, 'formatter': 'verbose', }, 'myapp_apis_log_file': { 'level': level, 'class': 'logging.handlers.TimedRotatingFileHandler', 'when': 'midnight', 'filename': os.path.join(log_dir, 'myapp_apis.log'), 'interval': 1, 'backupCount': 7, 'formatter': 'verbose', } }, 'loggers': { 'django': { 'handlers': ['console', 'django_log_file', 'django_errors_file'], 'level': level, 'propagate': False, }, 'django.db.backends': { 'handlers': ['console', 'db_log_file'], 'level': level, 'propagate': False, }, '': { 'handlers': ['console', 'apps_log_file'], 'level': level, 'propagate': True, }, 'myapp_ui': { 'handlers': ['console', 'myapp_ui_log_file'], 'level': level, 'propagate': True, }, 'api1': { 'handlers': ['console', … -
Django Database transaction rollback in Loop
User may import a excel and I want to check if the data are correct. # Excel Data | id | item | qty | |:---- |:------:| -----:| | 1 | item A | 10 | | 2 | item B | 20 | | 3 | item C | 30 | | 4 | item D | 40 | <-- For example, Not enough qty to minus (only have 1) | 5 | item E | 50 | # Database | id | item | qty | |:---- |:------:| -----:| | 1 | item A | 100 | | 2 | item B | 200 | | 3 | item C | 300 | | 4 | item D | 1 | <-- For example, Not enough qty to minus (Need 40) | 5 | item E | 500 | I need to check the Database is that item has qty to minus, if yes then save the changes, if not, then rollback all changed data in this excel data (rollback to before import this excel) and return errors details to user. def myFunction(self, request): try: error_details = [] with transaction.atomic(): for data in excal_data: result = checkIfVerify(data) # … -
I keep getting this "OperationalError at / (2002, "Can't connect to local server through socket '/run/mysqld/mysqld.sock' (2)")" after django deploy
I keep getting this "OperationalError at / (2002, "Can't connect to local server through socket '/run/mysqld/mysqld.sock' (2)")". I only turned DEBUG to True since to see what the error is and since I'm only the one currently accessing it. This is my first deployment of a django app. I've tried checking for the socket path, I can't find any folder called run. I think mysqld is in C:/Program Files/MySQL/MySQL Server 8.0/bin but when i tried setting C:\Program Files/MySQL/MySQL Server 8.0/bin/mysqld.mock it as my socket it didn't work either. I'd really appreciate the help -
How to use Exception in python?
I wrote code below. def get(self, request): ... try: ... ... food = Food.objects.get(food_id="red") if food: data = { "name" : food.name, } res.append(data) return JsonResponse({"success": res}, status=200) except Exception as e: return JsonResponse({"failed": e}, status=403) My intention is, I would like to go to exception and get 403 if there is no food. However, in this case, if there is no 'food' data, a 500 error (DoesNotExist) occurs. Why do I get this error? Am I misunderstanding the concept of exception? -
Django returns session id but doesn't authenticate user
I have the following code that sends requests to check JWT token, then authorize user and return authorized session with Access token, Refresh Token and Session ID. @csrf_exempt def new_login_view(request, *args, **kwargs): def convert_data(req): data = { "email": req.data['username'], "password": req.data['password'], } try: data["language"] = request.LANGUAGE_CODE except: data["language"] = request.POST.get('language', 'en') return data if request.user.is_authenticated and not request.META.get('HTTP_X_AVOID_COOKIES'): return HttpResponseRedirect(request.GET.get(KEY_NEXT, '/')) if request.method == 'POST': request_data = convert_data(request) # request to Accounts API to check if user exists response = send_service_request(EnumAuthUrls.sign_in.value, json_data=request_data, original_response=True) if isinstance(response, dict): return JsonResponse(response) if response.status_code == 200: tok_ac = response.headers.get(HEADER_ACCESS_KEY) tok_ref = response.headers.get(HEADER_REFRESH_KEY) # checking JWT token user = ApiAuthenticationBackend().authenticate(request, tok_ac) # creates session data = login_session(request, response, user) data['user_id'] = request.user.id data['account_id'] = request.user.profile.account_id data['balance'] = request.user.balance if request.META.get('HTTP_X_AVOID_COOKIES'): return JsonResponse(data) response = AuthResponse( data=data, ssid=request.session.session_key, access_token=tok_ac, refresh_token=tok_ref, ) return response else: return ErrorApiResponse(response.json()) service = urllib.parse.quote_plus(request.build_absolute_uri()) return HttpResponseRedirect(settings.ACCOUNTS_URL + f'login/?service={service}') Here's the code of login_session fucntion: def login_session(request: HttpRequest, response: HttpResponse, user): request.user = user request.session.create() base_data = response.json().get(KEY_DATA) return request.user.serialize(request, base_data, token=True) And here's the class AuthResponse that is eventually based on HttpResponse: class AuthResponse(SuccessResponse): def __init__(self, data={}, ssid='', access_token: str = '', refresh_token: str = '', **kwargs): super().__init__(data, **kwargs) if ssid: …