Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store unknow number of entries in django sqlite module
I have the following form which the user select a product and quantity. Product_name Quantity product1 3 product2 2 + Add Product And a button to add a extra field in the table, the button can be used any number of times to add extra products. How can i store the users orders in the database? Result: a database with fields of users orders. -
How to count the number of objects depending on the status?
I have the code which counts the number of elements of each type. Views.py from django.db.models import Count class HomeView(ListView): model = TypeCartridge template_name = 'home.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) type_counts = TypeCartridge.objects.values('type').annotate(total=Count('type')) context['type_counts'] = type_counts return context home.html: <div> {% for cartridge in object_list %} <div> <p>Number {{ cartridge.num}}: {{ cartridge.type }}, status {{ cartridge.status }}</p> </div> {% endfor %} <h2>Type Counts</h2> <ul> {% for type_count in type_counts %} <li>{{ type_count.type }} - {{ type_count.total }}</li> {% endfor %} </ul> </div> For example, I have a table: num type Status 0000001 Samsung Installed 0000002 Samsung NotInstalled 0000003 Xerox Installed 0000004 Brother NotInstalled 0000005 Brother NotInstalled 0000006 Brother NotInstalled 0000007 HP Installed 0000008 HP Installed And the result of my code is the following: Samsung - 2 Xerox - 1 Brother - 3 HP - 2 But I would like the code to count only elements with status "Installed". The result should be : Samsung - 1 Xerox - 1 HP - 2 How to improve the code? -
how to convert DateField field while returning a filtered result in DJANGO
I have the following table in django: models.py class Activity(models.Model) name = models.CharField(max_length=50) date_created = models.DateField() here is the way i create an instance of that table from datetime import date Activity.objects.create(name="Foo", date_created=str(date.today())) I know that auto_now_add=True can be used to store the date but at the moment it's out of the question and I need to find a solution exactly like the models is above. Is there a way to format the date_created field while querying all instances of the table Activity using .values() below in the views.py views.py activity = Activity.objects.filter(name="soccer").values() I am currently getting the following error: TypeError: Object of type date is not JSON serializable activity = Activity.objects.filter(name="soccer").values() -
Issue with complex lookup in Django
Below are my Django models. I'd like to write signal that will do the following: User updates project that contains let's say 3 Spider objects. Each Spider object contains config_file so signal should get list of all Spider objects and update group from all config files from the list. In the end when the user updates group name in Project all config_files should change group name as well. class Project(models.Model): name = models.CharField(max_length=200, default="") user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') is_shared = models.BooleanField(default=False) group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True, blank=True, default=1) class Spider(models.Model): name = models.CharField(max_length=200, default="", unique=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') project = models.ForeignKey(Project, on_delete=models.CASCADE, blank=True, null=True, related_name='project_spider') config_file = models.ForeignKey(BaseFileModel, on_delete=models.SET_NULL, null=True, default='') class BaseFileModel(models.Model): file = models.FileField(upload_to=custom_upload_files, null=True, default='') group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True, blank=True, default=1) version = models.IntegerField(default=1) I tried to write pre_save signal but it doesn't work as expected because file field in BaseFileModel is null after spider.config_file.save() and not all config files have group updated. The problem I have is that there is no direct connection between BaseFileModel and Project and I am not sure how to write lookup/query to update all config files after updating project group. @receiver(pre_save, sender=Project) def update_spiders_group(sender, instance, … -
how do i prepopulate a dynamic html template for updating a instance
I'm trying to prepopulate the text fields in a form template with an existing instance, I can select the instance and can even user {{instance}} to see the variables but unfortunately can't figure out how to fill in the fields with the instance vars. If i do instance.cpacity for example it will display the correct value but in every field, and as this must be dynamic i need to make it so that each field has its own text box and is prepopulated, ive managed to do this with it being dynamic for "create "but i am struggling with this Sorry for the spelling punctuation and grammar, I am dyslexic Template.html as you can see the {{instance}} in the middle is where my input would be views.py my example input in views.py again i tried using the instance in the context but i dont know what html functions can help me get the neccesary variables in the loop! -
Custom header "X-API-Version" throws CORS error Django REST framework
I tried to add a custom header called "X-API-Version" to check if the front-end is up to date, but despite following the documentation instructions I got a CORS error. Access to XMLHttpRequest at 'http://192.168.5.39:8001/api/host/login/' from origin 'http://localhost:9000' has been blocked by CORS policy: Request header field x-api-version is not allowed by Access-Control-Allow-Headers in preflight response. I already installed the django-cors-headers package, added it to INSTALLED_APPS, added 'corsheaders.middleware.CorsMiddleware' and 'django.middleware.common.CommonMiddleware' in MIDDLEWARE and I also added x-api-version to CORS_ALLOW_HEADERS and CORS_ORIGIN_ALLOW_ALL = True but the error still persists. What could I do to prevent this error from happening? Is there another way to add a custom header? Thanks for helping Here is the settings file: from corsheaders.defaults import default_headers from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. import django.core.mail.backends.smtp BASE_DIR = Path(_file_).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DEBUG', False) EMAIL_BACKEND = django.core.mail.backends.smtp.EmailBackend SERVER_EMAIL = EMAIL_HOST_USER # VARIAVEIS DE AMBIENTE API VIASAT IXC_TOKEN = os.environ.get( 'TOKEN', '*' ) IXC_API = … -
rest_framework and Django urlpatterns for api_root raising 500 Internal Server Error
Using rest_framework with Django to create the REST API for my application. But when I load the webpage (GET /api/v1/) on my browser I get a 500 Internal Server Error with the following output: AssertionError at /api/v1/ Cannot apply DjangoModelPermissionsOrAnonReadOnly on a view that does not set `.queryset` or have a `.get_queryset()` method. Request Method: GET Request URL: http://localhost:8000/api/v1/ Django Version: 4.1.7 Exception Type: AssertionError Exception Value: Cannot apply DjangoModelPermissionsOrAnonReadOnly on a view that does not set `.queryset` or have a `.get_queryset()` method. Exception Location: D:\projects\warehauser\env\lib\site-packages\rest_framework\permissions.py, line 208, in _queryset Raised during: main.views.api_root Python Executable: D:\projects\warehauser\env\Scripts\python.exe Python Version: 3.10.6 Python Path: ['D:\\projects\\warehauser\\warehauser', 'C:\\Users\\omega\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\omega\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\omega\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\omega\\AppData\\Local\\Programs\\Python\\Python310', 'D:\\projects\\warehauser\\env', 'D:\\projects\\warehauser\\env\\lib\\site-packages'] Server time: Fri, 24 Mar 2023 23:42:41 +1100 Here is my urls.py # urls.py from django.urls import path, include from . import views from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ path('', views.home, name='home',), path('api/v1/', views.api_root), path('api/v1/products/', views.ProductList.as_view(), name = 'product-list'), path('api/v1/products/<int:pk>/', views.ProductDetail.as_view(), name = 'product-detail'), path('api/v1/orders/', views.OrderList.as_view(), name = 'order-list'), path('api/v1/orders/<int:pk>/', views.OrderDetail.as_view(), name = 'order-detail'), path('api/v1/users/', views.UserList.as_view(), name = 'user-list'), path('api/v1/users/<int:pk>/', views.UserDetail.as_view(), name = 'user-detail'), ] urlpatterns = format_suffix_patterns(urlpatterns) Here is my views.py # views.py from django.shortcuts import render, redirect from django.contrib.auth import login, logout, authenticate from django.contrib.auth.decorators import login_required from django.http … -
Django Python: How to make the 'feed.html' Paginator an Infinite Scroll?
I'am working on a Social Media Website, I use Django, Python. I would like to make an Infinit Scroll Paginator to have a User-Friendly Surf experience. For now it shows a Select Bar at the end, f.e. 1, 2, 3, Last. How to make an Infinit Scroll Paginator where it laods when you scroll to the end? feed.html {% if posts.has_other_pages %} {% if posts.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{posts.previous_page_number}}">Previous</a> {% endif %} {% for num in posts.paginator.page_range %} {% if posts.number == num %} <a class="btn btn-info mb-4" href="?page={{num}}">{{num}}</a> {% elif num > posts.number|add:'-3' and num < posts.number|add:'3' %} <a class="btn btn-outline-info mb-4" href="?page={{num}}">{{num}}</a> {% endif %} {% endfor %} {% if posts.has_next %} <a class="btn btn-outline-info mb-4" href="?page={{posts.next_page_number}}">Load more Shots</a> <a class="btn btn-outline-info mb-4" href="?page={{posts.paginator.num_pages}}">Last</a> {% endif %} {% endif %} views.py @login_required def posts_of_following_profiles(request): profile = Profile.objects.get(user = request.user) users = [user for user in profile.following.all()] posts = [] qs = None for u in users: p = Profile.objects.get(user=u) p_posts = p.user.post_set.all() posts.append(p_posts) my_posts = profile.profile_posts() posts.append(my_posts) if len(posts)>0: qs = sorted(chain(*posts), reverse=True, key=lambda obj:obj.date_posted) paginator = Paginator(qs, 6) page = request.GET.get('page') try: posts_list = paginator.page(page) except PageNotAnInteger: posts_list = paginator.page(1) … -
I can't run my code, it has an unreachable error
I'm writing a page to introduce myself but I have some errors and don't know how to fix it when runserver it can't query the data. My code can still runserver but after opening the web, I get an error like this Exception Value: Cannot choose from an empty sequence Here is my code thanks. models.py from django.db import models class Person(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() job_title = models.CharField(max_length=100) summary = models.TextField() education = models.TextField() work_experience = models.TextField() skills = models.TextField() profile_picture = models.ImageField(upload_to='images') def __str__(self): return self.name class Education(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) school = models.CharField(max_length=200) degree = models.CharField(max_length=200) major = models.CharField(max_length=200) start_year = models.PositiveIntegerField() end_year = models.PositiveIntegerField() specialization = models.CharField(max_length=200, blank=True) specialization_url = models.URLField(blank=True) certificate = models.CharField(max_length=200, blank=True) certificate_url = models.URLField(blank=True) image = models.ImageField(upload_to='images/', blank=True) def __str__(self): return f"{self.degree} in {self.major} from {self.school}" views.py from django.shortcuts import render from .models import Person import random def self_introduction(request): people = Person.objects.all() person = random.choice(people) context = {'person': person} return render(request, 'self_introduction.html', context) -
Field 'id' expected a number but got''.The above exception (invalid literal for int() with base 10:'') was the direct cause of the following exception
I will learn Python, I tried to do video lessons, but everything works for them, but I get this error I want to write likes using JavaScript. But it gives me an error at this point: post_obj = Post.objects.get(id=post_id) models.py title = models.CharField(max_length=222, verbose_name='Заголовок') text = models.TextField(blank=True, verbose_name='Текст') user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) views = models.ManyToManyField(IpModel, related_name="post_views", blank=True) def total_views(self): return self.views.count() def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title def get_absolute_url(self): return reverse('new_detail', kwargs={'pk': self.pk}) LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike'), ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, max_length=8) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user}-{self.post}-{self.value}" views.py def like_unlike_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) user = Post.objects.get(user=user) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value=='Like': like.value='Unlike' else: like.value='Like' else: like.value='Like' post_obj.save() like.save() return redirect('like_button:main-post-view') urls.py urlpatterns = [ path('', index, name='index'), path('liked/', like_unlike_post, name='like-post-view'), html <div class="content"> <p> {{ obj.content }} </p> <div class="right floated"> <form action="{% url 'like_button:like-post-view' %}" method="POST" class='like-form' id='{{obj.id}}'> {% csrf_token %} <input type="hidden" name="post_id" value={{obj.id}}> <button type="submit" class="ui button like-btn{{obj.id}}"> ❤ {% if … -
Django provide value for baseuser_ptr
I'm learning django and I want to have my custom user and admin object but I'm encountering an error when I run makemigrations. I'm not sure if this is the right approach to do this so do enlighten me if I'm following the wrong approach. On one of my questions someone mentioned that I should only have one child of the AbstractBaseUser class but I really want to separate the customer model and the admin model. So I have created an app called 'core' where I want to do authentication stuff so that's where I've put my custom and admin user models. Here are the files I've written for that task so far: models.py: from django.db import models from store.models import CartItem from django.contrib.auth.models import AbstractBaseUser, UserManager from enum import Enum from django_countries.fields import CountryField from django.contrib import admin ADDRESS_CHOICES = ( ('B', 'Billing'), ('S', 'Shipping'), ) class AuthLevel(Enum): VOID = 0 Customer = 1 Worker = 2 Admin = 3 Programmer = 4 class Address(models.Model): street_address = models.CharField(max_length=100) apartment_address = models.CharField(max_length=100) country = CountryField(multiple=False) zip = models.CharField(max_length=100) address_type = models.CharField(max_length=1, choices=ADDRESS_CHOICES) default = models.BooleanField(default=False) def __str__(self): return self.street_address.name + " " + self.apartment_address.name class Meta: verbose_name_plural = 'Addresses' class … -
Django Heroku app using Postgres : django.db.utils.ProgrammingError: relation already exists
In my Django app which is hosted using Heroku I am trying to migrate from Sqlite to Postgesql. I have migrated all of my data from the Sqlite database to the Postgres database but I am having problems with executing queries using the Django ORM. When executing a simple query such as Item.objects.all() I get an error telling me that the table does not exist. django.db.utils.ProgrammingError: relation "App_item" does not exist When i run python manage.py migrate then it displays No migrations to apply. which would imply that all models / tables have been migrated from my old Sqlite database to my Postgres database? As well as this, when inspecting the schemas through PG-Admin4 all models appear, so I am really not sure how it can't find my tables. models.py class Item(models.Model): item_id = models.CharField(max_length=20, primary_key=True) item_name = models.CharField(max_length=210) ... .. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'legosite_DB', 'USER':'postgres', 'PASSWORD':'xxxxx', 'HOST':'127.0.0.1', 'PORT':'5432', } } -
Add Django model parent class to an existing "child" model for multi-table inheritance
I would like to add a new parent class to an existing model, which inherits from the same "super" parent class. Example of initial condition: from django.db import models class Ticket(PolymorphicModel): name = models.CharField(max_length=50) company = models.CharField(max_length=80) price = models.CharField(max_length=10) class MovieTicket(Ticket): # functions and logic For my implementation, I would like to add an "intermediary" EntertainmentTicket model, which inherits from Ticket and is inherited by MovieTicket for logic grouping purposes. Desired final condition: class Ticket(PolymorphicModel): name = models.CharField(max_length=50) address = models.CharField(max_length=80) price = models.CharField(max_length=10) class EntertainmentTicket(Ticket): # some functions and common logic extracted class MovieTicket(EntertainmentTicket): # logic unique to MovieTicket Note that the child classes have the same fields as Ticket, they only contain functions and logic. I cannot make Ticket into abstract, because I have other models pointing to it in a foreign key relationship. I use django-polymorphic to return the appropriate ticket type. I have made migrations for EntertainmentTicket, what are the right steps to take in writing custom migrations? -
"Why is my Django API returning an empty list of days for routines instead of a complete nested object with exercises and notes?"
I am having trouble getting a complete array of routines with each routine having multiple days, each day having multiple exercises, and all exercises having series, repetitions, cadence, and notes. The endpoint for routines is only returning its ID, name, and an empty list of days. I am using Django and Django REST Framework for this project. Here is the code for my models, serializers, and views: Models: from django.db import models class Ejercicio(models.Model): nombre = models.CharField(max_length=100) series = models.CharField(max_length=100) repeticiones = models.CharField(max_length=100) cadencia = models.CharField(max_length=100) notas = models.TextField(null=True, blank=True) class Dia(models.Model): dia = models.CharField(max_length=100) enfoque = models.CharField(max_length=100) ejercicios = models.ManyToManyField(Ejercicio) class Rutina(models.Model): nombre = models.CharField(max_length=100) dias = models.ManyToManyField(Dia) Serializers: from django.contrib.auth.models import User, Group from rest_framework import serializers from .models import Ejercicio, Dia, Rutina class EjercicioSerializer(serializers.ModelSerializer): class Meta: model = Ejercicio fields = ("id", "nombre", "series", "repeticiones", "cadencia", "notas") class DiaSerializer(serializers.ModelSerializer): ejercicios = EjercicioSerializer(many=True) class Meta: model = Dia fields = ("id", "dia", "enfoque", "ejercicios") class RutinaSerializer(serializers.ModelSerializer): dias = DiaSerializer(many=True) class Meta: model = Rutina fields = ("id", "nombre", "dias") def create(self, validated_data): dias_data = validated_data.pop("dias") rutina = Rutina.objects.create(**validated_data) for dia_data in dias_data: ejercicios_data = dia_data.pop("ejercicios") dia = Dia.objects.create(rutina=rutina, **dia_data) for ejercicio_data in ejercicios_data: Ejercicio.objects.create(dia=dia, **ejercicio_data) return rutina Views: … -
Ajax based drop down menu in Django admin
Please find the models and requirements below. As we can see from the models below, tags belong to a particular station. I am adding/editing data in these 2 models in a single page (as shown in the screen shot below), through my app’s Django admin. My requirement is when I choose a station name from a drop down, all the tags related to this station should load via AJAX automatically. Currently I am choosing a station name and I click save and continue editing in Django admin and after the page refresh all tags for that station name gets loaded. Waiting for the page refresh to load all tags belonging to a station name is very time consuming when adding details in bulk. Hence looking for ways to make an AJAX call every time the station name changes so that the tags are pulled and send back to the admin form asynchronously. Any suggestions is appreciated. In Models.py class Station(FeedmachineModel): slug = models.SlugField(unique=True) name = models.TextField() domain = models.TextField() timezone = models.TextField(choices=TIMEZONE_CHOICES) class Meta: ordering = ['slug'] def __str__(self): return self.slug + ': ' + self.domain class Tag(CmsObject, FeedmachineModel): name = models.TextField() station = models.ForeignKey(‘Station’, on_delete=models.CASCADE) objects = TagManager() def … -
ModuleNotFoundError at /register/ No module named 'django.core.email'
hey guys i have bug in my django project im trying to Implementation send vertification email with custom user and api and when i register with api i get error and this is my serializer code please help me: def create(self, validated_data): User = user.objects.create_user( username=validated_data['username'], email=validated_data['email'], fullname=validated_data['fullname'], password=validated_data['password1'], userid=validated_data['userid'], ) sendmail(email=validated_data['email']) return User def sendmail(email): subject = 'you should verify your account' message = f'please verify your account with this link.' email_from = settings.EMAIL_HOST_USER recipient_list = [user.email, ] send_mail( subject, message, email_from, recipient_list ) and this is my error: ModuleNotFoundError at /register/ No module named 'django.core.email' i got this error: ModuleNotFoundError at /register/ No module named 'django.core.email' -
Override Django filter when searching for list of values in one property
I have simple GroupViewSet, which allows to filter Group objects by id and parent. Everything works as expected. I would like to expand functionality by allowing filter by multiple parents. Something like /api/groups/?parent=1&parent=2. The problem is that returned list is filtered only by last provided parent value. So in my example returned queryset will be filtered by parent=2. How can I override filter for list of values while preserving its other functionality. class GroupViewSet(ModelViewSet): queryset = models.Group.objects.all() serializer_class = serializers.GroupSerializer filter_backends = (DjangoFilterBackend) filterset_fields = ('id', 'parent') def get_queryset(self): parent_ids = self.request.query_params.getlist('parent') if len(parent_ids) > 1: return self.queryset.filter(parent__in=parent_ids) return self.queryset -
How to set different custom fields for articles in different article categories in Django?
I am a python rookie. I am using Django 4.X to create some basic CMS functions. The features I expect are: custom article classification, custom fields within article classification, and the ability to add different field contents based on user needs when adding articles in different categories. For example, Category 1: In addition to adding titles and article content, users also need to add weather information, while Category 2: users need to add price and quantity in addition to titles and article content. Here are the features I have already implemented and successfully run: Article publishing Article classification Custom fields within article classification Here is the feature I am unable to implement: When the user enters the page from post/int:category_id/add/, they should be able to add an article with the specific category ID and see the input fields for the custom fields I have added for that category ID. Here is my models.py and views.py code: models from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(max_length=50) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') custom_fields_group = models.ForeignKey('CustomFieldsGroup', on_delete=models.SET_NULL, null=True, blank=True, verbose_name='自定义字段组') class MPTTMeta: order_insertion_by = ['name'] def __str__(self): return self.name class Meta: verbose_name = "多层分类" verbose_name_plural … -
Persistent 403 Forbidden with Apache + Django
I hope you can help me with a problem that seems simple but I don't understand where the error comes from My Django application remains inaccessible with my current configuration apache2/error.log [Fri Mar 24 16:35:24.094998 2023] [mpm_event:notice] [pid 101389:tid 140233809427776] AH00494: SIGHUP received. Attempting to restart [Fri Mar 24 16:35:24.168460 2023] [mpm_event:notice] [pid 101389:tid 140233809427776] AH00489: Apache/2.4.54 (Debian) mod_wsgi/4.7.1 Python/3.9 configured -- resuming normal operations [Fri Mar 24 16:35:24.168499 2023] [core:notice] [pid 101389:tid 140233809427776] AH00094: Command line: '/usr/sbin/apache2' [Fri Mar 24 16:35:27.794864 2023] [authz_core:error] [pid 106856:tid 140233787946752] [client 192.168.130.131:55869] AH01630: client denied by server configuration: /home/sullivan/webapp/webapp-proto/appback/wsgi.py appback/wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'appback.settings') application = get_wsgi_application() apache2 webapp_prod.conf <VirtualHost *:80> ServerName localhost WSGIDaemonProcess webapp_prod python-home=/home/sullivan/venv python-path=/home/sullivan/webapp/webapp-proto/webapp/appback/ WSGIProcessGroup webapp_prod WSGIScriptAlias / /home/sullivan/webapp/webapp-proto/appback/wsgi.py # WSGIScriptAlias / /home/sullivan/webapp/webapp-proto/appback/django.wsgi <Directory /home/sullivan/webapp/webapp-proto/webapp/appback/> Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> apache2 apache2.conf # Global configuration # # # ServerRoot: The top of the directory tree under which the server's # configuration, error, and log files are kept. # # NOTE! If you intend to place this on an NFS (or otherwise network) # mounted filesystem then please read the Mutex documentation (available # at <URL:http://httpd.apache.org/docs/2.4/mod/core.html#mutex>); # you will save yourself a … -
How to show required request body using django rest framework + drf_spectacular + swagger
I started using drf_spectacular and swagger recently, I have a an API endpoint that expects request body with field in it, however I can't seem to understand how to reveal this in the UI. my view: @extend_schema( responses={200: TripSerializer}, ) def get(self, request: Request) -> Response: trip = TripService.get_trip(trip_id=request.data.get("trip_id")) if trip is None: return Response(status=status.HTTP_404_NOT_FOUND) trip_serializer = TripSerializer(trip) return Response(trip_serializer.data, status=status.HTTP_200_OK) my request body: { "trip_id": "1" } my swagger UI ps will appriciate any help, Thanks -
Adding prerequisite to course sections
I am using the Tutor + OpenEdx open source platform and am looking to be able to set the prerequisite requirement for the individual sections as you can see this is already possible with the subsections but do not think there's an option for the individual sections. For example in the screenshots attached would like to have "Python" and "C++" locked until the student has completed "Intro to Programming". Think this is only possible with the subsections and not the sections at the moment so would like to build a plugin for it (or make changes to the code) to allow one to do the same with the sections. Would anyone be able to provide guidance on how to make this possible? -
I download Django project with Virtual Environment but cannot use it
I use FTP download my djaongo project from server to laptop. After that, In folder virtual environment it have many file like this image. I use this command to access virtual environment. .\myproject_env\bin\activate.ps1 It show (myproject_env) in front of path but when I use command python manage.py runserver it show error like this. How to fix it? (base) (myproject_env) PS D:\Django\myproject\myproject> python manage.py runserver Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. -
Getting error:"ORA-12505: TNS:listener does not currently know of SID given in connect descriptor". when connecting DJANGO to a remote oracle database
i can successfully connect to the remote database from my laptop through the follwing sqlplus command: sqlplus pdb1admin/mypass@192.168.18.102:1521/pdb1 but when i enter the credentials in my django project it gives the error:"ORA-12505: TNS:listener does not currently know of SID given in connect descriptor". my pluggable database name is pdb1. my service name is also pdb1. my username for the pdb1 database is pdb1admin. my password is 'mypass' and my port is 1521. my settings.py file in django project: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'pdb1', 'USER': 'pdb1admin', 'password':'mypass', 'HOST':'192.168.18.102', 'PORT':'1521', } } here is my tnsnames.ora file which is on my other computer which have the oracle database running. XE = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.18.102)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = XE) ) ) PDB1 = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.18.102)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = pdb1) ) ) LISTENER_XE = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.18.102)(PORT = 1521)) LISTENER_PDB1 = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.18.102)(PORT = 1521)) ORACLR_CONNECTION_DATA = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521)) ) (CONNECT_DATA = (SID = CLRExtProc) (PRESENTATION = … -
Cannot use fetch with Django: blocked by CORS policy although CORS is set up in Django
There are many solutions on SO for this problem. Some are extremely detailed (e.g. this one). However, although I think I have followed the setup instructions explicitly, I still cannot get it to work. Can someone please point out my error? js let endpoint = 'http://192.168.4.28:8000/test-put' const form_data = new FormData(); form_data.append("payload", payload); await fetch(endpoint, { credentials: "include", method: "PUT", body: form_data, headers: { "X-CSRFToken": getCookie("csrftoken"), }, }) urls.py path('test-put/', views.TextPut.as_view()), views.py class TextPut(View): def put(self, request): return {} settings.py ... CORS_ALLOWED_ORIGINS = [ 'http://localhost:8888', ] CSRF_TRUSTED_ORIGINS = [ 'http://localhost:8888', ] ... INSTALLED_APPS = [ ... 'corsheaders', ... ] ... MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... 'django.middleware.common.CommonMiddleware', ... ] This produces the error: Access to fetch at 'http://192.168.4.28:8000/test-put' from origin 'http://localhost:8888' has been blocked by CORS policy: Response to preflight request doesn't pass access control -
Django: Deployment to different companies using the same project?
If, for example, ten people from different companies want to use my Django site. I think, I need a different database per company. Does this means ten different Django projects/instances being deployed? With different domains and separate databases? This seems unmanageable if one needs to update the code. (I am using PythonAnywhere a d mySQL but I don't care what I use in the end, just that I do this the right way so I don't end up with a major problem. I am looking to keep it as simple as possible to start and learn.) To all, what is your method to handle the 'selling' on a subscription basis a website to different organization while keeping everything organized? An example is a CRM program. If I an employee wants to see all the notes about Customer A, I don't want them seeing customers from different companies when I query to get .all(). So I am guessing I need different databases, deployments etc. . . Thank you, I don't even know what to search on Google to read about this or else I probably wouldn't be asking it here.