Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django channels unable to connect(find) websocket after docker-compose of project using redis
I have currently implemented websocket connections via django channels using a redis layer. I'm new to docker and not sure where I might have made a mistake. After the docker-compose up -d --build the "static files, media, database and gunicorn wsgi" all function, but redis won't connect. even though it is running in the background. Before trying to containerize the application with docker, it worked well with: python manage.py runserver with the following settings.py setction for the redis layer: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("0.0.0.0", 6379)], }, }, } and by calling a docker container for the redis layer: docker run -p 6379:6379 -d redis:5 But after the trying to containerize the entire application it was unable to find the websocket The new setup for the docker-compose is as follows: version: '3.10' services: web: container_name: web build: context: ./app dockerfile: Dockerfile command: bash -c "gunicorn core.wsgi:application --bind 0.0.0.0:8000" volumes: - ./app/:/usr/src/app/ - static_volume:/usr/src/app/staticfiles/ - media_volume:/usr/src/app/media/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db networks: - app_network redis: container_name: redis image: redis:5 ports: - 6379:6379 networks: - app_network restart: on-failure db: container_name: db image: postgres volumes: - postgres_data:/var/lib/postgresql/data/ environment: - ./.env.psql ports: - 5432:5432 networks: … -
Django pytest running many migrations after tests
I am running pytest-django with a legacy database that was not created by Django (e.g. all my models use managed=False). In production, everything is fine but in testing Django wants to apply a bunch of curious migrations. For testing, I have a pre-populated test database and I want my tests to commit changes to the database (because we have logic in db views and triggers that needs to get run). All that is working fine but afterwards a ton of migrations are run and it takes my test suite time from 1s to 70s. The migrations are overwhelmingly this type: ALTER TABLE [DeprecatedLegacyTable] CHECK CONSTRAINT [FK_dbo.DeprecatedLegacyTable_dbo.User_DeprecatedServiceId]. The tables aren't even in any models.py, so I guess Django is digging this up with inspectdb. I've looked around a bit and it seems this is a "feature" of Django but it is hurting my workflow. Is there any way to apply these migrations once and for all rather than replay them every test run? (I'm also pretty curious why these migrations are all being done after the tests themselves. Seems backwards.) -
Django can't find admin page
I'm building a blog app in Django and I wanted to access the build-in admin page. However, when I try to reach it, it keeps throwing a 404 error and I have no idea why. So, when I try to access http://127.0.0.1:8000/admin/ I get: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Using the URLconf defined in blog.urls, Django tried these URL patterns, in this order: [name='index'] posts [name='posts'] posts/<slug:slug> [name='post'] The current path, admin/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Note: The porject is called 'my_site' and the app is called 'blog' Some code snippets below: my_site/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')) ] blog/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('posts', views.posts, name='posts'), path('posts/<slug:slug>', views.post, name='post'), ] blog/views.py from django.shortcuts import render, get_object_or_404 from .models import Author, Post # Create your views here. def index(request): all_posts = Post.objects.all().order_by("-date") latest_posts = all_posts[:3] return render(request, "blog/index.html", { "posts": latest_posts }) def posts(request): return render(request, … -
How to build MS Access like form in Python?
How would you go about building a form like the one attached in Python and having each metric/cell being filled in? For example, I enter someone's name and the other fields would get filled in with data from various tables. It's currently built in Excel and it's calling the data from multiple tabs but I'd like to transition to Python. I have built the backend data portion of it in Jupyter Notebook using Pandas but now would like to build the shell so that the data will auto-populate in its designated cell/location once a given variable has been entered into an input field (like 'Name' in the example). Can I do this in Jupyter Notebook (preferred)? Would I have to learn/use Django, Flask or HTML? Any tips, suggestions, or examples that you've seen would be greatly appreciated! Form Example -
SyntaxError: invalid syntax After complete installation of Qiime1
Traceback (most recent call last): File "/home/raju/miniconda2/envs/qiime1/bin/beta_diversity.py", line 4, in import('pkg_resources').run_script('qiime==1.9.1', 'beta_diversity.py') File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/pkg_resources/init.py", line 666, in run_script self.require(requires)[0].run_script(script_name, ns) File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/pkg_resources/init.py", line 1462, in run_script exec(code, namespace, namespace) File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/qiime-1.9.1-py2.7.egg-info/scripts/beta_diversity.py", line 13, in from qiime.util import make_option, parse_command_line_parameters File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/qiime/util.py", line 49, in from skbio.util import remove_files, create_dir File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/skbio/init.py", line 15, in import skbio.io File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/skbio/io/init.py", line 309, in import_module('skbio.io.clustal') File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/skbio/io/clustal.py", line 123, in from skbio.alignment import Alignment File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/skbio/alignment/init.py", line 230, in from ._alignment import Alignment, SequenceCollection, StockholmAlignment File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/skbio/alignment/_alignment.py", line 21, in from skbio.stats.distance import DistanceMatrix File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/skbio/stats/distance/init.py", line 193, in from ._base import (DissimilarityMatrixError, DistanceMatrixError, File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/skbio/stats/distance/_base.py", line 17, in from IPython.core.pylabtools import print_figure File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/IPython/init.py", line 48, in from .core.application import Application File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/IPython/core/application.py", line 23, in from traitlets.config.application import Application, catch_config_error File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/traitlets/config/init.py", line 6, in from .application import * File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/traitlets/config/application.py", line 17, in from decorator import decorator File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/decorator.py", line 162 print('Error in generated code:', file=sys.stderr) ^ SyntaxError: invalid syntax -
Can we make video conference app using django
Is it possible to make a video conferencing app with similar functionalities as of gmeet and zoom, namely, audio and/or video calling, screen share using django or do we have to use express.js for it? -
how set validation for password in django==4
Im useing this view for set new password for user But the output below this is always printed password not valid view.py from django.shortcuts import redirect, render from django.contrib.auth import login, logout, authenticate from django.urls import reverse_lazy from django.contrib import messages import re from .models import Users def edit_password(request): password_cahnged = False PASSVALID = r"^a" error = None if request.method == "POST": password = request.POST.get("password") password1 = request.POST.get("password1") password2 = request.POST.get("password2") username = None if request.user.is_authenticated : username = request.user.username user = authenticate(request, username=username, password=password) if user is not None: print(PASSVALID) print(password1) print(str(password1)) if re.fullmatch(PASSVALID, str(password1)): if str(password1) == str(password2): userr = Users.objects.get(username=str(user),password=password) print(userr) password_cahnged = True else: error = "password not math" else: error = "password not valid" else: error = "password its wrong" else: return redirect("login") print(error) context = {"password_cahnged": password_cahnged ,"error":error} return render(request, "edit_password.html", context=context) If you also have a better solution for changing the password is welcome (except forms) -
Django Rest Framework: why is my api call much slower in production than dev?
I've a django app that's deployed on an ec2 instance with docker and nginx. An api call that takes 700ms on my local system takes 15s on the production server. Even with debug set to false, on my local machine the call returns within 600-800ms but on production it consistently takes 15-20s to return. What causes this difference in performance? How does the way django handles api calls in debug differ from prod? I already use select_related and prefetch wherever possible. What changes could I make to speed up the api calls on the prod env? -
Django UploadFile Form not working with init overload
class UploadFileForm(forms.ModelForm): ALLOWED_TYPES = ['pdf', 'dwg'] class Meta: model = Files100 fields = ['project', 'category', 'file'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) categories = Category.objects.values_list("name", flat=True).distinct() categories = categories.exclude(kuerzel="AAAAAA") self.fields['category'].queryset = categories.filter(level__gt=0).order_by("level", "name") ö {% load django_bootstrap5 %} <div class="col-sm-3 col-md-3 col-sm-3 col-lg-2"> {% if file_upload_form %} <form method='post' enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form file_upload_form %} {% bootstrap_button button_type="submit" content="Upload File" %} {% bootstrap_button button_type="reset" content="Cancel" %} </form> {%endif%} When I take the init it works totally fine. But with the init the upload is passed without errors but also without uploading the file. I need the init to reduce my queryset. Is there another way of doing this. With self in the init I get error. If I put the super at the bottom I get error as well. Please help. Thanx -
module 'urllib.request' has no attribute 'POST' [closed]
Soy nuevo en Django y estoy tratando de crear una aplicación web simple. Cree formulario para registrarse utilizando CustomUserCreationForm. Desafortunadamente, recibí el siguiente error. módulo 'django.http.request' no tiene atributo 'POST'. Me podran ayudar??? A continuación encontrará el código view.py: from asyncio.windows_events import NULL from email import message from http.client import OK from urllib import request from django.shortcuts import render, HttpResponse, redirect, get_object_or_404 from django.http import HttpResponseRedirect from .models import personas, remito, detalle_remito, recursos from .forms import formularionuevo, CustomUserCreationForm from django.contrib import messages from django.core.paginator import Paginator from django.http import Http404 from django.contrib.auth import authenticate, login def registro(resquest): form = CustomUserCreationForm() if resquest.method=="POST": formulario = CustomUserCreationForm(data=request.POST) if formulario.is_valid(): formulario.save() user= authenticate(username=formulario.cleaned_data("username"), password=formulario.cleaned_data("password1")) login(resquest, user) messages.success(request, "Te has registrado correctamente") return redirect(to="home") form=formulario return render(resquest,"registration/registro.html", {'formulario':form}) Registro.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> {% load static %} <!-- Bootstrap --> <link href="{% static 'RemitoTicapp/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <title> Registro de usuario</title> </head> <body> <div class="container"> <br> <br> <br> <div class="row"> <div class="col-12 col-md-6 offset-md-3"> <div class="card"> <div class="card-body"> <h2> Registro de usuario </h2> <hr> <form action="" method="POST"> {% csrf_token %} {% for field in formulario %} <label> {{ field.label }} :</label> {{ field }} <br … -
Redirect Page Login google
I see this tutorial about Google Authenticantion: TUTORIAL But my button of google: Redirect to a page that needs to click continue to redirect to the login page, but what I would like is that as soon as I click on the google login button, I will be redirected to the login page, without this intermediate page Below my settings -
How to get a field's value by joining multiple querysets in Django
I am trying to display images in a list based on certain conditions. To that end, I have been trying to create a queryset join of a set of models (as shown below): models.py class ModeOfTransport(models.Model): mode_of_transport = models.CharField(unique=True, max_length=4... class Route(models.Model): route_id = models.AutoField(primary_key=True) route_start = models.ForeignKey(City, related_name='route_start') route_end = models.ForeignKey(City, related_name='route_end') class RouteLeg(models.Model): route_leg_id = models.AutoField(primary_key=True) route_id = models.ForeignKey(Route, related_name='route_hdr') leg_start = models.ForeignKey(City, related_name='leg_start') leg_end = models.ForeignKey(City, related_name='leg_start') mode_of_tptn = models.ForeignKey(ModeOfTransport, related_name='route_tptn_mode') class ImageType(models.Model): image_type_id = models.CharField(primary_key=True, max_length=1) image_type = models.CharField(max_length=4) class RouteImage(models.Model): image_id = models.AutoField(primary_key=True) image_name = models.CharField(max_length=125) image_type = models.ForeignKey(ImageType) image_route = models.ImageField(upload_to='images/route_images/') From a list of existing routes (a generic listview), I am trying to create a further drilldown like this: views.py def graf_display_route(request, pk): if request.method == 'GET': route_grafiks = RouteLeg.objects.all().filter(route_id=pk) return render(request, 'route_grafiks.html', {'route_grafiks': route_grafiks}) Now in order to get to the image field (RouteImage.image_route), I tried the following to get the image_type and then the image itself: qs_mode_of_tptn = ImageType.objects.filter(image_type_id__in= route_graphics.values_list('mode_of_tptn', flat=True)) The result (on printing the list of resultant queryset) I can see in the terminal as: [<ImageType: ImageType object (2)>, <ImageType: ImageType object (3)>]> Next, using the queryset qs_mode_of_tptn when I use another qset, I get the image table fields … -
How do I test all of my app's urls in Django to make sure they require authentication?
I want to write a Django test that looks at all the urls in one particular app, and makes sure that hitting them without being authenticated redirects me to the login page. Something like: from django.test import TestCase from django.urls import reverse from my_app.urls import urlpatterns class AuthTest(TestCase): def _test_url(self, url): response = self.client.get(url) self.assertRedirects(response, expected_url=reverse("login_app:login")+ "?next=" + url) def test_auth(self): for url in urlpatterns.SOMETHING: with self.subTest(url=url): self._test_url(url) Is there a way to get the actual list of urls in each urlpattern for my app? And, related question: for those URLs that require a pk, is there a way to automatically use pk=1? My fixtures will make sure that pk=1 exists for all those urls. -
Reverse for 'edit_review' with arguments '('',)' not found. 1 pattern(s) error when editing comment
When i try to click on my edit comment button in product_detail i get this error and i cant figure out how to fix it. would really appreciate some help thanks in advance. error when clicking edit comment button below: Am only writing out the needed code not the full code if there is anything u need tell me and i add. views.py from django.shortcuts import render, redirect, reverse, get_object_or_404 from django.contrib import messages from django.contrib.auth.decorators import login_required from django.db.models import Q from django.db.models.functions import Lower from .models import Product, Category, Review from .forms import ProductForm, ReviewForm @login_required def edit_review(request, review_id): review = get_object_or_404(Review, pk=review_id) product = Product.objects.get(name=review.product) if request.method == 'POST': review_form = ReviewForm(request.POST or None, instance=review) if review_form.is_valid(): review_form.save() messages.success(request, 'Successfully updated Review!') return redirect(reverse('product_detail', args=[product.id])) else: messages.error(request, 'Failed to update product. Please ensure the form is valid.') else: review_form = ReviewForm(instance=review) messages.info(request, f'You are editing {edit_review}') template = 'products/edit_review.html' context = { 'review_form': review_form, 'Review': Review, } return render(request, template, context) Models.py class Review(models.Model): product = models.ForeignKey(Product, related_name='reviews', on_delete=models.CASCADE) rating = models.IntegerField(default=3) content = models.TextField() created_by = models.ForeignKey(User, related_name='reviews', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.product.name, self.created_by) forms.py from django import forms … -
.add() .set() on m2m reletion django not working as expected
I have some troubles with m2m relation in Django. I'm working on slqlite db local and mysql on production. Locally everything is working as I expected (with shell and admin panel). But I have issues on production. Relation Artwork-ArtCollection is defined in Artwork model: class Artwork(models.Model): ... art_collections = models.ManyToManyField("ArtCollection", related_name="artworks", blank=True) According to the https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_many/ Adding a second time to m2m relation is OK, it will not duplicate the relation: >>> a2.publications.add(p3) but when I run artwork = Artwork.objects.get(pk=1) art_collection = ArtCollection.object.get(pk=1) artwork.art_collections.add(art_collection) even when the relation already exists the .count() method returns count += 1 and I have duplicated relation (or multipled by 3, 4, 5 if I will countinue running .add(art_collection) In shell I can clear the relations only by .clear() method, can not use artwork.art_collections.set([art_collection]) When I try to delete art_collections ids on admin panel (I have raw_id_field) - nothing happens. Those are my methods on ArtworkAdmin def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) def save_related(self, request, form, formsets, change): super(ArtworkAdmin, self).save_related(request, form, formsets, change) what is interesting - form.cleaned_data['art_collections'] return qs with only one instance of ArtCollection - no matter if there are 5 when I clicked save button or 1 or … -
How Can I Automatically Create Profile For Guest User During PIN Activation
I am working on an Event Ticketing Application in Django where guest would need a Recharge PIN to be validated on the portal for booking or reserving a seat in an event they bought PIN for. And I also want these guests to be authenticated so I can be able to management Authorization on them too. In my Models I have a Profile Model where I am using signals to automatically create user profile upon Admin User Creation, and I also have three User Groups in the Create New User Form with Privileges assigned accordingly; Organizer, Staff and Guest are the groups. I have also developed a Django CreateUserForm class using UserCreationForm module in my forms.py where I have a Drop Down of all these group for the Admin to add Users (Registration Page is accessible by Admin only) using Admin dashboard. My problem is that I want each PIN that is Validated by Guest to be able to create his/her Profile immediately the PIN Validated using Signals but I don't know how to do it. I am confused with my CreateUserForm class since all the groups are listed in Drop down. Don't know how to use conditionals inside the … -
Django DecimalField min value validation error
I need a decimal field in my form with a minimal value of 0.20, maximal value of 20 with 2 decimal places as you can see in the code bellow. forms.DecimalField(min_value=0.20, max_value=20.00, max_digits=4, decimal_places=2, initial=1) The problem occures when you put 0.20 in, because you get a validation error: Ensure this value is greater than or equal to 0.20. I'm using python 3.10 and Django 4.0.4 -
Why is image serializer feild not returning link format
Is there any update on image field serializer? I was trying to server an image api to the frontend. My serializer is not returning image link instead its returning the path relative to the base dir of the django-project models.py def upload_to(instance, filename): return 'profiles/{filename}'.format(filename=filename) class Picture(models.Model): image = models.ImageField(upload_to=upload_to) serializer class PictureSerializer(serializers.ModelSerializer): class Meta: model = Picture fields = ['image'] **serializer.data result ** [ { "image": "/media/profiles/quiz-app-.jpg" }, { "image": "/media/profiles/coding2.jpg" }, { "image": "/media/profiles/dummy_2s9CyV8.jpg" } ] instead of the above result I want something like a link in return [ { "image": "http://127.0.0.1:8000/api/media/profiles/quiz-app-.jpg" }, { "image": "http://127.0.0.1:8000/api/media/profiles/coding2.jpg" }, { "image": "http://127.0.0.1:8000/api/media/profiles/dummy_2s9CyV8.jpg" } ] -
Calling viewset from another route
I use Django rest-framework which fetch the items from tables and return serialized json, when calling like this below localhost/api/mixs?id=12 Source code. class MixViewSet(viewsets.ModelViewSet): serializer_class = MixSerializer filter_backends = [django_filters.rest_framework.DjangoFilterBackend] filter_fields = ["id","user"] filterset_fields = ['id'] search_fields = ['id'] def list(self,request,*args,**kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(queryset, many=True) custom_data = { 'items': serializer.data } custom_data.update({ 'meta':{"api":"Mix"} }) return Response(custom_data) def get_queryset(self): queryset = Mix.objects.all() ids = self.request.query_params.get('ids') if ids is not None: id_arr = ids.split(',') if len(id_arr) > 0: queryset = queryset.filter(id__in=id_arr) u_key = self.request.query_params.get('u_key') if u_key is not None: queryset = queryset.filter(u_key=u_key) return queryset Now, I want to use this function from another method. For example def createMix(request): #do something and make Mix m = Mix(detail={},user=1) m.save() print(m.id) ### for example 13 #Now I want to do the equivalent thing #to `localhost/api/mixs?id=13` # returning the data id=13 When calling this url localhost/myapp/createsong The program do something and insert data in Mix table. then do the equivalent thing to localhost/api/mixs?id=13 Is it possible? Or my idea is correct? -
Why does command prompt throws" Syntax Error: Generator expression must be parenthesized " while creating a Django App named Authentication?
I am new to Django and was trying to make a Django project inside the virtualenv to learn but getting following error on python manage.py startapp Authentication: python manage.py startapp Authentication Traceback (most recent call last): File "C:\Users\Prompt\Desktop\Django\manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "D:\anaconda\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "D:\anaconda\lib\site-packages\django\core\management\__init__.py", line 337, in execute django.setup() File "D:\anaconda\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "D:\anaconda\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "D:\anaconda\lib\site-packages\django\apps\config.py", line 94, in create module = import_module(entry) File "D:\anaconda\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "D:\anaconda\lib\site-packages\django\contrib\admin\__init__.py", line 4, in <module> from django.contrib.admin.filters import ( File "D:\anaconda\lib\site-packages\django\contrib\admin\filters.py", line 10, in <module> from django.contrib.admin.options import IncorrectLookupParameters File "D:\anaconda\lib\site-packages\django\contrib\admin\options.py", line 12, in <module> from django.contrib.admin import helpers, widgets File "D:\anaconda\lib\site-packages\django\contrib\admin\widgets.py", line 151 '%s=%s' % (k, v) for k, v in params.items(), ^ SyntaxError: Generator expression must be parenthesized -
I want to set a limit for the rows only upto 5 rows which will get added from the django.models admin panel
I have a table in my models file and I want to design it such that there is a limit to only 5 rows in the table. When the limit is exceeded error has to show and input should not take.I am new to Django so if anyone had a suggestion on how to do this, it would be greatly appreciated! -
Import app model with multiple Django apps error ModuleNotFoundError: No module named 'apps'
So I have a problem importing a model from a different app in same Django project. My files are structured as follows: /project /apps __init__.py /app1 __init__.py models.py ... /non_app_dir __init__.py work.py ... /core __init.py settings.py urls.py wsgi.py ... manage.py In my settings.py, I have this: INSTALLED_APPS = [ ... 'apps.app1', 'apps.non_app_dir', ... ] Ok, so in my work.py (from non_app_dir), I try to import a model from models.py (from app1) like below: from apps.app1.models import MyModel def testModel(): test = MyModel.objects.all() print(test) but i get the following error ModuleNotFoundError: No module named 'apps' Any solutions to this? -
drf_yasg swagger_auto_schema move from views
In my project's views classes I use swagger_auto_schema decorator to customize swagger possible responses. My question is this: "Is this a way to move all these decorators from my class based views to other place like module or python file?". I'm asking this question because swagger_auto_schema decorators sometimes take up most of the code of my views, and it's getting hard to read them. example: class ArticleListCreateAPIView(ListCreateAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer def get_serializer_class(self): if self.request.method == "GET": return ArticleResponseSerializer return super().get_serializer_class() @swagger_auto_schema( responses={ status.HTTP_201_CREATED: openapi.Response( description="Successful article create", schema=ArticleResponseSerializer, ), status.HTTP_400_BAD_REQUEST: openapi.Response( description="Data serialization failed. Incorrect data.", schema=DetailResponseSerializer ), status.HTTP_409_CONFLICT: openapi.Response( description="Media-file is already bouned to some other model", schema=DetailResponseSerializer ) } ) def post(self, request, *args, **kwargs): ... Maybe I should stop using swagger_auto_schema and replace it by some other structures? -
How to use django-hijack from api
I have follow the django-hijack installation process but unfortunately the usage demonstration is using the django template. But like most current applications, my application uses Django Rest Framework and has a javascript application for the front end. I can't find a solution to impersonate an user from the front-end. I've tried to do a POST while logged in as an admin on /hijack/5 or /hijack/acquire/5 where 5is the ID of the user I want to impersonate but I got a 404 error on my POST. So my question is how to impersonate an user while an admin with Django when using a javascript front end application ? I'm open to other projects than django-hijack if this one is not compatible. -
javascript - fetching data from webserver only getting 'redirected' response from cors
So I managed to make my first api accessable locally. However when I try to fetch data like I would normally (url to phpscript to get data from db), I only get a Response telling me that I was successfully redirected. In wich way should I change my fetch function to make this work? script.js async function getTop10() { let url = 'http://192.168.2.131:81/stern'; try { let res = await fetch(url); console.log(res); return await res.json(); } catch (error) { console.log(error); } } getTop10(); Response Response {type: 'cors', url: 'http://192.168.2.131:81/stern/', redirected: true, status: 200, ok: true, …} body: (...) bodyUsed: true headers: Headers {} ok: true redirected: true status: 200 statusText: "OK" type: "cors" url: "http://192.168.2.131:81/stern/" [[Prototype]]: Response Sample dataset from the url [ [ "Nach", 20 ], [ "In", 16 ], [ "Sie", 15 ], [ "Die", 14 ], [ "So", 10 ], [ "Putin", 10 ], [ "Das", 9 ], [ "Ukraine", 9 ], [ "Deutschland", 9 ], [ "Der", 8 ] ]