Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'Request' object has no attribute 'DELETE'
I am trying to add permission for deleting an object. views.py class DeleteView(APIView): permission_classes = [IsAllowedDelete] def delete(self, request, id): obj = Mymodel.objects.get(id=id) obj.delete() return Response({"detail" : "Deleted successfully"}, status.HTTP_204_NO_CONTENT) urls.py path('remove/<int:id>', vm.DeleteView.as_view(), name='delete_view'), permissions.py class IsAllowedDelete(permissions.BasePermission): def has_permission(self, request, view): if request.method == "DELETE": print('id : ',request.DELETE["id"]) return True else: return False But I am getting the below error:- AttributeError: 'Request' object has no attribute 'DELETE' at below statement:- request.DELETE["id"] Please help me to fix this. -
transaction.atomic celery task
I have transaction.atomic celery task: @app.task( name="create_order", bind=True, ignore_results=True, ) @transaction.atomic def create_order(self: Task) -> None: try: data = MyModel.objects.select(...) # Some actions that may take long time and only use DB for SELECT queries make_order(data, ...) except SomeException as exc: raise self.retry(exc=exc, countdown=5) else: data.status = DONE data.save() @transaction.atomic decorator creates new connection with DB and holds it before any exception or COMMIT statement. But what if task raises self.retry? Connection will be closed and when the task retries django will open a new one? -
How to exclude certain DateField and CharFields in IF statement?
I'm very new to Django, being a C guy (embedded/Linux) for the most part, so I apologize for my ignorance. I've tried searching for this exact problem with no luck. I have a Django project in which I have forms. When the form is not nullable, I want to put an asterisk in the visible name so that an end user knows it is mandatory to fill in Hence, we created the following code: # we need to add a * to the label if the fields are not nullable model = self.Meta.model nullable_fields = [f.name for f in model._meta.get_fields() if f.null] for visible in self.visible_fields(): # if the field is not nullable add an asterix, # that is if the label doesn't already have one for some arbitrary reason if visible.name not in nullable_fields and not visible.label.endswith("*"): visible.label = visible.label + ' *' Now, this is working fine for most of my models. However, for certain fields which are presented as nullable still an asterisk is added (FK). Please see these models: class BU(SoftDeleteObject, models.Model): class Meta: verbose_name_plural = "Business Units" users = models.ManyToManyField( 'User', blank=True, verbose_name="Gebruikers met toegang", through='UserBu', related_name='users') class EmailTemplate(SoftDeleteObject, models.Model): cc = models.ManyToManyField( Group, related_name='cc', … -
Performing git pull operation from a django view
I am trying to perform a git pull operation when a django view is called inside the view. cmd = 'cd %s && git pull origin master' % dir_path process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdout, stderr = process.communicate() I get below error in stderr: fatal: unsafe repository ('/home/user/my_dir' is owned by someone else) To add an exception for this directory, call: git config --global --add safe.directory /home/user/my_dir I believe it is ownership related issue but not sure about the solution. It is currently running from django runserver. I have tried adding this directory to safe.directories git config --global --add safe.directory /home/user/my_dir but still see the same error -
when a certain time value comes from false back to true
I need to make it automatically when it comes leave_date(leaveted date) room_bool == True now it's all done via urls.py /get/by/<int:pk> views.py date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') reg = Registration.objects.get(rooms_id=pk) room = Rooms.objects.get(pk=pk) a = reg.leave_date.replace(tzinfo=None) >= datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S').replace( tzinfo=None) if a != True: reg.room_bool = True reg.save() room.room_bool = True room.save() models.py room_num = models.IntegerField() room_bool = models.BooleanField(default=True) #if room_bool = True room is open, else closed. category = models.CharField(max_length=150) def __str__(self): return f'{self.room_num}' class Meta: verbose_name = 'Room' #This class Registration for visitors, to open room for the them class Registration(models.Model): rooms = models.ForeignKey(Rooms, on_delete=models.CASCADE) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) admin = models.ForeignKey(User, on_delete=models.CASCADE) pasport_serial_num = models.CharField(max_length=100) birth_date = models.DateField() img = models.FileField() visit_date = models.DateTimeField() leave_date = models.DateTimeField() guest_count = models.IntegerField() def func(self): room = Rooms.objects.filter(room_bool=True) for i in room: if i.room_num == int(self.rooms): i.room_bool = False #this should change when adding new registration i.save() -
User() got an unexpected keyword argument 'profile_image' when creating user
i created a user registration form using from django.contrib.auth.models import User, auth but when i try to submit the form instead of creating a new user it's throws me an error like: TypeError at /register/ User() got an unexpected keyword argument 'profile_image' ? is anybody who know what's wrong with my code please ? the register template: <form action="{% url 'register' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label style="font-family: Arial, Helvetica, sans-serif; color: dodgerblue;">Username</label> <input type="text" class="form-control" name="username"> </div> <br> <div class="form-group"> <label style="font-family: Arial, Helvetica, sans-serif; color: dodgerblue;">First Name</label> <input type="text" class="form-control" name="first_name"> </div> <br> <div class="form-group"> <label style="font-family: Arial, Helvetica, sans-serif; color: dodgerblue;">Last Name</label> <input type="text" class="form-control" name="last_name"> </div> <br> <div class="form-group"> <label style="font-family: Arial, Helvetica, sans-serif; color: dodgerblue;">Enter Your Email</label> <input type="email" class="form-control" name="email"> </div> <br> <div class="form-group"> <label style="font-family: Arial, Helvetica, sans-serif; color: dodgerblue;">Password</label> <input type="password" class="form-control" name="password"> </div> <br> <div class="form-group"> <label style="font-family: Arial, Helvetica, sans-serif; color: dodgerblue;">Repeat Password</label> <input type="password" class="form-control" name="password2"> </div> <br> <div class="mb-3"> <label for="formFile" class="form-label">Profile Image</label> <input class="form-control" type="file" id="formFile" name="profile_image"> </div> <br> <a href="{% url 'login' %}" style="text-decoration: none; font-family: Arial, Helvetica, sans-serif; color: dodgerblue;">Already Have An Account</a> <br> <br> <button type="submit" class="btn btn-warning">Create</button> </form> the register view: … -
Facing ModuleNotFoundError: No module named 'django' on Apache and Django Setup
Need help and clear understanding on Django and Apache based environment setup. My setup information as follows: OS: Ubuntu 20.04 Apache2 configured with Virtual Host Django2.2 installed without sudo Python 3.8.10 Configuration from default-ssl.conf <IfModule mod_ssl.c> <VirtualHost *:443> WSGIScriptAlias /dynamic /var/project/module/wsgi.py WSGIApplicationGroup %{GLOBAL} ServerName localdev.test.com <Directory /var/www> AllowOverride None Require all granted </Directory> <Directory /var/project> AllowOverride None Require all granted </Directory> </VirtualHost> </IfModule> Now my issue is whenever I tried to access Django Admin component it throws following error in Apache error logs. [Tue May 24 04:45:17.726120 2022] [wsgi:error] [pid 12972:tid 140147584620288] [client 103.179.111.50:54976] mod_wsgi (pid=12972): Failed to exec Python script file '/var/project/module/wsgi.py'. [Tue May 24 04:45:17.726169 2022] [wsgi:error] [pid 12972:tid 140147584620288] [client 103.179.111.50:54976] mod_wsgi (pid=12972): Exception occurred processing WSGI script '/var/project/module/wsgi.py'. [Tue May 24 04:45:17.726247 2022] [wsgi:error] [pid 12972:tid 140147584620288] [client 103.179.111.50:54976] Traceback (most recent call last): [Tue May 24 04:45:17.726274 2022] [wsgi:error] [pid 12972:tid 140147584620288] [client 103.179.111.50:54976] File "/var/project/module/wsgi.py", line 16, in <module> [Tue May 24 04:45:17.726279 2022] [wsgi:error] [pid 12972:tid 140147584620288] [client 103.179.111.50:54976] from django.core.wsgi import get_wsgi_application [Tue May 24 04:45:17.726297 2022] [wsgi:error] [pid 12972:tid 140147584620288] [client 103.179.111.50:54976] ModuleNotFoundError: No module named 'django' My setup does not use django virtual environment and also as mentioned above django … -
How to get the model default value after creating new, without call another get?
Is there any way to get default value (such as ID of type UUID) after creating a new row. Here is my model class Employee(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name= models.CharField(max_length=255) created_at = models.DateField(default=None, blank=True, null=True) class Meta: db_table="business" When I create I do this, for example from rest_framework import generics from django.forms.models import model_to_dict class Create(generics.CreateAPIView): def post(self, request) inputData = {"name":"abcdef", "created_at": datetime.datetime.now} employee = Employee.objects.create(**inputData) return JsonResponse(model_to_dict(employee), safe=False) Here is the response: { "name": "abcdef", "created_at": "2022-05-24T10:36:39.126", } So now I dont know what is the ID of the new row I just create -
504- Gateway timeout only in django function
I have a very mind-boggling problem and my team has struggled to solve it. We do have it narrowed down but not 100%. Introduction We are trying to implement LTI in a Django app with the Vue frontend. To fetch the token from the URL the backend makes a POST request to the URL with data and should receive a token or error if it's expired or invalid. Design Browser ---- POST REQUEST --> view function on Server (Django) --- POST REQUEST --> Auth URL Problem The post request that Django view makes times out the 504 Gateway Timeout. This could be normal if the server takes a lot of time. However, increasing the time did not help and checked Auth URL with POSTMAN it worked fine and was not down. What I have tried We decided to debug or diagnose this issue that why a code block works in a function when it is called through a shell but not when it is called by a POST request does not. Eliminated the front end and used POSTMAN to send a POST request to my Django server -- timeout on the Auth URL Called the same function using Django shell … -
Couldnot resolve URL for hyperlinked relationship using view name "snippet-detail"or incorrectly configured the `lookup_field` attribute on this field
""ImproperlyConfigured at /snippet/5 Could not resolve URL for hyperlinked relationship using view name "snippet-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field."" ----models.py from email.policy import default import imp from tkinter import CASCADE from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles from pygments.lexers import get_lexer_by_name from pygments.formatters.html import HtmlFormatter from pygments import highlight from django.contrib.auth.models import User import snippets # Create your models here. LEXERS=[item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES=sorted([(item[1][0],item[0]) for item in LEXERS]) STYLE_CHOICES=sorted([(item,item)for item in get_all_styles()]) class Snippet(models.Model): created=models.DateTimeField(auto_now_add=True) title=models.CharField(max_length=100,blank=True,default='') code=models.CharField(max_length=250,default="0") linenos=models.BooleanField(default=False) language=models.CharField(choices=LANGUAGE_CHOICES,default='python',max_length=100) style=models.CharField(choices=STYLE_CHOICES,default='friendly',max_length=100) owner=models.ForeignKey('auth.User',related_name='snippets',on_delete=models.CASCADE) class Meta: ordering=['created'] ------permissions.py import imp from rest_framework import permissions class IsOwnerReadOnly(permissions.BasePermission): """custom permissions to only allow owners of an oject to edit """ def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user -------serializers.py from operator import mod from numpy import source from .models import * from rest_framework import serializers from snippets.models import Snippet, LANGUAGE_CHOICES,STYLE_CHOICES class SnippetSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') class Meta: model=Snippet fields = ['url', 'id', 'owner', 'created', 'title', 'linenos', 'language', 'style'] # fields='__all__' # fields=['id','url','owner'] from django.contrib.auth.models import User class UserSerializer(serializers.HyperlinkedModelSerializer): snippets=serializers.HyperlinkedRelatedField(lookup_field = 'username',many=True,view_name='snippet-details',read_only=True) owner=serializers.ReadOnlyField(source='owner.username') class … -
ModuleNotFoundError: No module named 'drf_spectacular.views'
urls.py from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'), path('api/docs/', SpectacularSwaggerView.as_view(url_name='api-schema'), name='api-docs'), path('api/redoc/', SpectacularRedocView.as_view(url_name='api-schema'), name='api-redoc'), path('api/user/', include('user.urls')), path('api/recipe/', include('recipe.urls')), ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'drf_spectacular', 'core', 'user', 'recipe', ] requirements.txt drf-spectacular # drf-spectacular>=0.15,<0.16 REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } I'm trying to add Swagger UI in Django API, but I'm getting this error ModuleNotFoundError: No module named 'drf_spectacular.views'. -
List all online users in a Django Project
You see I am trying to make a simple chatting web app in Python/Django and I was trying to make the mock-up of the whole project first. But when i got to the part where other users would be able to see who was online or not i totally got stuck. I mean I HAVE NO IDEA AT ALL. any ideas??? -
type object 'PizzaMenu' has no attribute '_default_manager'
I have following error while i try to reach PizzaDetailView on template: AttributeError at /pizza/6/ type object 'PizzaMenu' has no attribute '_default_manager'. Where is the problem? models.py class PizzaMenu(models.Model): name = models.CharField(max_length=30) description = models.TextField() ingredients = models.CharField(max_length=100) price = models.DecimalField(max_digits=4, decimal_places=2) def __str__(self): return self.name class Meta: ordering = ["price"] views.py from django.views.generic import TemplateView, ListView, DetailView from .models import PizzaMenu class IndexView(TemplateView): template_name = "index.html" class PizzaMenu(ListView): model = PizzaMenu template_name = "menu.html" context_object_name = "pizza_menu" # ordering = ["price"] class PizzaDetailView(DetailView): model = PizzaMenu template_name = "pizza_detail.html" context_object_name = "pizza_detail" class About(TemplateView): template_name = "about.html" urls.py from pizza.views import IndexView, PizzaMenu, About, PizzaDetailView urlpatterns = [ path("", IndexView.as_view(), name="home"), path("menu/", PizzaMenu.as_view(), name="menu"), path("about/", About.as_view(), name="about"), path("pizza/<int:pk>/", PizzaDetailView.as_view(), name="pizza_detail"), path("admin/", admin.site.urls), ] -
DRF/django-filter programmatically calling a Filterset class without using the Viewset/request
I am building functionality to allow users to save a set of filters from a query-builder component on my Angular frontend. I am also using the django-filter package to power most of the search ability in my app. Say I have a model named MyModel (with a FK field 'category') and a ViewsSet wherein I've specified filterset_class = MyModeFilter from django_filters import rest_framework as filters class MyModelFilter(filters.Filterset): category_in = filters.BaseCSVFilter(field_name='category', method='filter_category_in') def filter_category_in(self, qs, name, value): # filters happen return qs This works well when my frontend calls https://api-url/mymodel/?category_in=1,2,3 What I want to do now is programmatically call this filter from inside the django app. Use case: I need to program a CRON job to build and email an excel report based on a queryset that would match the ?category_in=1,2,3 param filter. This is very straightforward with the ViewSets when using DRF requests, but I don't know where to start looking at his to use this filter without going the requests route. The the filter is saved in a JSONField (saved_query_statement) in a model called SavedQuery. It will look something like this: sqs = { 'name': 'category', 'lookup_expr': 'in', 'value': '1,2,3' } So the CRON job function, when executed, will … -
list index out of range Django overlapping
Hi When I am checking overalapping i am getting list index out of range, how i can solve that , for i in range(count): start_value=(self.data.get(f'applicationvalue_set-{i}-start_value', [])) end_value=(self.data.get(f'applicationvalue_set-{i}-end_value', [])) if start_value is not None or end_value is not None: value1=[] value2=[] for start in start_value: if start not in value1: value1.append(start) for end in end_value: if end not in value2: value2.append(end) a=range(value1[0],value1[-1]) b=range(value2[0],value2[-1]) if a in b.exists(): raise ValidationError("overlap not allowed")djangp -
I want to create a chart label with code like this, but I got an error. what's the solution?
I think there's something wrong with the labels and I don't know what. Please I need your help. I want to create a chart label with code like this, but I got an error. what's the solution? <div class="container"> <div class="row my-5"> <div class="col-md-6"> <div class="bg-white"> <canvas id="myChart1" width="400" height="300"></canvas> <script> var ctx = document.getElementById('myChart1').getContext('2d'); var myChart1 = new Chart(ctx, { type: 'pie', data: { labels: [{% for product in product %} '{{product.name}}', {% endfor %}], datasets: [{ label: 'Orders', -
Changing the language in Firefox Selenium Django / Python for behave tests
I am running local Selenium Behave tests on Firefox for a Django / Python project. My Firefox browser is set to English and I visit my local website via the browser manually everything is in English. However, when I run the Behave tests with Selenium, the browser is in German, as well as the standard language selected on my website. When I use the fix in this thread it changes the browser language to English but not the default language of the website. This would be the code of the before_all script: from selenium.webdriver import Firefox, FirefoxOptions from selenium.webdriver.support.ui import WebDriverWait def before_all(context): """Run once before any testing begins.""" options = FirefoxOptions() options.set_preference('intl.locale.requested', 'en') options.headless = False context.driver = Firefox(options=options) context.driver.implicitly_wait(5) context.driver.set_window_size(1024, 768) context.wait = WebDriverWait(context.driver, 30) logging.disable(logging.ERROR) (The problem is that the behave tests do not find the German button texts) -
Django Production Server Server Error 500 nginx -t shows something different
I need to deploy my website urgently and when I finally did that I was playing around with certbots and so on and it worked fine. Both Http and Https website with domain was running. I made changes to my code and the settings and reloaded the nginx and gunicorn and I thought it is still working fine. But then I had some code changes that weren't taking effect so I did a reboot. Now the server isn't working coming back with Server Error 500. python manage.py runserver runs fine. Debug is true in setting.py nginx -t comes back with this problem: ubuntu system django Version 4.x, python 3.9. nginx: [alert] could not open error log file: open() "/var/log/nginx/error.log" failed (13: Permission denied) 2022/05/24 08:44:59 [warn] 4182#4182: the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /etc/nginx/nginx.conf:1 2022/05/24 08:44:59 [emerg] 4182#4182: cannot load certificate "/etc/letsencrypt/live/domain.com/fullchain.pem": BIO_new_file() failed (SSL: error:8000000D:system library::Permission denied:calling fopen(/etc/letsencrypt/live/domain.com/fullchain.pem, r) error:10080002:BIO routines::system lib) I need to get this server up and running again. Please help. Thank you -
django 3.2.9: update time stamp on view function call
I am using django 3.2.9 as a back-end for my app. This is an excerpt of my Project model: class Project(TimeStampedModel): """ A collection of projects completed """ uuid = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True) account = models.ForeignKey('accounts.Account', on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=True, null=True) description = models.CharField(max_length=250, blank=True, null=True) # I need to add a time stamp here copied_on I need to add a time stamp to my Project model that gets updated every time the following view is called: @action(detail=True, methods=['post']) def copy_to_account(self, request, *args, **kwargs): user = request.user project = self.get_object() do yo know how to do it? Thank you -
How to implement date range filter in django-filters
I want to filter upload_date in date range (upload_date__lte, upload_date__gte) My models is class MetaData(models.Model): # Video Info tag = models.CharField(max_length=100, default="") category = models.CharField(max_length=100, default="") upload_date = models.DateField() upload_time = models.TimeField() caption = models.CharField(max_length=2000, blank=True, default='Not Set') comments = models.IntegerField() likes = models.IntegerField() shourtcode = models.CharField(max_length=200, default='', unique=True) owner_id = models.PositiveIntegerField(default=0) # Post link = models.URLField(unique=True) user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True) status = models.CharField(max_length=20, choices=( ('Pending', 'Pending'), ('Acquired', 'Acquired'), ('Rejected', 'Rejected'), ('Approved', 'Approved')), default='Pending') public = models.BooleanField(default=False) date = models.DateTimeField(auto_now_add=True) My views is class FetchMetaData(ListCreateAPIView): queryset = MetaData.objects.all() serializer_class = s.MetaDataSerializer name = 'metadata-list' pagination_class = DefaultPagePagination filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filter_fields = ( "tag", "category", "public", "status", "user", "upload_date", ) ordering_fields = ( '-upload_date', '-upload_time', 'likes', 'comments', ) search_fields = ( "$tag", "$caption", "$category" ) ordering = ['-upload_date'] What I want is filter range in upload_date Like http://localhost/tags/filterMetadata/?upload_date__lte=2022-01-05?upload_date__gte=2022-01-05 -
starting a website project in python and django in windows 10
Whenever I type django-admin start project project name the console returns Django-admin : The term 'Django-admin' 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. At line:1 char:1 Django-admin start project emart + CategoryInfo : ObjectNotFound: (Django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException. -
AssertionError: Class UserSerializer missing "Meta" attribute while performing User Accounts Management on Django
my views.py file: from rest_framework.views import APIView from rest_framework.response import Response from .serializers import UserSerializer class TestView(APIView): def get(self, request, format=None): print("API called") return Response("You did it!", status=200) class UserView(APIView): def post(self, request, format=None): print("User created") user_data = request.data print(request.data) user_serializer = UserSerializer(data=user_data) if user_serializer.is_valid(raise_exception=False): user_serializer.save() return Response({'user': user_data}, status=200) return Response({'msg': "error: no user created"}, status=400) my serializers.py file: from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.validators import UniqueValidator from rest_framework.settings import api_settings class UserSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) username = serializers.CharField( required=True, max_length=32, validators=[UniqueValidator(queryset=User.objects.all())] ) first_name = serializers.CharField( required=True, max_length=32 ) last_name = serializers.CharField( required=True, max_length=32 ) password = serializers.CharField( required=True, min_length=8, write_only=True ) def create(self, validated_data): password = validated_data.pop(password, None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token class Meta: model = User fields = ( 'token' 'username', 'password', 'first_name', 'last_name', 'email', 'id' ) my urls.py file: from django.urls import path from .views import TestView, UserView from rest_framework_jwt.views import refresh_jwt_token, verify_jwt_token urlpatterns = [ path('test', TestView.as_view()), path('user-view/', UserView.as_view()), ] Postman request: as you can see, i'm sending a username … -
Django translations with parler - show default language text when adding translation
I'm working on a Django CMS with content to be translated into multiple languages. I'm using django-parler. To make the translations easier I would like to have the text from the default language visible when adding the translated text, preferable just above the input field/textarea. Any ideas on how to solve it? -
how to improve many to many relationship in django
I have 2 models User and Content and they have relationship called Watched which is many-to-many. this relationship will be using a third table (using through in Django) and how it works is that for each set of user and content we are going to keep what was the last position before they stopped watching and there is going to be one row per each user-content so if a user watches a content multiple time first time that row is created and next times that row only updates to keep the last data. our database engine is mariadb. currently we have about 10000 users and 4000 contents. so at max that third table would have 40,000,000 and we expect to have about 15000 users and 6000 content so it need to be able to handle 90,000,000 record at most. Question 1: someone suggested we handle the third table ourselves and don't use the many-to-many relationship offered by Django because it might use some joins and queries that will be heavy for database. (so it would be a table with 2 integer fields for id and 1 other field for last position) is this a good solution or we should stick … -
Django: How to display the average of all rating using django?
i am creating a function where users can rate a book using django, i have achieved the part where users can rate the book using a form from the front end and it get saved in the backend. Now what i want to achieve is a way to display an average of all the rating that the user make. e.g let say there are usera - 1.0, userb - 3.0, userc -5.0. i want to display the average which is 3.0 and i dont know how to achive this. let men put some of the code i have written below models.py class BookRating(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE, null=True) rating = models.CharField(max_length=1000, choices=USER_BOOK_RATING) review = models.TextField() view.py - only what i am doing is listing out all the reviews but not the average of star rating