Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"detail": "Authentication credentials were not provided." to admin
I have my token for admin, the booking entries is allowed in Insomnia but would not be allowed DRF display. I am missing something please? Is there way to provide the token for it to be allowed? #view.py from django.shortcuts import render, redirect from django.contrib.auth.models import User from rest_framework import viewsets from .models import Booking, Menu from .serializers import BookingSerializer, MenuSerializer, UserSerializer from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import TokenAuthentication from rest_framework import generics from datetime import datetime from django.views.decorators.csrf import csrf_exempt from django.db.models import Sum from django.contrib import messages def home(request): return render(request, 'index.html') def about(request): return render(request, 'about.html') class UserRegistrationView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer class BookingViewSet(viewsets.ModelViewSet): queryset = Booking.objects.all() serializer_class = BookingSerializer permission_classes = [IsAuthenticated] authentication_classes = [TokenAuthentication] settings.py REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], 'DEFAULT_AUTHENTICATION_CLASS': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication' ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } -
Django Templates with Vue
I'm trying to integrate vue-components into django-templates. The basic setup did work, but I'm stacked with a component which needs an import itself. Here is the component (vue/dropdown.html): <div id="app"> <template> ... </template> </div> <script setup> import { computed, ref } from 'vue' import {CheckIcon, ChevronUpDownIcon} from '@heroicons/vue/20/solid' const query =ref('') const selectedPerson = ref(null) ... var app = new Vue({ delimiters: ['[[', ']]'], el: '#app', data: { message: 'Hello Vue!', }, }); </script> So, the 2 imports: import {computed, ref} from Vue import {CheckIcon, ChevronUpDownIcon} from '@heroicons/vue/20/solid' are triggering the error in the browser's console: Cannot use import statement outside a module What is the proper way to use the imports? I'm calling the dropdown.html from base.html: <html lang="{{ LANGUAGE_CODE }}"> <head>...</head> <body> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> {% include 'vue/dropdown.html' %} </body> </html> -
Django form not sending data to admin
I have a form users can fill out to reserve a table at a restaurant. However when they submit the form no data gets sent to the admin side. I have watched some tutorials and read other posts on this site and nothing seems to fix it. I feel like it is something so small but i just cant figure it out. VIEWS.PY from django.shortcuts import render, get_object_or_404 from django.views import generic, View from .models import Book from .forms import BookForm from django.http import HttpResponseRedirect def Book(request): """ Renders the book page """ if request.user.is_authenticated: form = BookForm(request.POST or None) context = { "form": form, } else: return HttpResponseRedirect("accounts/login") book_form = BookForm(data=request.POST) if book_form.is_valid(): instance = book_form.save(commit=False) instance.save() else: book_form = BookForm() return render( request, "book.html", { "book_form": BookForm(), } ) MODELS.PY from django.db import models from django.contrib.auth.models import User from django.core.validators import MinValueValidator from cloudinary.models import CloudinaryField class Book(models.Model): name = models.CharField(max_length=50) number_of_guests = models.PositiveIntegerField(validators=[MinValueValidator(1)]) date = models.DateTimeField() email = models.EmailField() requests = models.TextField(max_length=200) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) approved = models.BooleanField(default=False) class Meta: ordering = ['date'] def __str__(self): return f"{self.date} for {self.name}" FORMS.PY from .models import Book from django import forms class BookForm(forms.ModelForm): class Meta: model = … -
Get multiple columns data from extra query in Django
I have two models as below: class Model1(models.model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) filename = models.CharField(max_length=255) class Model2(models.model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) filename = models.CharField(max_length=255) I would like to get the related model2 which have the same column value in filename as that of model1. My solution was to use either Subquery or Extra. The problem with Subquery is that it allows only one column to be queried but what I want is a dict object of all the columns of model2 related to model1. They do not have a foreignkey relation to use select_related. So I tried to use extra but again I am getting the multiple columns error. How can I solve this problem? My code is as below: model1_objs = Model1.objects.filter(id=given_id).extra( select={ "model2_obj": f"SELECT * FROM model2 WHERE filename = model1.filename AND id = '{model2_id}'" } ) This does not work. -
record user;s voice with js and post to django server
i want to record a voice from the user and post it to server side (django) the important thing is i don't want save voice with models , but i want to convert voice to text with python libraries for this, i use this plugin, but my the recorded voice is stored in blob format and in an audio tag. i can't send blob to server. I also used Recorder.js, but it is also saved as a blob -
Accessing/Working with rabbitmq Queue using python
I am trying to create an page to monitor RabbitMQ Queues in our application. I want to know how I can perform following operations. I am using Python and Django for the back-end. How to get the number of queues and read their data. How to Purge/Delete the tasks under queue. How to get size (count) of the queue. Thanks in Advance. -
How to pass a paragraph having multiple ( " ) and ( ' ) from a variable inside a string in django?
I want to pass a variable having a paragraph in which there are multiple uses of ( " ) and ( ' ). I am passing this variable inside another string which is an sql query in a django project. For example - variable1 = input() command = "insert into table 1 values{"{}"}".format(variable1); So in avbove code iif the user is entering some data with no ( " ) or ( ' ) it is working fine but when there is presence of these it just throws error. Ho can I get independent of these symbols inside my input data and pass it as a query ? I tried using raw input but when it comes to fetching data from a database and then passing that data containig multiple symbols of ( " ) and ( ' ) it just throws erre. What I want is that it just ignore all these symbols present in my variable . -
Problems with creating a type protocol for Django user class
I have a function that operates on users, but in one of the projects that uses it we don't use Django user. We have a dataclass that pretends to be a user. Problems started when I was trying to type this function. I couldn't use AbstractBaseUser as the user type, because that would obviously not work in this project with dataclass user. However, Python has a solution for such problems - protocols! I quickly created a user protocol containing all features I used in the function: class ManagerProtocol(Protocol): def get(self, **kwargs: Any) -> UserProtocol: ... class UserProtocol(Protocol): objects: ManagerProtocol class DoesNotExist(Exception): ... and adjusted our dataclass user to follow this protocol: class FakeManager: def get(self, **kwargs: Any) -> StaticUser: return StaticUser(user_id=kwargs.get('user_id', '')) @dataclass(frozen=True) class StaticUser: user_id: str is_authenticated: bool = True objects = FakeManager() class DoesNotExist(Exception): pass and then I ran mypy and got this: error: Argument 1 to "function" has incompatible type "StaticUser"; expected "UserProtocol" [arg-type] note: Following member(s) of "StaticUser" have conflicts: note: DoesNotExist: expected "Type[UserProtocol.DoesNotExist]", got "Type[StaticUser.DoesNotExist]" note: objects: expected "ManagerProtocol", got "FakeManager" I've read some articles on the web and the solution was clear - use properties instead of class members! class UserProtocol(Protocol): @property def objects(self) … -
Celery OperationalError [Errno 111] Connection refused
I have one important question that have been worrying me for 2 last days. I have django, postgres and rabbitmq containers in docker. I want to connect celery with rabbitmq but if I do it using django container (docker-compose exec web celery -A myshop worker -l info), it doesn`t connect at all. What only I have tried - nohow. I got the 111 error connection refused. Elif I do it straightforward (celery -A myshop worker -l info) it works and connects but as soon as the task is completing I got the same issue - error 111. Please help me. services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db rabbitmq: image: rabbitmq:3.11.8-management-alpine ports: - "5672:5672" - "15672:15672" volumes: - ./.docker/rabbitmq/data/:/var/lib/rabbitmq/ init.py from .celery import app as celery_app __all__ = ['celery_app'] celery.py import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings') app = Celery('myshop') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() tasks.py from celery import shared_task from django.core.mail import send_mail from .models import Order @shared_task def … -
Using JQuery triggers Uncaught ReferenceError: $ is not defined
I use JQuery in my django project quite often, and it hasn't been a problem so far. Even in my current project, I use it on multiple pages. But on one page, I get this error in the console: Uncaught ReferenceError: $ is not defined This is my JQuery Code: $(document).ready(function(){ console.log("hello") }) This is what I imported in my base.html: <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> Like I said I used JQuery a lot in this project so and it worked fine so far. I also did extend Base.html properly. What could be the problem? -
Docker is taking wrong settings file when creating image
I have Django application where my settings are placed in folder named settings. Inside this folder I have init.py, base.py, deployment.py and production.py. My wsgi.py looks like this: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp_settings.settings.production") application = get_wsgi_application() Problem Every time I create image Docker is taking settings from development.py instead of production.py. I tried to change my setting using this command: set DJANGO_SETTINGS_MODULE=myapp_settings.settings.production It works fine when using conda/venv and I am able to switch to production mode however when creating Docker image it does not take into consideration production.py file at all. Question Is there anything else I should be aware of that causes issues like this and how can I fix it? -
Django - Annotating, Filtering and Sorting on a none to many relationships doesn't work
I am working on a table that display a list of orders with the option to filter and to sort depending either to direct attribute of the order or indirectly to attribute of related models. The two models in question are Order and Block. An Order can have none too many Blocks associated to it and Block always have one unique order. class Order(CustomBaseModel): date_of_order = models.DateField(default=timezone.now, verbose_name="Date of order" ... class Block(CustomBaseModel): ... order = models.ForeignKey(Order, on_delete=models.CASCADE) ... To be able to filter orders with or without block, I annotate my queryset using the following: order_queryset = Order.objects.all().annotate( is_material_available=Case( When(block__isnull=False, then=Value(True)), default=Value(False), output_field=BooleanField() ), ) and then use the filter option on the new annotation: is_material_available = self.data["is_material_available"] if is_material_available == "True": order_queryset = order_queryset.filter(is_material_available=True) elif is_material_available == "False": order_queryset = order_queryset.filter(is_material_available=False) Using this method result in those behaviors: is_material_available=="True": Only fetch orders which have an orders, which is great, but completly disrupts the pagination. Let's say the number of order per page is 8, it will create page with only one order, or more. Also some orders are present in different pages. is_material_available=="False": Fetch orders with and without blocks associated to it, but the pagination works fine. I … -
Duplicate Media(CSS, JS) load when using class inheritance in django components
I am using django-components. Common parts are inherited from parent classes and child classes are registered as components. It is written as follows components.py from django_components import component class Parent(component.Component): def get_context_data(self, data): return { "data": data, } @component.register("aaa") class ChildA(Parent): template_name = "/aaa.html" class Media: css = ["css/my.css", "css/test/aaa.css"] js = "js/common.js" @component.register("bbb") class ChildB(Parent): template_name = "/bbb.html" class Media: css = ["css/my.css", "css/test/bbb.css"] js = "js/common.js" When I call the aaa component in a template, I want to call only the Media (css, js) associated with the ChildA class. xxx.html {% component "aaa" data=""%} However, when we check the expanded HTML, even the Media of ChildB is called as shown below. Expanded final HTML <script src="js/common.js" ></script> <script src="js/common.js" ></script> <link href="css/my.css" media="all" rel="stylesheet"> <link href="css/test/aaa.css" media="all" rel="stylesheet"> <link href="css/my.css" media="all" rel="stylesheet"> <link href="css/test/bbb.css" media="all" rel="stylesheet"> What should I do to avoid calling Media of a component of another class that has the same parent? We have already confirmed that common.js is called only once when ChildB js is specified empty. @component.register("bbb") class ChildB(Parent): template_name = "/bbb.html" class Media: css = ["css/my.css", "css/test/bbb.css"] js = "" -
How to disable the Authorize Button in DRF-Spectacular Swagger Django
Im working on drf-spectacular . My Question is how to desable Authorize Button in drf-spectacular. enter image description hereIs there any settings? "APPEND_COMPONENTS": { "securitySchemes": {"ApiKeyAuth": None} } By using above setting I'm getting error -
Store dynamic choice field form from api call to be able to pass the verification in post request
I'm working on an app that can display the events coming from a google calendar. To be able to do this, the user need to fill a form with the start date, end date, timezone and select a calendar. I'm new to Django and it's ok to make a form with date, text, checkbox but regarding the choice field, it fail because the values are not present in the choice list. Select a valid choice. johndoe@gmail.com is not one of the available choices. This is normal because the values will change according to the user. For that I'm calling the google calendar api before showing the page at GET request. I tried to add it to the form but of course, it doesn't stay while the post method is called. Is there a way to store the value without using the session or database? How do you manage dynamic choice field that isn't coming from database? Here is my code: form.py from django import forms class events_filters(forms.Form): start = forms.DateField(label='Start date') end = forms.DateField(label='End date') calendar = forms.ChoiceField(label='Select calendar') timezone = forms.BooleanField(label="Show timezone") view.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from googleapiclient.discovery import build from google.oauth2.credentials import Credentials … -
pytest-django: allow test to update database
I have a lot of little "tests" I use manually, that is, I run them on demand. Some of them I want to alter the database. I have for a long time used pytest for these. (situation is caching production data in dev environment for some specific testing and debugging) I have been convinced to add pytest-django, which has some great features. It has hijacked my ad-hoc tests; immediately, they can't access or update the database. Database access and allowing updates is documented and I was quickly able to half solve it: enable database access, update the database during the test. But all my changes are backed out. My solution to do that may be bad, well obviously it only half works. I have added this file: conftest.py in what seems to be the correct place (same directory as the tests). with contents: import pytest from django.conf import settings pytest_plugins = [ "tests.fixtures.environments", "tests.fixtures.initial_data", ] @pytest.fixture(scope="session") def django_db_setup(): settings.DATABASES["default"] = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'django_api_sync', 'PASSWORD': 'devpassword', 'NAME': 'django_api_sync', 'HOST': 'db', 'PORT': 5432, } settings.DATABASES["dear_analytics"] ={ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'django_api_sync', 'PASSWORD': 'devpassword', 'NAME': 'dear_analytics', 'HOST': 'db', 'PORT': 5432, } @pytest.fixture def db_no_rollback(request, django_db_blocker): django_db_blocker.unblock() request.addfinalizer(django_db_blocker.restore) and then I decorate my … -
AttributeError: Got AttributeError when attempting to get a value for field `comments` on serializer `Post`
**In my blog app when i used to retrive all the posts I got this error. ** AttributeError: Got AttributeError when attempting to get a value for field comments on serializer Post. The serializer field might be named incorrectly and not match any attribute or key on the Post instance. Original exception text was: 'Post' object has no attribute 'comments'. I attached my code below. Help me how to get rid out of this. models.py from django.db import models from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import User #Abstract Start class TimeStamp(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Selection(TimeStamp): name = models.CharField(max_length=100) class Meta: abstract = True ordering = ['name'] #Abstract End class Post(Selection): # name = title author = models.ForeignKey(User,on_delete=models.CASCADE) body = models.TextField(_("content")) slug = models.SlugField(_("slug")) likes = models.IntegerField(_("likes"),default=0) def __str__(self): return self.name class Comment(TimeStamp): user = models.ForeignKey(User,on_delete=models.CASCADE) content = models.TextField(_("comments")) likes = models.IntegerField(_("likes"),default=0) post = models.ForeignKey(Post,on_delete=models.CASCADE) def __str__(self): return self.content serializers.py from django.contrib.auth.models import User from rest_framework import serializers from . import models class UserSr(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') class Comment(serializers.ModelSerializer): user = UserSr() class Meta: model = models.Comment exclude = ['created_at','updated_at'] class Post(serializers.ModelSerializer): author … -
Django + nginx + gunicorn error while IMAGE PROCESSING [ upstream prematurely closed connection while reading response header from upstream ]
I am using Django, and I believe it is not an issue from Django side. Simply upload an image (~500kb) using a Model Form, and using OpenCV just convert it into the grayscale (plus many more if this works). I have configured using nginx and gunicorn and all functionalities works except file uploading and editing. ERROR: upstream prematurely closed connection while reading response header from upstream, client: 174...194, server: .com, request: "POST / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: ".com", referrer: "http://****.com/" Configuration----------------------- /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=shubham Group=www-data WorkingDirectory=/home/shubham/editor/src ExecStart=/home/shubham/editor/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --timeout 600 \ --bind unix:/run/gunicorn.sock \ src.wsgi:application Restart=always RestartSec=3 [Install] WantedBy=multi-user.target /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/nginx/nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; client_max_body_size 10000M; proxy_connect_timeout 300s; proxy_read_timeout 300s; client_body_buffer_size 10000M; proxy_max_temp_file_size 10000M; send_timeout 300s; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; # … -
How to edit api and add changes in django
I'm sending api like: [ { "id": 1, "name": "Burger", "name_ru": "Burger", "name_en": "Burger", "img": null, "parent_category": 1 }, { "id": 3, "name": "Pizza", "name_ru": "Pizza", "name_en": "Pizza", "img": null, "parent_category": 1 } ] how can edit this api? I want to send parent_category with id and name, not just id. My views.py: class TestList(APIView): def get(self, request, pk, format=None): cc = Child_Category.objects.filter(parent_category_id = pk) serializer = ChildCategorySerializer(cc, many=True) return Response(serializer.data) My models.py: class Parent_Category(models.Model): name = models.CharField(max_length=255) name_ru = models.CharField(max_length=255) name_en = models.CharField(max_length=255) img = models.ImageField(blank=True, null=True) def __str__(self): return self.name_en class Meta: verbose_name_plural = 'Parent Categories' class Child_Category(models.Model): name = models.CharField(max_length=255) name_ru = models.CharField(max_length=255) name_en = models.CharField(max_length=255) parent_category = models.ForeignKey(Parent_Category, on_delete=models.CASCADE) img = models.ImageField(blank=True, null=True) def __str__(self): return self.name_en class Meta: verbose_name_plural = 'Child Categories' -
{{minMaxPrice.price__min}}-{{minMaxPrice.price__max}}
Learning Django and now creating price filter. When min and max price is statick, all good, when chenging filter to dinamic, nothin working. Static range from 0 to 1000 working: filter.html {% load static %} <script type="text/javascript" src="{% static 'product-filter.js' %}"></script> <h3 class="mb-4 border-bottom pb-1">Фильтры</h3> <!-- Price Filter --> <div class="card mb-4"> <h6 class="card-header">Цена</h6> <div class="list-group list-group-flush"> <li class="list-group-item"> <input type="range" id="rangeInput" min="0" max="1000" oninput="maxPrice.value=this.value" /> <p>{{minMaxPrice.price__min}}-{{minMaxPrice.price__max}} </p> </li> <li class="list-group-item"> Максимальная цена: <input type="number" onkeyup="rangeInput.value=this.value" id="maxPrice" min="0" max="1000" /> </li> </div> </div> <!-- Filter 1 --> <div class="card mb-4"> <h6 class="card-header">Категории</h6> <div class="list-group list-group-flush"> {% for cat in cats %} <li class="list-group-item"> <input class="filter-checkbox" data-filter="category" value="{{cat.category__id}}" type="checkbox" />&nbsp; {{cat.category__title}} </li> {% endfor %} </div> </div> template_context.py from .models import Product from django.db.models import Min, Max from django.db.models import FloatField def get_filters(request): cats = Product.objects.distinct().values('category__title', 'category__id') minMaxPrice = Product.objects.aggregate(Min('price', output_field=FloatField()), Max('price', output_field=FloatField())) data = { 'cats': cats, 'minMaxPrice': minMaxPrice, } return data` It's showing filter from 0 to 1000 and showing title range from my prices. Static range from 0 to 1000 Dinamic range not working: filter.html {% load static %} <script type="text/javascript" src="{% static 'product-filter.js' %}"></script> <h3 class="mb-4 border-bottom pb-1">Фильтры</h3> <!-- Price Filter --> <div class="card mb-4"> <h6 class="card-header">Цена</h6> … -
VueJS - How can I check if the user id was changed in local storage so I can check if the token is valid
I have Django back end and a Vue front end. People are able to log in. The user id and token is fetched from the back end and stored in localstorage after successful login. This id is then used in my Vue store so the user can get all the data associated with his account. While logged in you can access all the functionality and see the content associated with user (let's say ID = 1). Authorization with the back end happens through the token being sent in the request headers by the front end. Is this correct? But the back end (Django) does not check that the token being sent in the header belongs to a specific user, every time a requests happens am I right or wrong? Because after logging in I can use every end point that requires authentication and I get the data fine. If I delete the token then obviously that stops from happening. If I change the ID in local storage then I can browse the data of another user because according to Django the token is still valid, because from my observation the token in the request headers is not checked against a … -
Django - What's the difference between "exclude", "__ne", and "~Q"?
In the Django model querySet, I learned three ways to filter 'is not equal'. 1. exclude Model.objects.exclude(a='abc') 2. __ne Model.objects.filter(a__ne='abc') 3. ~Q Model.objects.filter(~Q(a='abc')) Are the above cases mean the same thing? -
Adding checkbox in Django table
I want to create a checkbox table in Django that I can click and confirm. After which, the data will be posted into javascript to be sent to a python function. I have tried different methods but can't seem to work. <doctor.html> {%extends "doctor.html" %} {% block emr %}active{% endblock %} {% block mainbody %} {% verbatim %} <div id="app2" class="container"> <div class="department-table"> <el-table :data="list" stripe style="width: 100%"> <el-table-column prop="id" label="Index" width="180"> </el-table-column> <input type="checkbox"> <el-table-column prop="name" label="Department" width="180"> </el-table-column> <el-table-column prop="registration_fee" label="Registration Fee"> </el-table-column> <el-table-column prop="doctor_num" label="Staff Count"> </el-table-column> </el-table> </div> <div class="filter-container"> <div class="filter-item"> <el-button @click="onAddMedicine">Add</el-button> </div> </div> </div> {% endverbatim %} <script> new Vue({ el: '#app2', data() { return { list: [] } }, mounted() { this.getDepartmentList() }, methods: { getDepartmentList() { // Obtain department list axios.post(ToDJ('departmentList'), new URLSearchParams()).then(res => { if (res.data.code === 0) { console.log(res.data.data) this.list = res.data.data } else { this.NotifyFail(res.data.data) } }) }, // Success notification NotifySuc(str) { this.$message({ message: str, type: 'success' }) }, // Error notification NotifyFail(str) { this.$message({ message: str, type: 'warning' }) } } }) </script> {% endblock %} Output that I obtain: I am new to web development. Hope that someone can assist. Thank you! -
Can Django STATIC_ROOT point to path on another server?
I am using Django 4.0.1 in my project, and right prior to deploying my site, I am faced with the issue of handling my static files. Due to the limit of my server, I have decided to instead serve these static files via CDN. I have already configured my STATIC_URL option in settings.py: STATIC_URL = 'assets/' I am aware that in the Django documentation, they say that this url refers to the static files located in STATIC_ROOT. Of course, normally the latter is an absolute path on your server where the collectstatic command collects the static files and put them there, but I am wondering if I can configure this STATIC_ROOT to point a path which is not on my server. To be precise, I want to know whether I can point STATIC_ROOT to my CDN storage. In that way I can still use STATIC_URL to refer to my static assets, while being able to serve them via CDN. -
Django on apache: Could not find platform dependent libreries <exe_prefix>
I'm trying to deploy a django app in an Apache Server (Wamp) using a virtual environtment, but getting that error. Everything is going well, the problem seems to be happen in the wsgi.py file. The wsgi.py never start the venv so this never start the app. Here is my httpd-vhost.conf: ServerName my.app.name ServerAdmin myadminname@localhost.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined WSGIPassAuthorization On Alias /static C:/wamp/apache2/htdocs/<myappname>/frontend/build/static/ <Directory "C:/wamp/apache2/htdocs/<myappname>/frontend/build/static/"> Allow from all Require all granted </Directory> <Directory "C:/wamp/apache2/htdocs/<myappname>/<mysetting's django folder>"> <Files wsgi.py> Allow from all Require all granted </Files> </Directory> #WSGIDaemonProcess <my.app.group> python-path="C:/wamp/apache2/htdocs/<app.name>/env/Lib/site-packages" #WSGIProcessGroup <my.app.group> WSGIScriptAlias / "C:/wamp/apache2/htdocs/<app.name>/<settings folder>/wsgi.py" </VirtualHost> Here is my wsgi.py file: import os import sys # Add the virtual environment path to the system path sys.path.append('C:/wamp/apache2/htdocs/<app.name>/env/Lib/site-packages') # activate_this = 'C:/wamp/apache2/htdocs/<app.name>/env/Scripts/activate_this.py' # execfile(activate_this, dict(__file__=activate_this)) # exec(open(activate_this).read(),dict(__file__=activate_this)) # Activate the virtual environment activate_env = 'C:/wamp/apache2/htdocs/<app.name>/env/Scripts/python' exec(open(activate_env, 'rb').read(), {'__file__': activate_env}) # Set the DJANGO_SETTINGS_MODULE environment variable # os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') os.environ['DJANGO_SETTINGS_MODULE'] = 'app.settings' # Import the Django application from the Django project from django.core.wsgi import get_wsgi_application application = get_wsgi_application() In the wsgi.py file there are two ways I found for activate the venv. The venv don't have the activate_this.py file but there was an answer I found answer-here that say you simply copying …