Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Web Application Mutual authentification on development server
I am working on an application that needs mutual authentication; there are needs to test it on the development server I have so far got all the keys, server and client, the server can be authenticated, what i don't know is how to request the client(browser) for the keys. Ideally this should be done once at the first request, since there is also password authentication. Anyone to show me how to go about. Note: I have searched the web for some good hours with no answer so far -
How to set the Navigation bar in the top of the html page?
I developed an index.html page in django project. The below is the template code I developed. Right now, the navigation bar is coming at the bottom index.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Contact Book Template</title> <link type="text/css" rel="stylesheet" href="{%static 'css/style.css' %}" /> <!-- Google Font --> <link href="https://fonts.googleapis.com/css?family=PT+Sans:400" rel="stylesheet"> </head> <body> <img class="contact_book" src="{% static 'img/contact_book.jpg' %}" alt="first" /> <div id="booking" class="section"> <div> <ul id="horizantal-style"> <li><a href="#">Home</a></li> <li><a href="#">News</a></li> <li><a href="#">Contact</a></li> <li style="float:right"><a href="#">Login</a></li> <li style="float:right"><a class="active" href="#about">Sign up</a></li> </ul> </div> </div> </body> </html> I developed the style.css file as shown below ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #dddddd } li { display: inline-block; } li a { display: block; color: #000; text-align: center; padding: 20px 24px; text-decoration: none; } li a:hover { background-color: #555; color: white; } .active { background-color: #337ab7; } I am expecting it to set the navigation bar at the top, could anyone please help? -
Unable to display multiple locations using GraphHopper in Leaflet map
Description: I am trying to display a route on a Leaflet map that connects multiple locations using GraphHopper. I have defined an array of latitude and longitude points and passed it to the ghRouting.route() function along with the vehicle type and API key. However, I am getting an error "ghRouting.route is not a function" in the console. Code: <!-- Leaflet JavaScript --> <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script> <!-- GraphHopper Client Web JavaScript --> <script src="https://graphhopper.com/api/1/client.js?key=<your_api_key>"></script> <script> // Create a new Leaflet map centered on Kathmandu, Nepal var map = L.map('map').setView([27.7172, 85.324], 12); // Add a tile layer to the map L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors', maxZoom: 18, tileSize: 512, zoomOffset: -1 }).addTo(map); // Define an array of points (latitude and longitude) for the route var points = [ [27.7172, 85.324], // Kathmandu [27.6679, 85.3188], // Lalitpur [27.6729, 85.4286], // Bhaktapur [27.6256, 85.5154] // Banepa ]; // Define a GraphHopper routing object with the API key and profile var ghRouting = new GraphHopper.Routing({ key: '<your_api_key>', vehicle: 'car' }); // Calculate the route using the GraphHopper API ghRouting.route({ points: points, instructions: true, vehicle: 'car', elevation: false }, function (err, res) { if (err) { console.error(err); return; } // Create a new … -
How can I use the FloatingField function with an email input in Django crispy forms with Bootstrap 5?
I have a Django project where I'm using crispy forms with the Bootstrap 5 version. https://github.com/django-crispy-forms/crispy-bootstrap5 I have two floating fields for the username and password input, but I also need to add an email input. FloatingField('username', css_class='shadow-none'), FloatingField('password', css_class='shadow-none'), I tried to search for a solution in the GitHub repository, but I couldn't find anything. I was expecting to find some documentation or an example of how to add an email input to the floating field layout. I concluded that it would be best to ask here before submitting any issue to the github repository, so how can I add an email input to the floating field layout in Django crispy forms with Bootstrap 5? -
Testing Django API route with internal async call
I have a Django Rest Framework based API with some routes calling async methods (using Celery). Like so : class MyList(ListCreateAPIView, DestroyModelMixin): def post(self, request, format=None): # Asynchronous call using Celery shared task async_call = my_async_method.delay(request.data) return Response( { "status": async_call.status, "task_id": async_call.task_id }, status=status.HTTP_202_ACCEPTED ) my_async_method is doing some processing and finally serializes data to the database model. I already test (with pytest) that the API actually returns HTTP 202 response, and other basic use cases. Now I want to test that the object is actually created and check some assumptions about it. Yet, the call is asynchronous so the object is not created when I check the assert statements. @pytest.mark.django_db def test_post_myapi_success(api_client): my_object = {} client = api_client() url = reverse("api-v1-app:list") response = client.post(url, my_object) assert response.status_code == status.HTTP_202_accepted #True assert MyObject.objects.count() == 1 # False First question: does it make sense to test all at once (API response and object creation) or should I split the tests ? Second question: If I try to test the async function with @pytest.mark.asyncio and await asyncio.sleep(5) after making the API request, I get the following error : django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context. I guess this is … -
How to solve Django TemplateDoesNotExist at accounts/login.html error?
I made a blog app in Django and deployed it with Heroku. When I opened the app, get 'TemplateDoesNotExist at /accounts/login/' error. It should load the login.html and it did not load it. If anyone could help me, I would be thankful. I tried 'DIRS': [os.path.join(BASE_DIR, 'Templates')], but did not work. Or maybe I did something wrong. Here is my file structure: BLOG ├─.idea ├─accounts | ├─__pycache__ | ├─migrations | ├─Templates | | └─accounts | | ├─login.html | | └─signup.html | ├─__init__.py | ├─admin.py | ├─apps.py | ├─models.py | ├─tests.py | ├─urls.py | └─views.py ├─articles | ├─__pycache__ | ├─migrations | ├─Templates | | └─articles | | ├─article_create.html | | ├─article_details.html | | ├─article_form.html | | ├─article_list.html | | └─pagination.html | ├─__init__.py | ├─admin.py | ├─apps.py | ├─forms.py | ├─models.py | ├─tests.py | ├─urls.py | └─views.py ├─blog | ├─__pycache__ | ├─Templates | | └─default.html | ├─__init__.py | ├─asgi.py | ├─settings.py | ├─urls.py | ├─views.py | └─wsgi.py ├─media ├─static | ├─favicon.ico | ├─logo.png | ├─slugify.js | ├─styles.css | └─background.jpg ├─db.sqlite3 └─manage.py Here is some part of my settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['Templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Factory Boy Base64 Encoded String Faker
Is it possible to fake a base64 encoded string within factory-boy? For example, in a given factory, I'm able to fake (generate) a random name by doing name = factory.Faker("name"). In addition, I can fake an email by doing email = factory.Faker("email"). However, I'm not sure how to fake a base64 encoded string. In my model, I have a field which is a simple CharField as such: encoded_string = models.CharField(max_length=512, blank=True, null=True). How can I go by faking this within my factory? I have tried several options, but they all result in errors. base64.b64encode("sample_string".encode("ascii")) results in: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb5 in position 3: invalid start byte Doing base64.b64encode(bytes("[{\"key\":\"Key Example:\",\"value\":\"Value Example\\\"\"}]", 'utf-8')) results in: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x95 in position 5: invalid start byte Doing base64.b64encode(b'data to be encoded') results in: binascii.Error: Invalid base64-encoded string: number of data characters (25) cannot be 1 more than a multiple of 4 -
How to disable WSGI debugging (Web application could not be started)?
If there is an error in my code, the debugging happens in the browser and the user sees it. How do I disable the debugging? I wanted the debugging not to work in the browser enter image description here -
Django update table from MYSQL query without refreshing the whole page
Developing my first Django app and i'm using an input and a button to query MYSQL database and render the result in a table . It works fine but I would like to achieve the same thing without the page to reload (so I wont loose the input content). I read many tutorials but still can't figure out how to use AJAX as it seems to be the only way to do this. home.html <form id="post-form" action='{% url "filter" %}' method="POST"> {% csrf_token %} <input id='search' name='search' type='text'> <button name="button" type="submit" >Send</button> </form> <table id='myTable' class="table table-striped table-hover table-bordered fixed_header sortable"> <thead class="table-dark"> <tr id='tableHeader'> <th scope="col">Name</th> <th scope="col">Email</th> <th scope="col">Phone</th> <th scope="col">Address</th> <th scope="col">City</th> <th scope="col">State</th> <th scope="col">Zipcode</th> <th scope="col">Created At</th> <th scope="col">ID</th> </tr> </thead> <tbody> {% if records %} {% for record in records %} <tr> <td>{{ record.first_name }} {{ record.last_name }}</td> <td>{{ record.email }}</td> <td>{{ record.phone }}</td> <td>{{ record.address }}</td> <td>{{ record.city }}</td> <td>{{ record.state }}</td> <td>{{ record.zipcode }}</td> <td>{{ record.created_at }}</td> <td><a href="{% url 'record' record.id %}">{{ record.id }}</a></td> </tr> {% endfor %} {% endif %} </tbody> </table> views.py def filter(request): data = request.POST.get('search') print(data) if not data == "": records = Record.objects.raw("SELECT * FROM website_record … -
My web site on AWS with Django does not read CSS files on Amazon S3
My web site that is made by Django and deployed on AWS does not apply CSS files after I uploaded CSS files on Amazon S3 using collectstatic. $ python manage.py collectstatic I checked one of CSS files on Amazon S3, but I am not sure which one is the url target I should set in settings.py. Which part of settings.py I write below should I change? Thank you. settings.py import os BASE_DIR = Path(__file__).resolve().parent.parent ################################################################# ##### Static Files (CSS, JavaScript, Images) ################################################################# STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') ################################################################# ##### Amazon S3 ################################################################# DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" STATICFILES_STORAGE = "storages.backends.s3boto3.S3StaticStorage" AWS_LOCATION = "static" AWS_STORAGE_BUCKET_NAME = "mydomain-bucket" AWS_S3_REGION_NAME = "ap-northeast-1" AWS_S3_CUSTOM_DOMAIN = "%s.s3.amazonaws.com" % AWS_STORAGE_BUCKET_NAME # AWS_S3_CUSTOM_DOMAIN = "{}.s3.{}.amazonaws.com".format(AWS_STORAGE_BUCKET_NAME, AWS_S3_REGION_NAME) # AWS_DEFAULT_ACL = None STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) Python 3.9 Django 4.1 Apache 2 -
Django - Specify in which database a model (table) must be created
I have many django models in my models.py. I have two data bases (db1 and db2). How can I specify each model to be created in the corresponding database. For example: class ModelDB1(models.Model): # This class table must be created in db1 class ModelDB2(models.Model): # This class table must be creared in db2 -
How to store data that has been initialized by code in BaseInlineFormSet
I need help. I have a specific form which has the option to create a month and a specific value for that month. Here is the model: class MonthAllocat(BaseModel): variable = models.ForeignKey(Variable, related_name="month_allocat", on_delete=models.CASCADE) month = models.PositiveSmallIntegerField(choices=MONTH_CHOICES) weight = models.DecimalField(max_digits=5, decimal_places=2, validators=PERCENTAGE_VALIDATOR) class Meta: db_table = "month_allocation" unique_together = ["month", "forecast"] ordering = ("month",) variable - this is the main form on which the work takes place At the time of creating a new form, I set certain values for each month: Here is what I have in admin.py -> class MonthAllocationInline(admin.TabularInline): model = MonthAllocation formset = VariableMonthAllocationInlineFormSet fields = ("month", "weight") classes = ("collapse",) ordering = ("month",) max_num = len(MONTH_CHOICES) form = MonthAllocationForm class Media: css = {"all": ("css/hide_admin_object_name.css",)} def get_extra(self, request, obj=None, **kwargs): # pragma: no cover if obj: return 0 else: return len(MONTH_CHOICES) -> class MonthAllocationForm(ModelForm): def __init__(self, *args, **kwargs): # pragma: no cover super(MonthAllocationForm, self).__init__(*args, **kwargs) if kwargs.get("prefix").split("-")[1].isdigit() and not self.initial: # type: ignore self.fields["month"].initial = MONTH_CHOICES[int(kwargs.get("prefix").split("-")[1])][ # type: ignore 0 ] self.fields["weight"].initial = round(Decimal(100 / len(MONTH_CHOICES)), 2) class Meta: model = MonthAllocation fields = ("month", "weight") Previously, I checked that the sum is equal to 100 class VariableMonthAllocationInlineFormSet(FieldTargetSumFormSetMixin): SUM_BY_FIELD = "weight" TARGET_SUM = 100 class … -
OperationalError while connecting django and mysql other
I have problems when I try to connect the mysql database with my application in django. 'default': (1045, "Access denied for user 'PEPE'@'localhost' (using password: NO)") that user does not exist in the database and my settings.py file does not define it either DATABASES = { 'default': {'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_python', 'DATABASE_USER': 'root', 'DATABASE_PASSWORD': 'abc', 'DATABASE_HOST': '127.0.0.1', 'DATABASE_PORT': '3306', } } I don't understand why django uses a different user when trying to establish the connection inside the python shell I print the value of the settings_dict['DATABASE_USER'] variable and it shows the correct user 'root' but it doesn't use it to establish the connection -
DRF: AttributeError when trying to creating a instance with SlugRelatedField and double underscore in slug_field
I get this error as the instance is successfully created and saved in the database with POST request and DRF: AttributeError: 'UserProfile' object has no attribute 'user__username' Here is my UserProfile and **UserImpression" models: class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE, primary_key=True) avatar = models.ImageField(upload_to=user_directory_path, null=True, blank=True) imp_laptop = models.ManyToManyField(Laptop, related_name="laptop_impression", through="UserImpression", through_fields=('profile', 'laptop')) objects = models.Manager() custom_manager = UserProfileCustomManager() def __str__(self): return self.user.username + ' profile' class UserImpression(models.Model): profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) laptop = models.ForeignKey(Laptop, on_delete=models.CASCADE) liked = models.BooleanField(default=True) class Meta: constraints = [ models.UniqueConstraint(fields=['profile', 'laptop'], name='unique_profile_laptop_impression'), ] My serializer class UserImpressionSerializer: class UserImpressionSerializer(serializers.ModelSerializer): profile = serializers.SlugRelatedField(queryset=UserProfile.objects.all(), slug_field="user__username") laptop = serializers.SlugRelatedField(queryset=Laptop.objects.all(), slug_field="slug") class Meta: model = UserImpression fields = ['profile', 'laptop', 'liked'] validators = [ UniqueTogetherValidator( queryset=UserImpression.objects.all(), fields=['profile', 'laptop'] ) ] def create(self, validated_data): profile = validated_data.get("profile", None) laptop = validated_data.get("laptop", None) if profile is None: raise serializers.ValidationError( {"profile": "Cannot retrieve the profile instance with the username"} ) if laptop is None: raise serializers.ValidationError( {"laptop": "Cannot retrieve the laptop instance with the laptop slug"} ) liked = validated_data.get("liked", True) return UserImpression.objects.create(profile=profile, laptop=laptop, liked=liked) My goal for the profile field is to get the UserProfile instance through the username field in the User model which has a 1-1 relationship with … -
Django channels websocket gives 404
I have created a django channels project on windows following the tutorial, and when I run it using dev server python manage.py runserver it seems websocket requests are handled as HTTP and I get Not Found: /ws/socket-server/. What could be the reason? I have tried with Python 3.7 with Django 3.2.18; or Python 3.11, Django 4.1.7 -
How to grenerate graph of part of a database using django_extensions
I'm following this tutorial https://medium.com/@yathomasi1/1-using-django-extensions-to-visualize-the-database-diagram-in-django-application-c5fa7e710e16 To generate graphic ER diagrams on django and because the database is to big, the graph is a little confusing so I want to create more than one file with the different relations. My question is, how to create something like this? python manage.py graph_models app1 -a -I model1, model2 -o output.png > output.dot Being app1 one of the aplications and model1, model2 two models located in another app. Is that even possible? Or do I have to enter manually all the models involved. If someone can help me with this I will appreciate it Cheers -
Django and HTMX for dynamically updating dropdown list in form.field
Using django and htmx I need to do the following. In a parent form create-update.html I need to give a user the ability to add another 'contact' instance to a field that contains a drop list of all current 'contact' instances in the database. I want the user to click an add button next to the sro.form field, which renders a modal containing a child form new_contact.html. The user will then enter the new 'contact' instance into the child form in the modal form new_contact.html and click save. This will cause the new contact instance to be saved to the database via create_contact_view(), and for the the sro form field in the parent form create-update.html to be replaced via an AJAX call, with an refreshed dropdown list I've partially completed this. I have a working modal form which is saving new 'contact' instances to the database, but the sro.form field just disappears and isn't reloaded. Here's my code. Many thanks. views.py class ProjectCreateView(CreateView): model = Project form_class = ProjectUpdateForm template_name = "create-update.html" def get_context_data(self, **kwargs): context = super(ProjectCreateView, self).get_context_data(**kwargs) context["type"] = "Project" context["new_contact_url"] = reverse("register:new-contact") # to create new url return context def form_valid(self, form, *args, **kwargs): mode = form.cleaned_data["mode"] … -
DJango Microsoft auth allauth automatic
I have a program in DJango. I have a second program called "users". Inside I have implemented login and login with microsoft authentication. I have done this using the "allauth" library. Now I want you when accessing the page, (without having to access the "/login" page) check if you have a microsoft account. That is, when I enter the main page: "/", it takes me to the page to choose a microsoft account in the event that it has one. Without having to press any buttons. That's possible? That it automatically connects if I am connected to a Microsoft account. This is my view: def home(request): if request.user.is_authenticated: return redirect('main_page') else: return render(request, 'home.html') I don't know if I explained myself correctly, I want the Microsoft authentication to be automatic -
My .pkpass file not working for iOS system, but in app Passes(android) I can see the content
I use Django-wallet for generation of .pkpass files. Everything works in Android, but for iOS I can't see the card Firstly I used certificates from another computer, but then I regenerated all certificates and etc on my own. Also I resized images Anything above doesn't helped -
Does xhtml2pdf also execute <script> tag in html?
I am trying to create a pdf from html in Django and I am using xhtml2pdf python module. But the issue is, it is not executing script tag in html. So does xhtml2pdf even execute script tag in html?? if not, please recommend any other module that does!! -
Video not playing in server (Django)
I am fairly new to Django and currently I'm making a Youtube Clone to understand Django in depth. So the problem I'm facing right now is that I can't seem to get the video to play in the server. I've spent a lot of time trying but can't seem to find an answer! I'll provide what I think relates to my problem; 1) Template ` video.html <video width="320" height="240" controls> <source src="{{ video.path }}" type="video/mp4"> Your browser does not support the video tag. </video>` 2) views.py `class VideoView(View): template_name = 'base/video.html' def get(self, request, id): #fetch video from DB by ID video_by_id = Video.objects.get(id=id) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) video_by_id.path = 'http://localhost:8000/get_video/'+video_by_id.path context = {'video':video_by_id} if request.user.is_authenticated: print('user signed in') comment_form = CommentForm() context['form'] = comment_form comments = Comment.objects.filter(video__id=id).order_by('-datetime')[:5] print(comments) context['comments'] = comments return render(request, self.template_name, context) class VideoFileView(View): def get(self, request, file_name): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) file = FileWrapper(open(BASE_DIR+'/'+file_name, 'rb')) response = HttpResponse(file, content_type='video/mp4') response['Content-Disposition'] = 'attachment; filename={}'.format(file_name) return response` 3) models.py `class Video(models.Model): title = models.CharField(max_length=30) description = models.TextField(max_length=300) path = models.CharField(max_length=100) datetime = models.DateTimeField(auto_now=True ,blank=False, null=False) user = models.ForeignKey('auth.User', on_delete=models.CASCADE) ` 4) urls.py ` app_name = 'Youtube' urlpatterns = [ path('home/', HomeView.as_view(), name='homeview'), path('login/', LoginView.as_view(), name='loginview'), path('register/', RegisterView.as_view(), name='register'), path('new_video/', … -
How to split django app in multiple folder
I like to split my django app here in my case it's called Core in multiple folders like in the picture. Example Bank ---views ---urls ---models ---serializer Currency ---views ---urls ---models ---serializer I put in each folder the __init.py__ file here the init file from bank folder ` from .models import BimaCoreBank` and here the models.py for bank folder from core.abstract.models import AbstractModel from core.country.models import BimaCoreCountry from core.state.models import BimaCoreState class BimaCoreBank(AbstractModel): name = models.CharField(max_length=128, blank=False, unique=True) street = models.CharField(max_length=256, blank=True, null=True) street2 = models.CharField(max_length=256, blank=True, null=True) zip = models.CharField(max_length=16, blank=True, null=True) city = models.CharField(max_length=16, blank=True, null=True) state = models.ForeignKey( BimaCoreState, on_delete=models.PROTECT) country = models.ForeignKey( BimaCoreCountry, on_delete=models.PROTECT) email = models.EmailField(blank=True, null=True) active = models.BooleanField(default=True) bic = models.CharField(max_length=16, blank=True, null=True) def __str__(self) -> str: return self.name class Meta: ordering = ['name'] permissions = [] app_label = "BimaCoreBank" and here the urls.py file from bank folder from rest_framework import routers from core.bank.views import BimaCoreBankViewSet router = routers.DefaultRouter() app_name = 'BimaCoreBank' urlpatterns = [ router.register(r'bank', BimaCoreBankViewSet, basename='bank'), ] It's the same on each folder,juste I changed the name of the class, Now in the __init.py__ file in core folder( the app folder that containt all the subfolders) from . import bank from … -
The 'Access-Control-Allow-Origin' header contains multiple values ERROR
I have an app with react frontend and django backend. I have a problem, when the frontend wants to get a file from the backend, an error appears Access to XMLHttpRequest at 'http://api.(site name).com/documents/15/' (redirected from 'http://api.(site name).com/documents/15') from origin 'http://www.(site name).com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'http://www.sitename.com, *', but only one is allowed. my nginx.conf on my server server { server_name api.sitename.com; listen 80; server_tokens off; client_max_body_size 10m; root /var/html/; # location ~ /.well-known/acme-challenge/ { # root /var/www/certbot; # } location / { if ($request_method = 'POST') { add_header 'Access-Control-Allow-Origin' '*' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always; } if ($request_method = 'GET') { add_header 'Access-Control-Allow-Origin' '*' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always; } if ($request_method = OPTIONS ) { add_header "Access-Control-Allow-Origin" '*' always; add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD"; add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept"; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; return 204; } # proxy_set_header Host $host; # proxy_set_header X-Forwarded-Host $host; # proxy_set_header X-Forwarded-Server $host; # proxy_pass http://backend:8000; } location /media/ { autoindex on; } location /docs/ { root /usr/share/nginx/html; try_files $uri $uri/redoc.html; } location … -
Group by with related_name relation using Prefetch
I need to make an API with this body structure for graph with multiple lines: [ { "title": "Test title", "dots": [ { "date": "2023-03-03", "sum_weight": 5000 }, { "date": "2023-03-06", "sum_weight": 1500 } ] } ] But I have a problem with Prefetch, since it's not possible to use .values() to do group_by date during query. Right now my ungrouped API looks like this: [ { "title": "Test title", "dots": [ { "date": "2023-03-03", "sum_weight": 5000 }, { "date": "2023-03-06", "sum_weight": 500 }, { "date": "2023-03-06", "sum_weight": 1000 } ] } ] My code right now: Query: groups = Group.objects.prefetch_related( Prefetch("facts", queryset=Facts.objects.order_by("date").annotate(sum_weight=Sum("weight"))) ) Serializers: class GraphDot(serializers.ModelSerializer): sum_weight = serializers.SerializerMethodField() def get_sum_weight(self, obj): if not hasattr(obj, 'sum_weight'): return 0 return obj.sum_weight class Meta: model = Facts fields = read_only_fields = ("date", "sum_weight",) class FoodGraphSerializer(serializers.ModelSerializer): dots = GraphDot(many=True, source="facts") class Meta: model = Group fields = read_only_fields = ("title", "dots") Is there any way to make a query that is grouped by date so my sum_weight annotation is summed within it? -
unable to authenticate the django login page in mysql
[I am unable to authenticate django login session with mysql] already tried below things (https://i.stack.imgur.com/rPFWE.png)