Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django graphene accept any mutation input
In mutation, I just need to save the event name and its payload that might differ and I do not need any validation for it. How can I say graphene that I just need to accept an object? class SendEvent(MutationMixin, relay.ClientIDMutation): class Input: event = graphene.String(required=True) payload = # any object -
Improve Django application logs to only display custom log from Logging settings
I am trying to improve the logging of my Django application to have it in a standardized way for querying it with Loki and for each log that I create, 3 log entries are recorded. For example, any request (sucess or failed) to this endpoint below will generate three log entries. views.py class ModelViewSet(models.ModelViewSet): def retrieve(self, request, *args, **kwargs): try: # do something logger.info(f"{request.path} {request.method} 200: user {request.user.id} - success!") return Response(serializer.data) except Exception as exc: logger.warning(f"{request.path} {request.method} {exc.status_code}: user {request.user.id} - {exc.detail}") return Response(exc.detail, status=exc.status_code) settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'timestamp': { 'format': '{asctime} {levelname} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'timestamp' }, }, 'loggers': { 'django': { 'handlers': ['console', ], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, }, } Output in console 2022-06-02 10:26:09,714 WARNING /api/v1/<path/ GET 403: user 71 - You do not have permission to perform this action. 2022-06-02 10:26:09,814 WARNING Forbidden: /api/v1/<path/ 2022-06-02 10:26:09,815 WARNING "GET /api/v1/<path/ HTTP/1.1" 403 12495 Any suggestion on how to optimize and have only one entry, preferably my custom logging entry and get rid of the other two? This will also help reduce drastically the size of the logs stored. -
React and django cache issue
I have a react and django app which is being served behind nginx. The /admin route and /api routes both point to uwsgi. However when loading these routes the react app is served unless a hard refresh of the page is peformed. It seems like react is serving all routes instead of just the index. Is there a way to exclude routes in react so it will only display if the path is "/" or is there something in nginx/django config I can change to overcome this issue. This is a snippet from my nginx conf: location / { try_files $uri $uri/ =404; } location /api/ { uwsgi_pass uwsgi; include /etc/nginx/uwsgi_params; } location /admin/ { uwsgi_pass uwsgi; include /etc/nginx/uwsgi_params; } and my django urls config: urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include(routers.urls)) ] Any ideas on how I could proceed would be appreciated -
Django development static 404 not found: new files only
Curious issue on Django development server. Static files which are in existing use work just fine. When I add new files (of any sort) I get 404 not found. settings.py DEBUG = True INSTALLED_APPS = [ 'django.contrib.staticfiles', ] STATIC_ROOT = os.path.join(BASE_DIR, '') STATIC_URL = '/static/' template <img src="{% static 'media/cypress.jpg' %}"/> <!-- old file works --> <img src="{% static 'media/butterfly.jpg' %}"/> <!-- new file returns 404 --> Jquery files which were in use are found, those which were sat in the same folder unused before aren't. I assume therefore it's an indexing issue of some sort. I've tried python manage.py collectstatic but no joy. Any guidance much appreciated. -
I need to redirect users to a previously typed link after authentication. (I am using Django)
In my App, being authenticated is a must to access the content. Let's say someone shared a link such as http://website.com/form/ioxPwhRtV8zeW2Lj9njZjs4065Ml6u/viewform. If not authenticated, it redirects the user to the main login page. I need to figure out how once authenticated I redirect the same user back to the previously typed link http://website.com/form/ioxPwhRtV8zeW2Lj9njZjs4065Ml6u/viewform. I am using Django version 4.4 for my app. For a reference, here is my code: def login_view(request): """ Display the login form and handle the login action. """ form = LoginForm(request.POST or None) msg = None if request.method == "POST": if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) now = datetime.datetime.now() current_time = now.strftime("%I:%M %p, %B %d") msg = f'Success - Logged in at {current_time}' messages.success(request, msg) # Look over here. It redirects not to the location typed, but the home page. I want it to redirect any authenticated user to the previously typed URL. return redirect("/") else: msg = 'Invalid credentials' messages.error(request, 'Error validating the form') else: msg = 'Error validating the form' messages.error(request, 'Error validating the form') return render(request, "accounts/login.html", {"form": form, "msg": msg}) Mates, I need help fast. -
django models hierarchy question: related attributes of a ManyToManyField
As a fresh coder, I seriously have problems to build my models relations. Please check these two cases, How can I set current_reading_pages on my Scenario2? from django.db import models # Scenario1: Users can record their reading progress of a book. class Book(models.Model): name = models.CharField(max_length=128) class User(models.Model): current_reading_book = models.ForeignKey('Book', on_delete=models.CASCADE) current_reading_page = models.IntegerField() Result1: No problems about database, but Users can records their progress of only one book. Other scenario, which I want to build: from django.db import models # Scenario2: Users can record their reading progress of multiple books. class Book(models.Model): name = models.CharField(max_length=128) class User(models.Model): current_reading_books = models.ManyToManyField('Book') # current_reading_pages = ??? I want to save all progress of current books, for example, User A is reading 3 books, book1 till page 100, book2 till page 10, book3 till page 0. -
Adding a comment through page instead of /admin - django
I am able to add comments to a page through the /admin panel and I would like to be able to do so through a buttom.. I've created an HTML page and added a some functionality for it forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('commenter_name', 'comment_body') widgets = { 'commenter_name': forms.TextInput(attrs={'class': 'form-control'}), 'comment_body': forms.Textarea(attrs={'class': 'form-control'}), } views.py @login_required(login_url='/accounts/login') def add_comment(request, slug): movie = Movie.objects.get(slug=slug) form = CommentForm() context = {'form': form} return render(request, 'add_comment.html', context) add_comment.html <form action="add_comment.html" method="post"> <textarea name="comment" id="comment" rows="10" tabindex="4" required="required"></textarea> <a href="{% url 'movies:add_comment' movie.slug %}" class="myButton">Submit</a> urls.py path('<slug:slug>', MovieDetail.as_view(), name='movie_detail'), path('<slug:slug>/add-comment/', views.add_comment, name='add_comment'), models.py class Movie(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=1000) image = models.ImageField(upload_to='movies') banner = models.ImageField(upload_to='movies_banner', blank=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES, max_length=10) status = models.CharField(choices=STATUS_CHOICES, max_length=2) cast = models.CharField(max_length=100) year_of_production = models.DateField() views_count = models.IntegerField(default=0) movie_trailer = models.URLField() created = models.DateTimeField(blank=True, default=timezone.now) slug = models.SlugField(blank=True, null=True) class Comment(models.Model): movie = models.ForeignKey(Movie, related_name="comments", on_delete=models.CASCADE) commenter_name = models.ForeignKey(User, default=None, on_delete=models.CASCADE) comment_body = models.TextField() date_added = models.DateTimeField(auto_now=True) def __str__(self): return '%s - %s' % (self.movie.title, self.commenter_name) I've confirmed the URL works and the html webpage add_comment is shown.. my goal is to allow the user to comment - … -
Ngrok "HTTP Error 404". The requested resource is not found
Error picture I've tried to execute my django-app with "ngrok". Added url to "ALLOWED_HOSTS" and other variables which need that. I did 'py manage.py runserver' and 'ngrok http 80' together => no result. -
Django model inheritance with proxy classes
I've got proxy classes which have been created mainly to implement custom filtering, but there are some other fairly small custom methods as well, and they will be expanded to provide other custom logic as well. So say I have models: class Videos(models.Model): title = models.CharField(max_length=200) publisher = models.Charfield(max_length=100) release_date = models.DateField() class Superheroes(Videos): objects = SuperheroesManager() class Meta: proxy = True class Recent(Videos): objects = RecentManager() class Meta: proxy = True and model managers: class SuperheroesManager(): def get_queryset(self): return super().get_queryset().filter(publisher__in=['Marvel','DC']) class RecentManager(): def get_queryset(self): return super().get_queryset().filter(release_date__gte='2020-01-01') On the front end a user may pick a category which corresponds to one of the proxy classes. What would be the best way to maintain a mapping between the category which is passed to the view and the associated proxy class? Currently I have an implicit dependency whereby the category name supplied by the front end must be the same as the proxy class name, allowing for a standard interface in the view: def index(request, report_picked) category = getattr(sys.modules[__name__], report_picked) videos = category.objects.all() I'd like to move away from this implicit dependency, but not sure what the best way would be. I wouldn't want to maintain a dictionary and can't use a … -
How to get Id from CreateView in django
Hello all I need some help getting the id from an object in django I have a createView where I want to send an notification for the user when a new object is created, and I need the object Id... def form_valid(self, form): # setting fields that are not open to user form.instance.created_by = self.request.user form.instance.status = 'open' messages.success(self.request, 'Ticket Created Successfully!') Notification.objects.create( created_by=self.request.user, created_for=form.instance.responsible, title=f"New ticket from {self.request.user.first_name} {self.request.user.last_name} =====> {form.instance.id}", message=f"Hello",) return super().form_valid(form) The problem is that {form.instance.id} is always none. Anyone can help me with that? Thanks in advance -
Why do my javascript integration in a django template does not work?
I am really new to django and i am trying to build a small page where a chart with chart.js is shown. I want to load the javascript file static. I created a basic html-file called data_table.html and added a folder static where three files are in: data_table.js, styles.css and a picture bild.jpg. The html file is: {% load static %} <!DOCTYPE html> <head> <link rel="stylesheet" href="{% static 'styles.css' %}" type="text/css"> <script type="text/javascript" src="{% static 'data_table.js' %}"></script> <title>Data viewer</title> </head> <body> <canvas id="myChart" width="200" height="200"></canvas> <script> </script> <p class="text">Picture:</p> <br> <img class="img" src="{% static 'bild.jpg' %}" alt="My image"> </body> </html> The css file and the picture are loaded. The picture is displayed and with the css file i can resize the picture. So that works i guess? The javascripts file looks as follows: const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for d in data%}'{{d.label}}',{%endfor%}], datasets: [{ label: '# of Votes', data: [{% for d in data%}{{d.data}},{%endfor%}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, … -
Django export model to csv for ManyToManyField
Have a few tables for which I successfully built export to CSV, based on the Models. However, for one where I count the 'likes' for the news (posts) I'm getting nowhere. Here is my model: class News(models.Model): news_title = models.CharField(max_length=300) news_text = models.TextField(max_length=2000) news_author = models.CharField(max_length=150) news_date = models.DateField(default=now) likes = models.ManyToManyField(User, related_name='user_like', blank=True) @property def total_likes(self): return self.likes.count() Problem is, that I can print out to CSV all items from the model, but if I print "likes" I get duplicated (or more) rows in CSV. The reason is, that if News is liked by 3 users, I get 3x rows on CSV for each User and under "Like Count" column I get their IDs. What I would like to get instead is: 1x row per News with a total of likes for each news. and view.py @login_required def export_news(request): newss = News.objects.all() response = HttpResponse(content_type='txt/csv') writer = csv.writer(response) writer.writerow(["ID","Title","Author","Date","Text","Likes Count"]) for news in newss.values_list('id','news_title','news_author','news_date','news_text','likes'): writer.writerow(news) response['Content-Disposition'] = 'attachment; filename="News_list.csv"' return response Appreciate any help. Thx -
How to get current value from django table
I am only getting the last value from my django table after clicking the delete button. html file - <body> <div class="for-body"> <!-- test table --> <form method="POST" action=""> {% csrf_token %} <input id="label" name="engname" value="{{ eng_name }}">{{ eng_name }}</input> <button name="update" class="add-button" type="submit"><b>Update</b></button> <button name="add" class="add-button1" type="submit"><b>Add Existing User</b></button> <tbody class="for-tbody1"> <tr class="for-tr1"> <td class="for-td1"> <dh-components-grid-body-render class="for-dhcomp"> <div class="for-div1"> <table class="for-table1" id="pgnum"> <thead class="for-thead1"> <tr class="for-tr2"> <td class="for-td2"><div class="dh-grid-headers-cell-default">User</div></td> <td class="for-td2"><div class="dh-grid-headers-cell-default">Email</div></td> <td class="for-td2"><div class="dh-grid-headers-cell-default">Role</div></td> <td class="for-td2"><div class="dh-grid-headers-cell-default">Remove</div></td> </tr> </thead> <tbody class="for-tbody2"> <tr class="for-tr3"> {% for i in user_list %} <td class="for-td3"><div class="cell-default-style">{{i.first_name}} {{i.last_name}}</div></td> <td class="for-td3"><div class="cell-default-style"><input type="hidden" value="{{ i.email }}" name="email">{{i.email}}</input></div></td> {% if i.is_superuser == True %} <td class="for-td3"><div class="cell-default-style">Super User</div></td> {% elif i.is_staff == True %} <td class="for-td3"><div class="cell-default-style">Admin</div></td> {% else %} <td class="for-td3"><div class="cell-default-style">Practitioner</div></td> {% endif %} <td class="for-td3"><div class="cell-default-style"><button class="btn" name="delete" type="submit"><img src="/static/assets/images/trash1.png" style="width: 18px;" alt="Delete"></button></div></td> </tr> {% endfor %} </tbody> </table> </div> </dh-components-grid-body-render> </td> </tr> </tbody> </form> </div> </body> views.py - def engagement_admin_edit(request, id): staff = request.user.is_staff a = User.is_authenticated if staff == True: eng_list = Grp.objects.all() eng = Grp.objects.get(id = id) eng_name = eng.gname eng_name = str(eng_name) eng_id = eng.id cursor = connection.cursor() cursor.execute('''SELECT * FROM main_enguser WHERE eid=%s''',[eng_id]) row = cursor.fetchall() users … -
How to optimize loading millions of records in MongoDB with Django admin?
I have MongoDB with over 20 million records integrated with Django administration. Both services are running in k8s. I have already applied some of the optimisations below: Adding NoCountPaginator (disable counting) Indexing MongoDB Sorting queryset Also, I read about adding skip and limit is not recommended since it will make the performance even worse. But still, loading is extremely slow and frequently throws timeout errors. Here's the custom manager to get queryset: models.py class RuleDataManagerRemoved(DjongoManager): def get_queryset(self): event_horizon = datetime.datetime.now() - datetime.timedelta(days=180) return RuleDataQuerySet(model=self.model, using=self._db, hints=self._hints).filter(last_change__gte=event_horizon) The filtering happens with indexed field, so I think the impact is not critical here. admin.py @admin.register(models.ChangedProductSlugs) class ChangedProductSlugsAdmin(RuleDataAdmin): paginator = NoCountPaginator show_full_result_count = False list_display = ('old_category_slug', 'old_product_slug', 'new_category_slug', 'new_product_slug', 'tld', 'last_change', 'created_by', 'stav') list_filter = ('last_change', ('old_product_slug', SingleTextInputFilterOldProduct), ('old_category_slug', SingleTextInputFilterOldCategory), ('new_product_slug', SingleTextInputFilterNewProduct), ('new_category_slug', SingleTextInputFilterNewCategory), 'deleted', 'deleted_by', 'tld') search_fields = ('old_category_slug', 'old_product_slug', 'new_category_slug', 'new_product_slug') resource_class = resources.ChangedProductSlugsResource actions = ['restore_queryset'] def stav(self, obj): return not obj.deleted stav.boolean = True def changelist_view(self, request, extra_context=None): default_filter = False try: ref = request.META['HTTP_REFERER'] pinfo = request.META['PATH_INFO'] qstr = ref.split(pinfo) if len(qstr) < 2: default_filter = True except: default_filter = True if default_filter: q = request.GET.copy() q['deleted__exact'] = '0' request.GET = q request.META['QUERY_STRING'] = request.GET.urlencode() return super(ChangedProductSlugsAdmin, … -
Django HttpRequest type hint / annotation problem
def my_func(request: HttpRequest) -> str: return request.user.email gives me a warning in PyCharm, saying that user is not a defined attribute. However writing it as request: HttpRequest() removes this warning, and gives me proper parameters in suggestions. Could someone explain why this is happening, and if I did something wrong? I'm importing HttpRequest from django.http. -
Django | I want to show the page to 'AnonymousUser' even though I'm using request.user in views.py
I want to show the page to all users even if they are not logged in but because im using request.user in views.py this is not possible. Is there anyway to handle this? views.py: class ServerView(View): def get(self, request, server_tag): server = Server.objects.get(tag=server_tag) posts = server.posts.all() is_following = False relation = ServerFollow.objects.filter(server=server, user=request.user) if relation.exists(): is_following = True return render(request, 'servers/server.html', {'server':server, 'posts':posts, 'is_following':is_following}) -
GA4 accounts not listed in Python
I want to list GA4 accounts in Python. But first, the user needs to connect Google Analytics account. Then I want to list the accounts with google.analytics.admin. How should I go about this? I followed this document but it didn't work: https://developers.google.com/analytics/devguides/config/admin/v1/quickstart-client-libraries#step_1_enable_the_api -
Django more type of user - ask about advice
I work on my project and i want create 3 type of user include Admin(user and second user with different premission). I want ask which method i should use to do it ? I read a bit about AbstractUser, create group and "flag's" 1th user - will can only add comment/ save file 2th user - will can create model and what 1th have 3th user - admin Admin after 2th get created should get notification that 2th suer get created and he need to accept his perrmision first (before he can create models like email and admin can do it in admin panel i think) -
Django DetailView count increases by 3 instead of 1
I have a webpage where every view is being counted by and incremented by 3 where it is intended to be incremented by 1 instead here's what I have in my views.py from django.views.generic import ListView, DetailView class MovieDetail(DetailView): model = Movie def get_object(self): object = super(MovieDetail, self).get_object() object.views_count += 1 object.save() return object def get_context_data(self, **kwargs): context = super(MovieDetail, self).get_context_data(**kwargs) context['links'] = MovieLink.objects.filter(movie=self.get_object()) context['related_movies'] = Movie.objects.filter(category=self.get_object().category) return context html <section class="movie"> <img src="{{object.image.url}}"> <ul> <li>{{object}}</li> <li>{{object.description}}</li> <li><a href="genre.html">Adventure</a>, <a href="genre.html">Drama</a>, <a href="genre.html">Romance</a></li> <li><a href="">{{object.cast}}</a></li> <li><i class="fa fa-eye" id="eye"></i> {{object.views_count}}</li> </ul> </section> It is scripted to increment by 1 but does not follow that logic.. what went wrong here? -
AttributeError at /class/55910/ 'tuple' object has no attribute 'get'
I've check the return render(), etc, I've all solutions and nothing happened. Thanks for solution, if you can solve this :) There is my classpage_views.py from django.shortcuts import render from django.http import HttpResponse from numpy import append from .models import Classes def class_article_preview(request, URLcodenumber): codenumber = Classes.objects.get(codenumber=URLcodenumber) schoolNum = '' classNum = '' def div_by_s_and_c(num): preSortArray = [] classSimLen = 1 if codenumber.is_2num_class == False: classSimLen = 1 else: classSimLen = 2 for sim in num: preSortArray.append(sim) schoolNumLen = len(codenumber.codenumber) - classSimLen for sim in preSortArray: nonlocal schoolNum schoolNum = schoolNum + str(sim) schoolNumLen = schoolNumLen - 1 if schoolNumLen <= 0: break for sim in reversed(preSortArray): nonlocal classNum classNum = classNum + sim classSimLen = classSimLen - 1 if classSimLen <= 0: classNum = classNum[::-1] break return classNum, schoolNum div_by_s_and_c(codenumber.codenumber) return classNum, schoolNum context = {'clsName': f'Школа №{schoolNum}, \n{classNum} параллель', 'articles': ['test', 'test2']} return render(request, 'blogpage\\articles_preview.html', context) def class_article_create(request): return render(request, 'blogpage\\create_article.html') This is traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/class/55910/ Django Version: 4.0.3 Python Version: 3.10.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'start_page', 'help_page', 'class_page'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner … -
What Django model field to use for the following JSON data from draft.js (react-draft-wysiwyg)?
I have a react-draft-wysiwyg component in my NextJS app, and I am trying to find a way to store that to my Django REST backend. This is the stringified JSON I get directly from the draft component, but I am not sure how to organize the django model to store such data as well as be able to make PATCH and GET requests later. Would appreciate any help! { blocks: [ { key: '64o0i', text: 'Introduction edited', type: 'header-three', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, { key: 'dcomv', text: 'this will be the awesome shit', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, { key: 'edvnc', text: 'Body paragraph', type: 'header-three', depth: 0, inlineStyleRanges: [ { offset: 0, length: 14, style: 'color-rgb(0,0,0)' }, { offset: 0, length: 14, style: 'bgcolor-rgb(255,255,255)' }, { offset: 0, length: 14, style: 'fontsize-24' }, { offset: 0, length: 14, style: 'fontfamily-ui-sans-serif, system-ui, -apple-system, "system-ui", "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji', }, ], entityRanges: [], data: {}, }, { key: 'd3sf7', text: 'this will be the awesome shit klasdfj lk;', type: 'unstyled', depth: 0, inlineStyleRanges: … -
Can't get data when writing interface using djangorestframework
from django.http import JsonResponse, Http404 from django.views import View from rest_framework.generics import GenericAPIView from rest_framework import filters from rest_framework.response import Response from persons.models import Persons from persons.serializer import PersonModelSerializer import json class PersonList(GenericAPIView): filter_backends = [filters.OrderingFilter] ordering_fields = ['name','nickname','grangs'] queryset = Persons.objects.all() serializer_class = PersonModelSerializer def get(self,request): person_qs = self.queryset person_qs = self.filter_queryset(person_qs) serializer = self.get_serializer(instance=person_qs,many=True) return Response(serializer.data) 编写一个查询接口报错提示: 'Do not evaluate the .queryset attribute directly, ' RuntimeError: Do not evaluate the .queryset attribute directly, as the result will be cached and reused between requests. Use .all() or call .get_queryset() instead.enter image description here -
Using a custom language gives "You have provided a value for the LANGUAGE_CODE setting that is not in the LANGUAGES setting."
I've just upgraded my Django project from 2.2 to 3.2 and the language broke. I had this piece of code which was working fine (inside my settings.py) LANGUAGE_CODE = 'tb' EXTRA_LANG_INFO = { 'tb': { 'bidi': False, 'code': 'tb', 'name': 'English', 'name_local': 'United States', 'fallback': ['en-US'], }, } import django.conf.locale LANG_INFO = dict(**django.conf.locale.LANG_INFO, **EXTRA_LANG_INFO) django.conf.locale.LANG_INFO = LANG_INFO Now I get ?: (translation.E004) You have provided a value for the LANGUAGE_CODE setting that is not in the LANGUAGES setting. Why is this happening and how can I fix it? Thanks. -
Static dict definition is python application till application is running
Trying to implement the the java static map implementation in python application. Tried approach: created a global dict, and trying to access it and update the same but not working. Created a class and created a global variable and trying to set and fetch from there. class staticdict: dict={} def init(self,type,data): self.dict[type]=data def __getitem__(self,type): return self.dict[type] setting the values : staticdict(type,nseTemp) fetching the values : print(" data----- "+ staticdict.getitem(type)) Error : TypeError: staticdict.getitem() missing 1 required positional argument: 'type' Also not sure this approach will work or it will keep on creating the new instance of class and override the dict present in the class. I want to keep the dict which will hold the data for static map -
How to use _set in SerializerMethod for instance?
I want to calculate the average rating by using SerializerMethodField(). The error in the following code is AttributeError: 'FeedbackModel' object has no attribute 'aggregate' I think _set is missing but I don't know where to put it..! class FeedbackSerializer(serializers.ModelSerializer): feedback_by_user_profile_pic = serializers.ImageField(source='feedback_by.profile_pic') average_rating = serializers.SerializerMethodField() def get_average_rating(self,instance): return instance.aggregate(average_rating=Avg('rating'))['average_rating'] class Meta: model = FeedbackModel fields = ['feedback_text','rating','date','feedback_by_user_profile_pic','average_rating'] Feedback Model class FeedbackModel(models.Model): feedback_text = models.CharField(max_length=1000) rating = models.IntegerField() date = models.DateField(auto_now=True) feedback_by = models.ForeignKey(UserModel,on_delete=models.CASCADE) business_account = models.ForeignKey(BusinessAccountModel,on_delete=models.CASCADE) class Meta: db_table = 'feedback'