Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM: How to filter on many-to-many relation without filtering related objects
I have some Django models like following: class Film: genre = models.ManyToManyField("Genre", blank=True) class Genre(TimeStampedModel): name = models.CharField(max_length=50, blank=False) slug = AutoSlugField(max_length=55, unique=True, populate_from="name") Now, I want to select all films which are associated with the genre "Theatre" and get a list of all their associated genres: In [1]: from apps.base.models import Film, Genre In [2]: qs = Film.objects.filter(genre__slug='theatre') In [3]: set(qs.values_list("genre__slug", flat=True)) Out[3]: {'theatre'} However, this is not the result that I want. Looking at the genres of the first film returned as part of the queryset, we can see more genres: In [4]: set(qs[0].genre.all().values_list("slug", flat=True)) Out[4]: {'dance', 'education', 'theatre', 'video-recording'} How can I efficiently filter the films to those associated with the genre "Theatre" and retrieve their associated genres? -
What is the best way to embed videos with Google amp-story player in django
Am currently working on an app that i would want to add google Amp-story player to embed videos, but somehow the google amp play wont render the video or images from the database but rather when i pass a link to the video source which is not from my data base it works. I have tried writing custom template tag and filter to handle the the images but still I find it a challenge to get it to work. Is there a possible way to go out this. {% load ampimage_tag %} <head> <script async src="https://cdn.ampproject.org/amp-story-player-v0.js" onload="initializePlayer()" ></script> <link href="https://cdn.ampproject.org/amp-story-player-v0.css" rel="stylesheet" type="text/css" /> <script> // JS let player; function events() { console.log( "iframes", document .querySelector("amp-story-player") .shadowRoot.querySelectorAll("iframe") ); player.addEventListener("storyEnd", (data) => console.log("storyEnd", data) ); player.addEventListener("amp-story-player-close", () => { console.log("Close button clicked"); }); } function initializePlayer() { player = window.document.querySelector("amp-story-player"); if (player.isReady) { // Player loaded. Run e.g. animation. console.log("isready"); events(); return; } player.addEventListener("ready", () => { // Player loaded. Run e.g. animation. console.log("ready"); events(); }); } function show(story) { player.show(story); } function nextStory() { player.go(1); } </script> </head> <body> <button onclick="console.log( 'iframes', document.querySelectorAll('amp-story-player iframe') );" > add story </button> <button onclick="show('https://merci-handy.my.join-stories.com/collection-la-bouche-avis-kQoT9uov/',false)" > First story </button> <button onclick="show('https://webstoriesinteractivity-beta.web.app/arts-quizzes.html',false)" > Second story </button> … -
Integrate OAuth 2.0 prompt property with Django MS Graph
I'm using Microsoft Graph to manage Azure authentication on my django app. The thing is that it automatically logs the user if he previously used an account in his browser, so I want to use the property "prompt=select_account" from OAuth 2.0 but didn't find any doc on how to integrate this. Currently the app works with a slightly modified version of MS Graph tutorial with the following yml settings file: app_id: "xxxxxx" app_secret: "xxxxxx" redirect: "http://localhost/callback" scopes: - user.read authority: "https://login.microsoftonline.com/xxxx-xxxx-xxxx-xxxx-xxx" I tried to add it as an option in this yml file : prompt: "select_account" Also tried in the authority url : authority: "https://login.microsoftonline.com/xxxx-xxxx-xxxx-xxxx-xxx&prompt=select_account" Any link to follow or direct answer would be greatly appreciated, Thanks ! -
How to solve problem with admin panel when using gunicorn
How I can solve problem with django admin panel when using gunicorn. My admin panel doesn't support static files Here what i have in terminal web_1 | Not Found: /static/admin/css/base.css web_1 | Not Found: /static/admin/css/nav_sidebar.css web_1 | Not Found: /static/admin/js/nav_sidebar.js web_1 | Not Found: /static/admin/css/dashboard.css web_1 | Not Found: /static/admin/css/responsive.css web_1 | Not Found: /static/admin/css/fonts.css web_1 | Not Found: /static/admin/css/base.css web_1 | Not Found: /static/admin/css/nav_sidebar.css web_1 | Not Found: /static/admin/css/dashboard.css web_1 | Not Found: /static/admin/css/responsive.css web_1 | Not Found: /static/admin/js/nav_sidebar.js web_1 | Not Found: /static/admin/css/base.css web_1 | Not Found: /static/admin/css/nav_sidebar.css web_1 | Not Found: /static/admin/css/dashboard.css web_1 | Not Found: /static/admin/css/responsive.css web_1 | Not Found: /static/admin/js/nav_sidebar.js web_1 | Not Found: /static/admin/css/base.css web_1 | Not Found: /static/admin/css/nav_sidebar.css web_1 | Not Found: /static/admin/css/dashboard.css web_1 | Not Found: /static/admin/css/responsive.css web_1 | Not Found: /static/admin/js/nav_sidebar.js web_1 | Not Found: /static/admin/css/base.css web_1 | Not Found: /static/admin/css/nav_sidebar.css web_1 | Not Found: /static/admin/css/dashboard.css web_1 | Not Found: /static/admin/css/responsive.css web_1 | Not Found: /static/admin/js/nav_sidebar.js -
Django Rest Api - Password does not change
I use the built-in methods to change the Password of a user via a POST from the frontend, but the password does not update when calling the view. I do get an http 200 back though. Any advice ? views.py from rest_framework import status from rest_framework import generics from rest_framework.response import Response from django.contrib.auth.models import User from .serializers import ChangePasswordSerializer from rest_framework.permissions import IsAuthenticated class ChangePasswordView(generics.UpdateAPIView): serializer_class = ChangePasswordSerializer model = User permission_classes = (IsAuthenticated,) def get_object(self, queryset=None): obj = self.request.user return obj def update(self, request, *args, **kwargs): self.object = self.get_object() serializer = self.get_serializer(data=request.data) if serializer.is_valid(): # Check old password if not self.object.check_password(serializer.data.get("old_password")): return Response({"old_password": ["Wrong password."]}, status=status.HTTP_400_BAD_REQUEST) # set_password also hashes the password that the user will get self.object.set_password(serializer.data.get("new_password")) self.object.save() response = { 'status': 'success', 'code': status.HTTP_200_OK, 'message': 'Password updated successfully', 'data': [] } return Response(response) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # Create your views here. serializers.py from rest_framework import serializers from django.contrib.auth.models import User class ChangePasswordSerializer(serializers.Serializer): model = User old_password = serializers.CharField(required = True) new_password = serializers.CharField(required = True) -
"post_save_user_model_receiver" is not defined
"post_save_user_model_receiver" is not defined I'm un able to use post_save_user_model_receiver do help me to solve the below problem -
Guys, there is a problem with template. My task is create a fliter in dropdown menu and last problem in templates
My models: class Category(ModelWithSlugMixin): class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' slugifying_field_name = 'title' title = models.CharField(verbose_name='Наименование', null=True, max_length=255) slug = models.SlugField(verbose_name='Slug', unique=True, null=True, blank=True, unique_for_date='publish') publish = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('article:category', kwargs={'category_slug': self.slug}) class Article(ModelWithSlugMixin): class Meta: verbose_name = 'Статья' verbose_name_plural = 'Статьи' slugifying_field_name = 'title' category = models.ForeignKey(Category, on_delete=models.SET_NULL, related_name='category', blank=False, null=True) title = models.CharField(verbose_name='Заголовок', max_length=255, null=True) slug = models.SlugField(verbose_name='Slug', unique=True, null=True, blank=True, unique_for_date='publish') text = RichTextUploadingField(verbose_name='Текст', null=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='articles') publish = models.DateTimeField(default=timezone.now) created_at = models.DateField(auto_now_add=True) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('article:article-detail', kwargs={'slug': self.slug} My view: class ArticleView(ListView): model = Article template_name = 'pages/analysis.html' context_object_name = 'articles' queryset = Article.objects.all() def get_context_data(self, **kwargs): context = super(ArticleView, self).get_context_data(**kwargs) # context['category'] = Category.objects.all() context['article_image'] = Photo.objects.all() context['article_pictures'] = Collage.objects.all() context['article_videos'] = Video.objects.all() return context class ArticleCategoryView(ListView): model = Article template_name = 'pages/analysis.html' context_object_name = 'articles' def get_queryset(self): return Article.objects.filter(category__slug=self.kwargs['category_slug']) def get_context_data(self, **kwargs): context = super(ArticleCategoryView, self).get_context_data(**kwargs) context['cat_selected'] = context['articles'][0].category_id return context Mu url: path('category/<slug:category_slug>/', ArticleCategoryView.as_view(), name='category'), And finally my template structure: <h3 class="widget-title">Categories</h3> <div class="form-group select-group"> <label for="category" class="sr-only">Select Category</label> <select id="category" name="category" class="choice empty form-control"> <option value="" disabled="" selected="" data-default="">Выбери категорию </option> <option>First category</option> <option>Second category</option> <option>Third category</option> … -
query set in django
i really need help with this: I have 3 models say User,Item and Comment where User is a foreign key in Item and Item is a foreign key in Comment. i want to get all comment belonging to a particular user in my view, how do i achieve it. bellow is are my model class User(models.Model): name= models.CharField(max_length=200,null=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Item(models.Model): user = models.ForeignKey(User, on_delete=CASCADE) name= models.CharField(max_length=200,null=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Comment(models.Model): user = models.ForeignKey(Item, on_delete=CASCADE) name= models.CharField(max_length=200,null=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name -
Why the login_requried decorator doesn't work after I login to an account?
Working on a project using Django 3.2, I have been added new features to the project by adding a login/register page for the user. To do that, I used which I used this library provided by Django from django.contrib.auth.models import User, and as well in the views I used from django.contrib.auth import authenticate, login, logout library. After I finished the login/register successfully I decided to do the authenticate the home page for the reason that the user without an account can't have access to the home page. To do that I used the decorators from django.contrib.auth.decorators import login_required, and I used it on every view that I want to authenticate for the unregistered user. To understand it better will show the code below: views.py from django.http.response import HttpResponse from django.shortcuts import render, redirect from django.utils import timezone from django.db.models import Count from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.contrib import messages from .models import * from .models import __str__ from .forms import CreateUserForm # Create your views here. @login_required(login_url='login/') def home(request): count_item = todo.objects.count() all_items = todo.objects.all().order_by("created") context = {'all_items': all_items, 'count_item':count_item} return render(request, 'html/home.html', context) @login_required(login_url='login/') def … -
django-cloudinary-storage must supply api_key
I'm using django-3.2.6, django-cloudinary-storage-0.3.0 and python-3.9.7 earlier the cloudinary was detecting API_KEY, but I don't know what happened now. settings.py DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' CLOUDINARY_STORAGE = { 'CLOUD_NAME': os.environ.get("CLOUD_NAME"), 'API_KEY' : os.environ.get("CLOUDINARY_API_KEY"), 'API_SECRET': os.environ.get("CLOUDINARY_API_SECRET"), } I tried to print the values i passed on CLOUDINARY_STORAGE, and it loads all .env succesfully, but django_cloudinary_storage isn't detecting these variables logs Environment: Request Method: POST Request URL: http://localhost:8000/admin/api/news/add/ Django Version: 3.2.6 Python Version: 3.9.7 Installed Applications: ['whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'api.accounts', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'django_filters', 'taggit', 'drf_yasg2', 'corsheaders', 'cloudinary', 'cloudinary_storage'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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'] Traceback (most recent call last): File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/contrib/admin/options.py", line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 232, in inner return view(request, *args, **kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1657, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/contrib/admin/options.py", … -
i am getting a hard time to impement two factor authentication using the totp ,i want the user after normal login to be prompted the token login page
the function bellow is the one i was trying to implement the logic behind the two factor authentication ''' def login_view(request): if request.user.is_authenticated: return redirect('/dashboard') if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] cache.set('email',email) fact = User.objects.filter(email=email).values('username') username = fact[0]['username'] username = username.encode(encoding='utf-8') password = password.encode(encoding='utf-8) username = username.strip(b"b'") print(username) print(str(password)) user = authenticate(request, username=username, password=password) cache.set('user',user) if user is None: context = {'error':'incorrect username or password'} return render(request, 'index.html' , context) print(username) is_enrolled = enrolled(request) if not is_enrolled.json(): login(request, user) return redirect('/dashboard') return render(request, 'tokenlogin.html') return render(request, 'index.html') ''' also the function below i wrote to check if the user has enrolled for two factor authentication ''' def isenrolled(request): email = request.user.email res = requests.post( 'http://0.0.0.0:8000/api/users/email/', data={ 'account_name': email, }, headers={ 'Authorization': 'Bearer {0}'.format(ACCESS_TOKEN), 'Content-Type': 'application/x-www-form-urlencoded' } ) return res #This function to check MFA enabled when user before login def enrolled(request): email = request.POST['email'] res = requests.post( 'http://0.0.0.0:8000/api/users/email/', data={ 'account_name': email, }, headers={ 'Authorization': 'Bearer {0}'.format(ACCESS_TOKEN), 'Content-Type': 'application/x-www-form-urlencoded' } ) ''' the error am getting is due to username and password being of type byte instead of string ,so if there is the way of converting them into string ''' Quit the server with CONTROL-C. b'jdv' … -
Django - Serializer throwing "Invalid pk - object does not exist" when setting ManyToMany attribute where foreign keyed object does exist
So below I have some code that tests the functionality where someone creates a post and that post has a hash_tag which is "#video" in this case. The code takes the Post body and uses regex to find any word that starts with "#". If it does then it creates or gets that HashTag from the HashTag table. Then sets that list of HashTag to the hash_tags attribute under Post. For some reason the CreatePostSerializer serializer is throwing an exception that doesn't make sense. The serializer is throwing the exception ValidationError({'hash_tags': [ErrorDetail(string='Invalid pk "[\'video\']" - object does not exist.', code='does_not_exist')]}). The reason this doesn't make sense is because when I debug and set a breakpoint right after except Exception as e under views.py this is what I get >>>e ValidationError({'hash_tags': [ErrorDetail(string='Invalid pk "[\'video\']" - object does not exist.', code='does_not_exist')]}) >>>HashTag.objects.get(pk='video') <HashTag: HashTag object (video)> >>>request.data['hash_tags'] ['video'] So the >>> represents what I input into the debugger. I'm essentially stopped at the line return Response... and we can see e is the ValidationError I mentioned, but we can see that the object it claims doesn't exist does indeed exist. Why is the serializer throwing a "ValidationError - object does not exist" … -
Django Inner join Parent model with child model
I have this tables class OtherTable(models.Model): #some attributes class Parent(models.Model): #some attributes class Child1(models.Model): group = models.ForeignKey(Parent) #more attributes class Child2(models.Model): group = models.ForeignKey(Parent) #more attributes class Child3(models.Model): group = models.ForeignKey(Parent) other_table = models.ForeignKey(OtherTable) #more attributes how can join all tables? I want to perform the equivalent SQL query using django's ORM: select * from parent inner join child1 on parent.id = child1.parent_id inner join child2 on parent.id = child2.parent_id inner join child3 on parent.id = child3.parent_id inner join othertable on other.id = child3.other_table_id -
How to filter query by multiple values using DRF, djagno-filters and HyperlinkedIdentityField values
Main target is to get query set based on multiple values in query. Business logic is to get all contracts for multiple drivers. Example: request url: /api/contract/?driver=http://localhost:8000/api/driver/1,http://localhost:8000/api/driver/2 Response should be all contracts for these two drivers. Driver Serializer: class DriverSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='driver-detail', read_only=True ) class Meta: model = Driver fields = [ 'url', 'id', 'first_name', 'last_name', ] Contract serializer: class ContractSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='contract-detail', read_only=True ) driver = serializers.StringRelatedField(many=False) class Meta: model = Contract fields = [ 'url', 'id', 'contract_detail_fields', 'driver', ] Contract View class ContractViewSet(viewsets.ModelViewSet): serializer_class = serializers.ContractSerializer queryset = Contract.objects.all() permission_classes = (IsAuthenticated,) filter_backends = [DjangoFilterBackend] filterset_class = ContractFilter ContractFilter: class ContractFilter(FilterSet): driver = CustomHyperlinkedIdentityFilterList('driver') What I have tried is to make custom filterField based on answer by Sherpa class CustomHyperlinkedIdentityFilterList(django_filters.BaseCSVFilter, django_filters.CharFilter): def filter(self, qs, value): values = value or [] for value in values: qs = super(CustomHyperlinkedIdentityFilterList, self).filter(qs, value) return qs Answer is ValueError: Field 'id' expected a number but got 'http://localhost:8000/api/drivers/driver/3/'. Then I am trying to modify to filter by id not urlField and changing this line qs = super(CustomHyperlinkedIdentityFilterList, self).filter(qs, value) to this: qs = super(CustomHyperlinkedIdentityFilterList, self).filter(qs, get_id_from_url(value)) where get_id_from_url is: def get_id_from_url(url): return int(resolve(urlparse(unquote(url)).path).kwargs.get('pk')) But it return me only contracts for … -
Speed up order_by and pagination in Django
Currently I have this result: That's not bad (I guess), but I'm wondering if I can speed things up a little bit. I've looked at penultimate query and don't really know how to speed it up, I guess I should get rid off join, but don't know how: I'm already using prefetch_related in my viewset, my viewset is: class GameViewSet(viewsets.ModelViewSet): queryset = Game.objects.prefetch_related( "timestamp", "fighters", "score", "coefs", "rounds", "rounds_view", "rounds_view_f", "finishes", "rounds_time", "round_time", "time_coef", "totals", ).all() serializer_class = GameSerializer permission_classes = [AllowAny] pagination_class = StandardResultsSetPagination @silk_profile(name="Get Games") def list(self, request): qs = self.get_queryset().order_by("-timestamp__ts") page = self.paginate_queryset(qs) if page is not None: serializer = GameSerializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(qs, many=True) return Response(serializer.data) Join is happening because I'm ordering on a related field? My models looks like: class Game(models.Model): id = models.AutoField(primary_key=True) ... class Timestamp(models.Model): id = models.AutoField(primary_key=True) game = models.ForeignKey(Game, related_name="timestamp", on_delete=models.CASCADE) ts = models.DateTimeField(db_index=True) time_of_day = models.TimeField() And my serializers: class TimestampSerializer(serializers.Serializer): ts = serializers.DateTimeField(read_only=True) time_of_day = serializers.TimeField(read_only=True) class GameSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) timestamp = TimestampSerializer(many=True) fighters = FighterSerializer(many=True) score = ScoreSerializer(many=True) coefs = CoefsSerializer(many=True) rounds = RoundsSerializer(many=True) rounds_view = RoundsViewSerializer(many=True) rounds_view_f = RoundsViewFinishSerializer(many=True) finishes = FinishesSerializer(many=True) rounds_time = RoundTimesSerializer(many=True) round_time = RoundTimeSerializer(many=True) time_coef = TimeCoefsSerializer(many=True) totals = … -
Trouble displaying inline forms of a ModelAdmin
I am encountering what seems to me a weird bug when rendering Inline forms on the "Add" view of a ModelAdmin. Here is a minimum example with Django version 2.2.4. in models.py: class MyModel(models.Model): text = models.CharField(max_length=100) class RelatedModel(models.Model): parent = models.ForeignKey(MyModel, null=False, on_delete=models.CASCADE) number = models.DecimalField(decimal_places=2, max_digits=10, null=False, blank=False) in admin.py: class RelatedModelInlineTabular(admin.TabularInline): model = RelatedModel show_change_link = False fields = ("number", ) class TestMyModelCreate(admin.ModelAdmin): fields = ['text', ] inlines = [RelatedModelInlineTabular] admin.site.register(MyModel, TestMyModelCreate) Steps to replicate Login to django admin website open the "add" view for MyModel (i.e. navigate to the list of Models and click on the "Add new" button) Expected result The form displays an empty text field. Below that, an Inline form is displayed with 3 empty rows for potential related instances of RelatedModel Actual result The Inline form is displayed twice, each instance with its own 3 empty rows, as if I had specified it twice. I attach a screenshot below of the actual page (Discount is the name of the related Model). I tried and I get the same result with both StackedInline and TabularInline. Am I making some trivial error here that could explain what's happening? Or is this is a known … -
404 Error on TextArea in Admin interface, Django Summernote
For texteditor i use Summernote Django, but i got error 404 on admin interface. summernote editor id doesn't find. that's urls.py urlpatterns = [ path('admin/', admin.site.urls), path('summernote/', include('django_summernote.urls')), ] -
How to get updated class variable value in Django
Hello~ I'm having trouble getting the updated value of the class variable. When ConnectTestAPI is called after "p_request" function executed, the class variables which are "result" and "orderNo" should updated in the "post" function. Then I want to receive the updated value of class variables by looping while statement in "p_request" function. However, despite setting the values of class variables with the post request, when the while statement is run, the corresponding values are still empty and 0 value respectively, so the while statement cannot be terminated and result in a time out error. Here is my source code. Thank you in advance!!!! class ConnectTestAPI(APIView): result="" orderNo=0 def post(self, request): data = request.data ConnectTestAPI.result = data['result'] ConnectTestAPI.orderNo = data['orderNo'] print(ConnectTestAPI.result) # I could successfully get data from POST request here! print(ConnectTestAPI.orderNo) # I could successfully get data from POST request here! return HttpResponse("ok") def p_request(): data = { "a" : 1234, "b" : 5678 } data = json.dumps(data,ensure_ascii=False).encode('utf-8') con = redis.StrictRedis(outside_server['ip'],outside_server['port']) con.set("data_dict", data) while True: if ConnectTestAPI.result != "" and ConnectTestAPI.orderNo != 0: break res_result = ConnectTestAPI.result res_orderNo = ConnectTestAPI.orderNo return res_result, res_orderNo -
Url pattern in django rest framework
I am trying to use modelviewset and for that I have to use router in urls file for routing. Everything seems to be working as expected but my urls are highlighted as if the code is just ignored in my pycharm. It is as follows: Here as we can see above, it is highlighted by pycharm as if the code doesnt have any part in the project or is being ignored. When I use apiview and do not use the routers, the urls are not highlighted and are shown normally. What is the issue?? -
How to turn on and off pagination in django rest?
I tried like this but it is returning paginated queryset even if I call api with my/api/?no-page I want to disable pagination and show all data if no-page in query params else paginate queryset as usual. class CustomPagination(PageNumberPagination): def paginate_queryset(self, queryset, request, view=None): if "no_page" in request.query_params: return None return super().paginate_queryset(queryset, request, view) -
How to update a nested object in Django?
I'm trying to update a nested object in Django but facing an error with sub-object id's already existing. I have these two Models: class Plan(models.Model): planId = models.CharField(primary_key=True, max_length=100, unique=True) name = models.CharField(max_length=200) class PlanEvent(models.Model): plan = models.ForeignKey(Plan, on_delete=models.CASCADE) id = models.CharField(primary_key=True, max_length=100, unique=True, blank=False, null=False) done = models.BooleanField() title = models.CharField(max_length=100, blank=True) I have an update method in my PlanSerializer and it works if I send a PUT request with an empty events-list, but if I include some events I want to update, I get an error: { "events": [ { "id": [ "plan event with this id already exists." ] } ] } This is my PlanSerializer update method: class PlanSerializer(serializers.ModelSerializer): events = PlanEventSerializer(many=True) class Meta: model = Plan fields = ('planId', 'name', 'events') def update(self, instance, validated_data): events_validated_data = validated_data.pop('events') events = (instance.events.all()) events = list(events) instance.name = validated_data.get('name', instance.name) instance.save() for event_data in events_validated_data: event = events.pop(0) event.done= event_data.get('done', event.done) event.title = event_data.get('title', event.title) event.save() return instance So I'm not getting to the update-method at all when I pass events to the PUT -payload, what I'm doing wrong? -
How to display Model Object Count In Django Admin Index
I am trying to display the count of objects of each model. For this i have edited env > lib > django > contrib > templates > admin > app_list.html, bellow is the code. I am having to doubts here. I know this is not optimal solution where editing directly in env django folder. So how i can edit the app_list.html so that i can display the count. I tried {{model}}, but was not able to display count, always come as blank as you can see in image. Possible out i tried in template html- {{model}} Object - {'name': 'Exam categorys', 'object_name': 'ExamCategory', 'perms': {'add': True, 'change': True, 'delete': True, 'view': True}, 'admin_url': '/admin/quiz/examcategory/', 'add_url': '/admin/quiz/examcategory/add/', 'view_only': False} {{model.count}} Object - {{model.all}} Object - {{model.objects.all}} Object - ---------------------------------------------------------------- env > lib > django > contrib > templates > admin > app_list.html ---------------------------------------------------------------- {% load i18n %} {% if app_list %} {% for app in app_list %} <div class="app-{{ app.app_label }} module{% if app.app_url in request.path %} current-app{% endif %}"> <table> <caption> <a href="{{ app.app_url }}" class="section" title="{% blocktranslate with name=app.name %}Models in the {{ name }} application{% endblocktranslate %}">{{ app.name }}</a> </caption> {% for model in app.models %} <tr class="model-{{ … -
mod_wsgi-express module-config command not working during django deployment on apache
During the deployment of my Django Project with Apache and mod_wsgi on Windows10. I have installed Apache24 in my C drive and its working fine. After that I have installed openpyxl and mod_wsgi with the commands "pip install openpyxl" and "pip install mod_wsgi" respectively. Both has been installed successfully. But when I try to run this command "mod_wsgi-express module-config" on the command prompt it shows me error "mod_wsgi-express : The term 'mod_wsgi-express' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again." error picture -
unable to predict in my web model after conversion of keras_savedmodel
After tensorflowjs conversion i got my model.json and weights.bin files like tutorials suggested i posted it in my github repository and used it to load my web app but the predictions are horrible and i dont know how to include labels to identify while predicting the models[ const video = document.getElementById('webcam'); const liveView = document.getElementById('liveView'); const demosSection = document.getElementById('demos'); const enableWebcamButton = document.getElementById('webcamButton'); const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0) const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0) var vidWidth = 0; var vidHeight = 0; var xStart = 0; var yStart = 0; // Check if webcam access is supported. function getUserMediaSupported() { return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia); } // If webcam supported, add event listener to activation button: if (getUserMediaSupported()) { enableWebcamButton.addEventListener('click', enableCam); } else { console.warn('getUserMedia() is not supported by your browser'); } // Enable the live webcam view and start classification. function enableCam(event) { // Only continue if the model has finished loading. if (!model) { return; } // Hide the button once clicked. enableWebcamButton.classList.add('removed'); // getUsermedia parameters to force video but not audio. const constraints = { video: true }; // Stream video from browser(for safari also) navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" }, … -
psycopg2 undefined column on column value
psycopg2 is being a preteen child to me right now. cur = conn.cursor() url = "https://shofi-mod.s3.us-east-2.amazonaws.com/" + str(rawbucketkey) query = f"""UPDATE contentcreatorcontentfeedposts_contentfeedpost SET picturemediatype = TRUE, mediakey ={rawbucketkey}, mediaurl= "{url}", active = TRUE, postsubmit = FALSE WHERE contentcreator_id ={userid} AND id ={contentpostid}; COMMIT;""" cur.execute(query) cur.close() But I keep getting an error: [ERROR] UndefinedColumn: column "https://shofi-mod.s3.us-east-2.amazonaws.com/061909729140543151" does not exist LINE 3: mediaurl= "https://shofi-mod.s3.us-east-... ^ Traceback (most recent call last): File "/var/task/lambdarunner.py", line 163, in lambda_handler cur.execute(query) and my database does in fact have a media column class ContentFeedPost(models.Model): contentcreator = models.ForeignKey(ContentCreatorUsers, on_delete=models.CASCADE) creationtimestamp = models.DateTimeField(auto_now_add=True) likes = models.BigIntegerField(default= 0) favoritedtimes = models.BigIntegerField(default=0) tipcount = models.IntegerField(default=0) mediakey = models.CharField(max_length=200, null=True, blank=True) mediaurl = models.CharField(max_length=200, null=True, blank=True) audiomediatype = models.BooleanField(default=False) videomediatype = models.BooleanField(default=False) audiotitle = models.CharField(max_length=100, null=True, blank=True) videoplaceholderimage = models.CharField(max_length=200, blank=True, null=True) videoplaceholderimagekey = models.CharField(max_length=200, blank=True, null=True) audioplaceholderimage = models.CharField(max_length=200, blank=True, null=True) audioplaceholderimagekey = models.CharField(max_length=200, blank=True, null=True) picturemediatype = models.BooleanField(default=False) postsubmit = models.BooleanField(default=True) posttext = models.CharField(max_length=1000, blank=True, null=True) active = models.BooleanField(default=False) Above is a django ORM definition whats weird is that it looks like its complaining about the value im trying to set the column mediaurl to. This makes no sense. Is there something Im doing wrong that is obvious?