Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save Temporary Data in Django
Is there any way to save temporary data in django framework? For example I need to save temp notices in a table, with expiration date. To give a better example, I have a table called product and in this table there are several fields such as: title, description, notices and others... is it possible to create a product with a temporary notice? like, this product has this notice until tomorrow. -
Question about the location of the git repository when deploying Django project on Elastic Beanstalk
i'm new in both python and elastic beanstalk. Here's my file structure: /.git # <- here's my git repo /my-first-django |-- django-project |-- app |-- django-project | |-- __init__.py | |-- settings.py | |-- urls.py | `-- wsgi.py `-- manage.py /venv When I read this doc, I can see they create git repository at the same level as django-project. Should I move the repository? Or am I fine with my current structure when deploying with awsebcli? Thank you for your help! -
Need Serialize a custom filed AVG notes for my API in Django
models.py from django.db import models from django.db.models import Avg from users.models import UserProfile from subjects.models import Subject class Note(models.Model): id_user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='user_note') id_subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='subject_note') exam_note = models.IntegerField() @property def average_note(self): if hasattr(self, '_average_note'): return self._average_note return Note.objects.aggregate(Avg('exam_note')) Thats my Note models and i need to calculate the notes average to serialize it and send in request resonse views.py class AvgNoteViewSet(viewsets.ModelViewSet): serializer_class = AvgSerializer authentication_classes = (TokenAuthentication,) permission_classes = (NotePermissions,) def get_queryset(self): return Note.objects.all().annotate(_average_note=Avg('exam_note')) And that is my get_queryset redefined method to calculate de average notes, but im just having a list of notes for result of that query, like that: resques response serializers.py class AvgSerializer(serializers.ModelSerializer): """ Serializes a notes AVG """ average_note = serializers.SerializerMethodField() def get_average_note(self, obj): return obj.average_note class Meta: model = Note fields = ['average_note'] And this is my serializer My intencion is try to get an avergate from the exam_notes from the logged user, so i understand that i need to try to group by user_id ant then agregate the average. This is my postgresql table from when im querying: notes_table I based my code from How to calculate average of some field in Django models and send it to rest API?, … -
Django database information doesn't exist when deployed to Heroku
I recently deployed a django rest api to heroku and the database is not working properly. When trying to log in, it seems that the user object that was in my sqlite database in my own files does not exist and therefore it tells me that my credentials are invalid. Does anyone know how to make it so that the database data gets uploaded to Heroku? Here is my Procfile: release: python manage.py makemigrations --no-input release: python manage.py migrate --no-input web: gunicorn rrt.wsgi Here are my Django settings: DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'articles', 'author_auth', 'authors', 'threads', 'category', 'rest_framework', 'corsheaders', 'rest_framework_simplejwt.token_blacklist', 'ckeditor', ] 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', 'corsheaders.middleware.CorsMiddleware' ] ROOT_URLCONF = 'rrt.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'rrt.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # … -
how to change images in boostrap's example?
I am a rookie of html. My English is also poor. Just download the bootstrap-v4 examples. One of the examples is carousel, but i don't kown which place in codes to change the images. And I don't understander the meaning of code below. Who can help me would be much appreciated. example's link :https://v4.bootcss.com/docs/examples/ .bd-placeholder-img { font-size: 1.125rem; text-anchor: middle; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } @media (min-width: 768px) { .bd-placeholder-img-lg { font-size: 3.5rem; } } </style>``` -
Django how to show many2many extra fields in a form?
here are my models.py: class EssentialOil(models.Model): name = models.fields.CharField(max_length=120, verbose_name="Nom") latin_name = models.fields.CharField(max_length=120, verbose_name="Nom latin") abbreviation = models.fields.CharField(max_length=8, verbose_name="Abbréviation") image = models.fields.CharField(default=None, null=True, blank=True, max_length=255, verbose_name="Photo") administrationmodes = models.ManyToManyField('AdministrationMode', through="EssentialOil_AdministrationMode", verbose_name="Mode d'administration") components = models.ManyToManyField('Component', through="EssentialOil_AdministrationMode", verbose_name="Composants") warnings = models.ManyToManyField('warning', through="EssentialOil_AdministrationMode", verbose_name="Points d'attention") properties = models.ManyToManyField('property', through="EssentialOil_AdministrationMode", verbose_name="Propriétés") uses = models.ManyToManyField('use', through="EssentialOil_AdministrationMode", verbose_name="Utilisations thérapeuthiques") class Meta: ordering = ['name'] def __str__(self): return self.name class AdministrationMode(models.Model): mode = models.fields.CharField(max_length=100, verbose_name="Mode") description = models.fields.CharField(max_length=2000, verbose_name="Description") warning = models.fields.TextField(max_length=2000, default="Aucun", verbose_name="Point d'attention") eo = models.ManyToManyField(EssentialOil, through='EssentialOil_AdministrationMode', blank=True, verbose_name="H.E. concernées") class Meta: ordering = ['mode'] def __str__(self): return self.mode class EssentialOil_AdministrationMode(models.Model): class Efficiency(models.IntegerChoices): RARE = 1 PARFOIS = 2 SOUVENT = 3 IDEAL = 4 eo = models.ForeignKey("EssentialOil", null=True, on_delete=models.CASCADE) am = models.ForeignKey("AdministrationMode", null=True, on_delete=models.CASCADE) co = models.ForeignKey("Component", null=True, on_delete=models.CASCADE) pr = models.ForeignKey("Property", null=True, on_delete=models.CASCADE) us = models.ForeignKey("Use", null=True, on_delete=models.CASCADE) wa = models.ForeignKey("Warning", null=True, on_delete=models.CASCADE) efficiency = models.IntegerField(Efficiency.choices) class Meta: unique_together = [['eo', 'am']] My forms.py: from django import forms from django.forms import ModelForm from .models import EssentialOil, AdministrationMode, Component, Warning, Property, Use class CreateEssentialOil(ModelForm): class Meta: model = EssentialOil fields = "__all__" administrationmodes = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=AdministrationMode.objects.all(), label="Mode d'administration") components = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Component.objects.all(), label="Composants") warnings = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Warning.objects.all(), label="Points d'attention") properties = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Property.objects.all(), … -
update_create is creating new feilds instead of updating total
payments = list((expense .annotate(month=Month('startDate')) .values('month') .annotate(total=Sum('cost')) .order_by('month'))) for i in payments: paymentMonths = (i["month"]) paymentTotal= (i["total"]) obj, created = Payment.objects.update_or_create( author=curruser, date=paymentMonths, total = paymentTotal, defaults={"total": paymentTotal}, ) totalcost = Payment.objects.filter(author = curruser.id) Apparently, it should update the (date = 12) total but it is making new ones with the updated value, it might be because the totaldate is diff or maybe I'm wrong it is confusing -
Django, url not found 404
Project Folder structure I am new to django. I am trying to create a simple rest api end point, but I get a 404. I am sure I am missing some setting. models.py class DisplayItems(models.Model): yesNo = models.CharField(max_length=10) yogaMessage = models.CharField(max_length=50) yogaTimeMessage = models.CharField(max_length=100) @classmethod def create(cls, yesNo, yogaMessage, yogaTimeMessage): displayItems = cls(yesNo=yesNo, yogaMessage=yogaMessage, yogaTimeMessage=yogaTimeMessage) return displayItems serializers.py from .models import DisplayItems class DisplayItemsSerializer(serializers.ModelSerializer): yesNo = serializers.CharField(max_length=10) yogaMessage = serializers.CharField(max_length=50) yogaTimeMessage = serializers.CharField(max_length=100) class Meta: model = DisplayItems fields = ('__all__') urls.py from .views import DisplayItemsViews from django.contrib import admin urlpatterns = [ path(r'^admin/', admin.site.urls), path(r'^zzz/', DisplayItemsViews.as_view()), ] views.py from rest_framework.response import Response from rest_framework import status from .serializers import DisplayItemsSerializer from .models import DisplayItems class DisplayItemsViews(APIView): def get(self, request): displayItems = DisplayItems.create("YES!", "There's yoga today", "At 2:00 pm Eastern Time") serializer = DisplayItemsSerializer(displayItems) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) The url I am trying to run is http://127.0.0.1:8000/zzz/ I have read almost all relevant stackoverflow posts, but can't seem to understand what I am missing. -
Get the users download directory
I'm on my linux server and I want to save something into the downloads folder from the user which is using the website, how do I get the downloads path from the user, when I try to save something in the downloads folder a folder named "downloads" gets created in my root directory, and not in my computers downloads folder. -
How to update user as an admin in djoser django?
My problem is that I want to change user status from admin panel. Admin should be able to change field "is_staff" from his panel. When I read the documentation, it says: User Use this endpoint to retrieve/update the authenticated user. Default URL: /users/me/ https://djoser.readthedocs.io/en/latest/base_endpoints.html#user Okay, and I am planning to use it to change user's password later, but it makes sense to change users password while being logged in as this user. But how to change another field ('is_staff') in another user while being logged in as admin? Does sending request to /users/me/ make sense? I will update this with any code needed. -
Creating endpoint fetch data from local json file using django rest
I am trying to create django application with a REST api endpoint. The application should be able to able to fetch a list of users from the json file The API should also allow the user to fetch a specific user from the json file. Json file {users:[ {"name":"Julia", "phone" :'+111454545' }, {"name":"Kenny" "phone":"+9911111111' }, ]} How do I do that ? -
reference a HTML tag with javascript that was generated from django json schema
i am trying to reference a HTML tag that is generated by a django's django_jsonforms link JSON Schema link via javascript to dynamically update the form. For example 2 dropdowns in a form, if you make a selection in the 1st dropdown the 2nd dropdown should update. I've done this for HTML selection tags that i manually typed out but i am trying to get this to work for HTML generated by JSON Schemas. Here is what i've tried: inspect HTML page and try to call the tag by name with var project_selection = document.getElementsByClassName("form[project]")[0]; this didnt work, which i was a little surprised by since i see when i inspect the page that the select tag has name="form[project]" then i thought maybe the JSON Schema renders the tag after the javascript runs so i tried adding defer into my <script defer> and that didnt work i tried using JSON Schema $id #anchor and $ref but none of those worked to reference the tag by ID I am sure someone has come across this before so i hope this is an easy answer. At the end of the day i know i need to use the following with the JSON … -
Django UUID Validation Error: Sometimes object, sometimes UUID
This page is supposed to show a post for a social media website. Within <div class="is-flex">, I have an if/else/endif block for showing a like/unlike button. As the code is right now, it successfully shows the like/unlike button on non-shared posts. I would like to have it so the like/unlike button appears on all posts as long as {user.is_authenticated} is true, but if I move the like/unlike code block anywhere else in the div, I get this error. Even adding the line for the button and commenting it out gives the error. No variables are being written, only read, so I don't know why Django would get the UUID in one instance and the entire post object in another instance. Lines with *NOTE* comments are lines I tried duplicating/moving the like/unlike code block to without success. {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} {% #header user=user %} {% /header %} {% load crispy_forms_tags %} {% load markdown_extras %} {% load url_check %} {% load comment_like %} {% load post_like %} <main> <div class="is-flex mt-3"> <small>Posted by: <a href="/author/{% valid_url_profile post.author.id %}">{{post.author.displayName}}</a></small> <small> &nbsp;• {% load tz %} {% localtime on %} <small>Created: {{post.published}}</small> … -
Show related item django
I have the following models: class Category(models.Model): name = models.CharField(max_length=255) class Element(models.Model): category = models.ForeignKey(Category) name = models.CharField(max_length=255) class Topic(models.Model): category = models.ForeignKey(Category) element = models.ForeignKey(Element) name = models.CharField(max_length=255) I basically need to add New topic in catégory id =1 and get only a list of élément belongs to category 1 I have created a view New topic in category id =1, but for fields element in form i get all elements for all categories -
how do I align RadioSelect button?
For some reason this button comes with weird alignment, I want it aligned next to gender label but the ul element comes with pre existing "margin-block-start, margin-block-end and padding-inline-start" so how do I align it right? html <div class="block"> <label>Gender</label> <span class="placer">{{ form.gender }}</span> </div> css #id_gender li { list-style-type: none; display: inline-block; } forms.py gender = forms.ChoiceField(choices=GENDER_CHOICES, widget=forms.RadioSelect(), required=True) I want the radios(Male and Female) to be aligned next to Gender. Thnx in advance! -
Fetch : authentication credentials were not provided
When I request this, everything is ok and I get the data: const get_players = async()=>{ const response = await fetch('http://127.0.0.1:8000/player_stats/api/players/') const data = await response.json() console.log(data) } But when I put permission_classes in views.py, I recive this in the console: {detail: 'Authentication credentials were not provided.} I am a beginner in Javascript so I wll hope you can understand. I dont know how to put the authentication credentials in my fech. Views.py class PlayersView(ModelViewSet): permission_classes = [IsAuthenticated] serializer_class = PlayersSerializer queryset = Players.objects.all() def list(self, request): queryset = Players.objects.all() serializer = PlayersSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = Players.objects.all() qs = get_object_or_404(queryset, pk=pk) serializer = PlayersSerializer(qs) return Response(serializer.data) Urls.py router = DefaultRouter() router.register('players',views.PlayersView,basename='players') app_name = 'main' urlpatterns = [ path('',include(router.urls)), ] Any idea? -
Constrain unique_together could have conflict with the unique_field in dajngo Class
Basically, I would like to know if there is any conflict using the constrain unique_together as well as the parameter unique=true in one of the fields that belong to the array of the unique_together. it´s because I can´t remove the parameter unique=true of my field because it´s used as a foreigner key in another model. class User(AbstractUser): # User information fiscal_number = models.CharField(max_length=30,unique=True) phone = models.CharField(max_length=15, null=True) email = models.EmailField(max_length=254, verbose_name='email address') class Meta: unique_together = ['fiscal_number', 'email'] As you can see the goal is to make the combination of the fields fiscal_number and email unique -
Why isn't Django Sitemap showing the URLs
I've been trying to make my django sitemaps work for a small blog application. After checking out multiple tutorials, I still can't get the sitemaps work properly. Here's my urls.py: from django.contrib import admin, sitemaps from django.urls import path from django.urls import include from rx import views from django.conf.urls.static import static from django.conf import settings from django.contrib.sitemaps.views import sitemap from rx.sitemaps import Static_Sitemap sitemaps = { 'static': Static_Sitemap, } urlpatterns = [ path('ckeditor/', include('ckeditor_uploader.urls')), path('admin/', admin.site.urls), path('', views.index, name='index'), path('blog/', views.blog, name='blog'), path('about/', views.about, name='about'), path('<slug:cat_slug_name>/', views.cat, name='cat'), path('<slug:cat_slug_name>/<slug:post_slug_name>/', views.blog_post, name='blog_post'), path('sitemap.xml/', sitemap, {'sitemaps': sitemaps}), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here's my settings.py: """ Django settings for rankxero project. Generated by 'django-admin startproject' using Django 3.2.9. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') MEDIA_DIR = os.path.join(BASE_DIR, 'media') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! … -
Django annotate queryset by predicate and count results
I have two models: class Game(models.Model): id = models.AutoField(primary_key=True) class Score(models.Model): id = models.AutoField(primary_key=True) game = models.ForeignKey(Game, related_name="score", on_delete=models.CASCADE) first_score = models.IntegerField(blank=True) second_score = models.IntegerField(blank=True) is_rusk = models.BooleanField(blank=True) And I got a queryset of Game objects: [ { "id": 314317035, "score": [ { "first_score": 5, "second_score": 1, "is_rusk": false } ] }, { "id": 311298177, "score": [ { "first_score": 5, "second_score": 2, "is_rusk": false } ] }, { "id": 310278749, "score": [ { "first_score": 5, "second_score": 2, "is_rusk": false } ] }, { "id": 309866238, "score": [ { "first_score": 5, "second_score": 0, "is_rusk": true } ] }, { "id": 307926664, "score": [ { "first_score": 5, "second_score": 0, "is_rusk": true } ] }, { "id": 306047964, "score": [ { "first_score": 4, "second_score": 5, "is_rusk": false } ] }, { "id": 304881611, "score": [ { "first_score": 5, "second_score": 3, "is_rusk": false } ] }, { "id": 304468136, "score": [ { "first_score": 5, "second_score": 2, "is_rusk": false } ] }, ] I want to annotate this queryset with rusks_cnt, it will be count of objects with is_rusk=True, If there is a way to not add this to every object, just as one field, that would be good too. I think easiest way to … -
Patch request not patching - 403 returned - django rest framework
I'm trying to test an API endpoint with a patch request to ensure it works. I'm using APILiveServerTestCase but can't seem to get the permissions required to patch the item. I created one user (adminuser) who is a superadmin with access to everything and all permissions. My test case looks like this: class FutureVehicleURLTest(APILiveServerTestCase): def setUp(self): # Setup users and some vehicle data we can query against management.call_command("create_users_and_vehicle_data", verbosity=0) self.user = UserFactory() self.admin_user = User.objects.get(username="adminuser") self.future_vehicle = f.FutureVehicleFactory( user=self.user, last_updated_by=self.user, ) self.vehicle = f.VehicleFactory( user=self.user, created_by=self.user, modified_by=self.user, ) self.url = reverse("FutureVehicles-list") self.full_url = self.live_server_url + self.url time = str(datetime.now()) self.form_data = { "signature": "TT", "purchasing": True, "confirmed_at": time, } I've tried this test a number of different ways - all giving the same result (403). I have setup the python debugger in the test, and I have tried actually going to http://localhost:xxxxx/admin/ in the browser and logging in manually with any user but the page just refreshes when I click to login and I never get 'logged in' to see the admin. I'm not sure if that's because it doesn't completely work from within a debugger like that or not. My test looks like this (using the Requests library): def … -
My pyrogram app don't start in Django framework view function, but in isolated module it works very well
When I create Client instance of Pyrogram library in single module (isolated .py file) and run that file my app works properly. app = Client("app", api_id=MY_ID, api_hash=MY_API_HASH) But in django view the exactly same code don't work. I create Client instance, but my project freezes after calling any methods (like start, stop, send_message ...). Are there any peculiarities when starting pyrogram app in Django framework? -
Returning queryset as json in Django
I wanted to get your advice. I have the below, which returns the data I want. However, so that I can use ajax to update the page without refresh, I need to be able to return the results as JSON. I keep getting erros that the query result is not serializable. Does anyone know how to do it? Thanks a lot! open_tasks = skills.objects.filter(creator=request.user).raw(''' SELECT *, round((closed_points/(open_points + closed_points)*100),2) as points_pct, round((closed_count/(open_count + closed_count)*100),2) as closed_pct from ( SELECT id, coalesce(sum(open_points),0) as open_points, coalesce(sum(closed_points),0) as closed_points, coalesce(sum(open_count),0) as open_count, coalesce(sum(closed_count),0) as closed_count from ( SELECT id, case when status = 'open' then sum(points) end as open_points, case when status <> 'open' then sum(points) end as closed_points, case when status = 'open' then sum(count) end as open_count, case when status <> 'open' then sum(count) end as closed_count from ( SELECT category as id, status, sum(cast(points as int)) as points, count(*) as count FROM voxi_skills WHERE creator = %s group by category, status)s group by id, status)p group by id)j ''', [request.user.username]) -
How to modify the pdf in the server, django
Good dat to all. I have a django project running in a linux server with apache2. What my code does is to replace a PDF file. When the user fills the form, it is received, then replace the corresponding fields in the file and save() it. Locally it works perfectly, but when I try it on the server, the pdf is not overwritten because it always displays the same PDF instead of the modified one. Since locally works correctly, I thought it would be maybe the routes, or the permissions. The first option i already checked the routes, they are correct, so it must not be that. The other thing that can be not letting to overwrite, are the permissions so what I did, was to give permissions chmod 777 to the PDF file to see if it works, but it didnt. It still the file doesn't change. This code is to add the corresponding fields to the pdf def generate_attached_standard_pdf(attachment_data): try: name=attachment_data['creditor'] w, h = letter # DEFINE PDF CONFIGURATIONS c = canvas.Canvas('anexoA.pdf', pagesize=letter) c.setTitle('Anexo {}'.format(name)) pdfmetrics.registerFont( TTFont('Lato', BASE_DIR +"/recursos/fonts/Lato-Regular.ttf"), ) pdfmetrics.registerFont( TTFont('Lato-Bold', BASE_DIR+"/recursos/fonts/Lato-Bold.ttf"), ) c.save() return { 'success': True, 'message': 'PDF CREADO' } except Exception as e: print(e) … -
Apache2 configurations with WSGIDaemonProcess use domain name not server ip
I deploy three projects Django on the same server each on must work on a subdirectory, they worked correctly this way WSGIDaemonProcess test.com/en threads=5 python-path=/home/api. WSGIProcessGroup test.com/en WSGIDaemonProcess test.com/fr threads=5 python-path=/home/apifr. WSGIProcessGroup test.com/fr WSGIDaemonProcess test.com/ru threads=5 python-path=/home/apiru. WSGIProcessGroup test.com/ru <VirtualHost *:80> ServerAdmin admin@test.com ServerName text.com ServerAlias {server_ip} ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined #WSGIPythonHome /home/api/venv/ WSGIPassAuthorization On WSGIScriptAlias /en /home/api/server/wsgi.py process-group=test.com/en WSGIScriptAlias /tr /home/apifr/server/wsgi.py process-group=test.com/fr WSGIScriptAlias /ru /home/apiru/server/wsgi.py process-group=test.com/ru Alias /api /home/api/server/wsgi.py <Directory /home/api/server/> <Files wsgi.py> AllowOverride All Require all granted </Files> RewriteEngine On RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule (.*) index.html [L] </Directory> I added three Alias for each subdirectory and directory like this one I want to change server_ip with domain name or subdomain to be api.test.com when I change it I get an error 400 , the apache2 log doesn’t show anything -
Display data on a dynamic page
Faced with such a problem, the exercise_new page does not display any form and does not display information from the DB. enter image description here #------------views.py-----------# def comment(request, pk): """Вывод полной статьи """ new = get_object_or_404(Exercise, pk=pk) comment = Comments.objects.filter(new=pk, moderation=True) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): form = form.save(commit=False) form.user = request.user form.new = new form.save() return redirect(exercise, pk) else: form = CommentForm() return render(request, "ProManager/exercise_new.html", {"new": new, "comments": comment, "form": form}) #---------models.py------------# class Comments(models.Model): """Ксласс комментариев к новостям """ user = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name="Пользователь", on_delete=models.CASCADE) new = models.ForeignKey( Exercise, verbose_name="Новость", on_delete=models.CASCADE) text = models.TextField("Комментарий") created = models.DateTimeField("Дата добавления", auto_now_add=True, null=True) moderation = models.BooleanField("Модерация", default=False) class Meta: verbose_name = "Комментарий" verbose_name_plural = "Комментарии" def __str__(self): return "{}".format(self.user) #-----------------forms.py-------------# class CommentForm(ModelForm): """Форма комментариев к статьям """ class Meta: model = Comments fields = ('text', ) #----------------exercise_new.html----------------# <h4>Комментарии</h4> {% for comment in comments %} Пользователь - {{ comment.user }}<br> {{ comment.text }} <br> Добавлен - {{ comment.created }}<br><br> {% endfor %} {% if user.is_active %} <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Отправить</button> </form> {% else %} <h4>Что бы оставить комментарий авторизуйтесь</h4> {% endif %} ---------------------urls.py------------------ urlpatterns = [ path('exercise/<int:pk>/', ExerciseDetailView.as_view(), name='exercise-new'), path('project/<int:pk>/', ProjectDetailView.as_view(), name='project-new'), …