Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
After the installation of SSL on my Django application, i encounter a 403 Forbidden error preventing access to CSS files. The domain is memcur.com
After the installation of SSL on my Django application, i encounter a 403 Forbidden error preventing access to CSS files. I am using nginx and ubunto. The /var/log/nginx/error.log shows the following continuously, though i have applied: sudo chown -R www-data:www-data /root/memcur/static/ sudo chmod -R 755 /root/memcur/static/ /var/log/nginx/error.log: "/root/memcur/static/libs/bootstrap/dist/js/bootstrap.bundle.min.js" failed (13: Permission denied), client: 103.180.203.6, server: memcur.com, request: "GET /static/libs/bootstrap/dist/js/bootstrap.bundle.min.js HTTP/1.1", host: "memcur.com", referrer: "https://memcur.com/account/login/?next=/" "/root/memcur/static/libs/metismenu/dist/metisMenu.min.js" failed (13: Permission denied), client: 103.180.203.6, server: memcur.com, request: "GET /static/libs/metismenu/dist/metisMenu.min.js HTTP/1.1", host: "memcur.com", referrer: "https://memcur.com/account/login/?next=/" "/root/memcur/static/libs/node-waves/dist/waves.min.js" failed (13: Permission denied), client: 103.180.203.6, server: memcur.com, request: "GET /static/libs/node-waves/dist/waves.min.js HTTP/1.1", host: "memcur.com", referrer: "https://memcur.com/account/login/?next=/" "/root/memcur/static/js/app.js" failed (13: Permission denied), client: 103.180.203.6, server: memcur.com, request: "GET /static/js/app.js HTTP/1.1", host: "memcur.com", referrer: "https://memcur.com/account/login/?next=/" The domain is memcur.com. The css, js, and images are not loading. Pleas visit and give me a suggestion to fix it. -
OSError: Load averages are unobtainable
Our django celery server is running with concurrency value of 500 with eventlet as execution pool. Recently, we encountered this issue and restarting the server fixed it. I am attaching the traceback of the error. python package versions: Django 4.1.7 celery5.2.3 eventlet 0.33.3 I checked the soft and hard limits of the open files if these are of any use. soft limits: core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited scheduling priority (-e) 0 file size (blocks, -f) unlimited pending signals (-i) 31071 max locked memory (kbytes, -l) 65536 max memory size (kbytes, -m) unlimited open files (-n) 2048 pipe size (512 bytes, -p) 8 POSIX message queues (bytes, -q) 819200 real-time priority (-r) 0 stack size (kbytes, -s) 8192 cpu time (seconds, -t) unlimited max user processes (-u) 31071 virtual memory (kbytes, -v) unlimited file locks (-x) unlimited hard limits: core file size (blocks, -c) unlimited data seg size (kbytes, -d) unlimited scheduling priority (-e) 0 file size (blocks, -f) unlimited pending signals (-i) 31071 max locked memory (kbytes, -l) 65536 max memory size (kbytes, -m) unlimited open files (-n) 16384 pipe size (512 bytes, -p) 8 POSIX message queues (bytes, -q) 819200 real-time priority … -
"GET /cart.json HTTP/1.1" 404
"GET /cart.json HTTP/1.1" 404 error show in the command prompt when I use runserver in my django app. The website works absloutly fine when the debug=True in the setting but when I turn it off it shows 500 internal error. I don't have cart.json in any part of my code, and I cannot really undrestand where it comes. How can I troubleshoot it? -
Django: How can i open an App with Django?
I am currently working on a Django project and have reached a point where I need to implement the final functionalities. However, I am encountering a problem in one specific area. When the app is opened on a smartphone, I want to open the scanner app of that specific smartphone with a button. I have tried using the URL scheme required for my smartphone provider, but that did not work. I have also made sure to allow all relevant permissions in the app settings. I am stuck and would appreciate any help. Below is the code snippet where the issue occurs: <span>@{{room.host.username}}</span> </a> </div> <div class="room__details"> {{room.description}} </div> <span class="room__topics">{{room.topic}} <a href="xmsf://scan/scanner">Open Scanner App</a> </span> </div> <div class="room__conversation"> <div class="threads scroll"> {% for element in liste %} <li>{{ element }}</li> {% endfor %} Thank you. -
Using `django_get_or_create` with onetoone related field
Given this django model from django.db import Model from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT) some_other_field = model.CharField(...) I have created 2 factory for the user and the customer model: import factory class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User django_get_or_create = ('username',) first_name = factory.Faker("first_name", locale="fr_FR") last_name = factory.Faker("last_name", locale="fr_FR") username = factory.LazyAttribute(lambda m: f"{m.first_name[0]}{m.last_name[0]}".lower()) email = factory.LazyAttribute(lambda m: f"{m.first_name.lower()}.{m.last_name.lower()}@ielo.net") customer = factory.RelatedFactory(CustomerFactory, factory_related_name="user", user=None) is_staff = False class CustomerFactory(factory.django.DjangoModelFactory): class Meta: model = "customers.Customer" user = factory.SubFactory('myapp.tests.fixtures.UserFactory', customer=None) To avoid flaky tests, I have set the django_get_or_create, since most of the time I just want a user, and I create specific classes for specific cases (UserIsStaffFactory, UserSuperAdminFactory) I copied the RelatedFactory/SubFactory from https://factoryboy.readthedocs.io/en/stable/recipes.html#example-django-s-profile but If I run: u1 = UserFactory(username='foo') u2 = UserFactory(username='foo') # raise IntegrityError, UNIQUE constraint failed: customers_customer.user_i -
Is there any package like pm2 for django apps
Question: I have a Django app running on a server, and I want to use PM2 to manage the process. However, when I try to start the app with PM2, it gives me an error. Here is my command: pm2 start myapp And here is the error message: Error: script not found or unable to stat: myapp What am I doing wrong? How can I use PM2 to manage my Django app? -
How to configure Django app on AWS elastic beanstalk without "Invalid HTTP_HOST header" errors
Goal: To deploy an application to AWS Elastic Beanstalk but constantly receiving the error ERROR 2023-06-16 17:54:37,903 exception 92295 139827093698112 Invalid HTTP_HOST header [some IP address] despite several attempts. Current status: The site works perfectly on my localhost. The requirements.txt file is in the same directory as manage.py. All changes are committed to the git main before deployment to Elastic Beanstalk (EB). There is no .ebignore file, only a .gitignore file. The wsgi.py file is located one level under manage.py, at config>wsgi.py. This is implemented in the .ebextensions>django.config file as shown below: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: config.wsgi:application Two settings.py files are used: base.py and production.py. Following an existing Stack Overflow response, the production.py file is obtained from django-cookie-cutter and shown below: The production.py file: from .base import * # noqa from .base import env import os SECRET_KEY = env("DJANGO_SECRET_KEY") if 'RDS_HOSTNAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } # SECURITY # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#secure-proxy-ssl-header SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") # https://docs.djangoproject.com/en/dev/ref/settings/#secure-ssl-redirect SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True) # https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-secure SESSION_COOKIE_SECURE = True # https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-secure CSRF_COOKIE_SECURE = True # https://docs.djangoproject.com/en/dev/topics/security/#ssl-https # https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-seconds # TODO: set this to 60 seconds first and … -
How to add jwt authentication to existing login page on django
So I am learning how to use Django and DRF and I created a Login and Register page on Django. Login and Register user view with their own html pages But, I don't want to use the normal authentication in Django and want to use Jwt token to authenticate I have already downloaded it and and can use api/token and api/token/refresh to get the access and refresh token but I cant seem to find a way to use it in my already built login and register page to authenticate -
Luxor Pool API (Create subaccount, delete subaccount)
Question: when create a subaccount on luxor pool it create the user but when i delete the same user by calling delete subaccount api. It does not give me access to create the same user subaccount with the same name. Error: {"errors":[{"message":"error: duplicate key value violates unique constraint \"users_username_key\"","locations":[{"line":3,"column":9}],"path":["provisionNewUser"]}],"data":{"provisionNewUser":null}} Subaccounts list: { "success": true, "message": "", "data": { "users": { "edges": [ { "node": { "username": "cxdevs" } }, { "node": { "username": "user-1" } } ] } } } Note: I have delete the account with the same name when i first created it. And after deleting it does give me access to create with the same name. (Luxor Pool APIs) -
I have upload a django project on server in public html folder
When creating a Python application on a server, I put the folder name or project name in the application root. However, the issue is that the folder is creating outside the public HTML folder. I want the folder to be created in the public HTML folder only. How can I ensure that the folder is created in the desired location? -
401 unauthorized on post request
serializer/login.py class LoginSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) refresh = self.get_token(self.user) data['user'] = UserSerializer(self.user).data data['refresh'] = str(refresh) data['access'] = str(refresh.access_token) if api_settings.UPDATE_LAST_LOGIN: update_last_login(None, self.user) return data viewsets/login.py class LoginViewSet(ViewSet): permission_classes = (AllowAny,) serializer_class = LoginSerializer http_method_names = ['post'] def create(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) try: serializer.is_valid(raise_exception=True) except TokenError as e: raise InvalidToken(e.args[0]) return Response(serializer.validated_data, status=status.HTTP_200_OK) I cant login with right credentials using post request, it says 401 unauthorized. but when I try to register or refresh token using post request (using the same crediatials I tried to login with), it works fine. serializer/register.py class RegisterSerializer(UserSerializer): #making the pass min 8 charecter and max 128 #and can't be read password = serializers.CharField(max_length=128, min_length=8, write_only=True, required=True) class Meta: model = User fields = ['id', 'email', 'username', 'first_name', 'last_name', 'password'] # 'bio', 'avater', #used the create_user method that we wrote def create(self, validated_data): return User.objects.create_user(**validated_data) viewsets/register.py class RegisterViewSet(ViewSet): serializer_class = RegisterSerializer permission_classes = (AllowAny,) http_method_names = ['post'] def create(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() refresh = RefreshToken.for_user(user) res = { "refresh" :str(refresh), "access": str(refresh.access_token), } return Response({ "user": serializer.data, "refresh":res['refresh'], "token":res['access'] }, status=status.HTTP_201_CREATED) viewsets/refresh.py class RefreshViewSet(viewsets.ViewSet, TokenRefreshView): permission_classes = (AllowAny,) http_method_names = ['post'] def create(self, … -
React gets non responsive when data from Django is used to display a Nivo line chart
I have been trying to display a nivo line charts using data from my backend (Django). However, when the data is inserted into the nivo line chart, the react window gets unresponsive. The backend sends the timestamps and the values like this -- Example -- timestamp = "2023-05-12 16:10:53.000000000" Values -- "39.520004" class AddView(APIView): from django.views.decorators.csrf import csrf_exempt from rest_framework import status import json @staticmethod @csrf_exempt def post(request): from awsfetch.rpm import rpm timestamps, values = rpm() return Response({"timestamps": timestamps, "values": values}) This is the nivo charts component -- import { ResponsiveLine } from "@nivo/line"; const MyResponsiveLine = ({ data }) => ( <ResponsiveLine data={data} margin={{ top: 50, right: 160, bottom: 50, left: 60 }} xScale={{ format: "%Y-%m-%dT%H:%M:%S.%L%Z", type: "time" }} xFormat="time:%Y-%m-%dT%H:%M:%S.%L%Z" yScale={{ type: "linear", stacked: true, min: 0.0, max: 1.0 }} curve="monotoneX" axisTop={null} axisRight={{ tickValues: [0.0, 0.2, 0.4, 0.6, 0.8, 1.0], tickSize: 5, tickPadding: 5, tickRotation: 0, format: "0.2", legend: "", legendOffset: 0 }} axisBottom={{ tickValues: "every 1 second", tickSize: 5, tickPadding: 5, tickRotation: 0, format: "%S.%L", legend: "Time", legendOffset: 36, legendPosition: "middle" }} axisLeft={{ tickValues: [0.0, 0.2, 0.4, 0.6, 0.8, 1.0], tickSize: 5, tickPadding: 5, tickRotation: 0, format: ".2", legend: "CPU", legendOffset: -40, legendPosition: "middle" }} enableGridX={false} colors={{ scheme: … -
Django REST framework prefetch not working on model with multiple foreign keys to the same target
I'm writing an endpoint to fetch data from the "Term" model in Django REST framework and I'm trying to reduce queries by prefetching data. Specifically there is a model "TermRelation", that saves vector relation scores between individual terms that I would like to prefetch data from. Simplified, the models look as follows: models.py class Term(models.Model): term = models.CharField(max_length=255, verbose_name=_('Term'), null=True, db_index=True) class TermRelation(models.Model): src_term = models.ForeignKey(Term, on_delete=models.CASCADE, verbose_name=_('Source term'), related_name='src_term_relation') trg_term = models.ForeignKey(Term, on_delete=models.CASCADE, verbose_name=_('Target term'), related_name='trg_term_relation') vector_sim = models.FloatField(blank=True, null=True, default=0.0, verbose_name=_('Vector similarity'), help_text=_('Cosine vector similarity.')) And here's the simplified view: views.py class TermsList(generics.ListCreateAPIView): def get_queryset(self): queryset = Term.objects.prefetch_related( 'src_term_relation', 'trg_term_relation', 'note_set', 'usage_set' ).all() return queryset There are other models related to term such as "Note" and "Usage" for which prefetch is working, only for relations it still makes a bunch of queries. I've included a screenshot of the Django SQL debug results, or rather the first few lines as this goes on for a while with the same queries. You can see that Django does run the prefetch operation, but then still makes the same queries as if it didn't happen. What am I doing wrong? Could this be related to "TermRelation" having two ForeignKey fields pointing to … -
Implementation of the post filter page in django
I am trying to filter blog posts using this model: class Post(models.Model): is_podcast = models.BooleanField(default=False) category = models.ManyToManyField(Category) title = models.CharField(max_length=500) slug = models.SlugField(allow_unicode=True , unique=True , null=True , blank=True) body = RichTextUploadingField() likes_count = models.IntegerField(default=0 , help_text="amount of likes") vip_members_only = models.BooleanField(default=False) def __str__(self): return self.title And I am using this view to filter the posts: def Index_view(request , slug=None): posts = Post.objects.filter() kind = request.GET.get('type') order = request.GET.get('order') author = request.GET.get('author') search = request.GET.get('search') if slug: cat = get_object_or_404(Category , slug=slug) posts.filter(category = cat) if search != '' and search is not None: posts.filter(Q(title__icontains = search)) if kind != '' and kind is not None: if kind == 'podcast': posts.filter(is_podcast=True) if kind == 'all': pass if kind == 'post': posts.filter(is_podcast=False) con = {'posts' : posts} return render(request , 'Weblog/posts.html' , con) Here is the urls.py too: path('posts/', Index_view), re_path(r'^posts/(?P<slug>[\w-]+)/$', Index_view), When I use this URL (http://127.0.0.1:8000/blog/posts/some-slug/?search=test), I receive all the posts and the filtering does not work. What is the problem? -
how do I call a djago admin delete fuction
I am trying to use the Django admin delete function to ensure that the corresponding quantity is deleted from the associated page when the delete function is clicked. For example, I have a class called RestockModel. When I add a new Restock item, the restock quantity can be automatically added in the StockListModel. However, when I need to delete the Restock item, the quantity in StockListModel is not deleted immediately. How can I call the django admin delete function to this statement? Here is the code that how I made the quantity can be added when I create a new restock item: class restockInfo(admin.ModelAdmin): list_display = ["product", "delivery_order_no","restock_quantity", "supplier_name", "created_date"] readonly_fields = ["created_date"] search_fields = ['created_date'] def save_model(self, request, obj, form, change): product = obj.product restock_quantity = obj.restock_quantity if restock_quantity and product.quantity_in_store: if restock_quantity >= 0: obj.product.quantity_in_store = product.quantity_in_store + restock_quantity # don't forget to save stock after change quantity obj.product.save() messages.success(request, 'Successfully added!') super().save_model(request, obj, form, change) else: messages.error(request, 'Invalid Quantity, Please Try Again!!!') return restockInfo This is my restock models: class restockList(models.Model): product = models.ForeignKey("stockList", on_delete=models.CASCADE, null=True) delivery_order_no = models.CharField(max_length=255, null=True) restock_quantity = models.IntegerField(null=True) supplier_name = models.CharField(max_length=255, null=True) created_date = models.DateTimeField(auto_now_add=True, blank=True, editable=False) class Meta: db_table = "restocklist" -
Getting object index in django object list
I have a list in context of one of my pages called comments and when I'm iterating on it i want to know the index of item; i want to know the index of comment in this for loop: <!-- comment list section --> <div class="card shadow my-3 p-5"> <h3>Comments:</h3> <!-- checking if any comment exist on this post --> {% if comments.count < 1 %} No comments. write the first one! {% else %} <!-- iterating on comments and showing them --> {% for comment in comments %} <div id="comment-div"> <span id="Comment-name">by: {{ comment.name }}</span> <span id="Comment-date">{{ comment.datetime_created|date:'M d Y' }}</span> <p id="Comment-body">{{ comment.body }}</p> </div> {% endfor %} {% endif %} </div> view: class PostDetailView(FormMixin, generic.DetailView): model = Post template_name = 'blog/post_detail.html' context_object_name = 'post' form_class = CreateComment def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) # get the default context data context['comments'] = Comment.objects.filter(accepted=True) # add extra field to the context return context model: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') email = models.EmailField(max_length=35) name = models.CharField(max_length=50) body = models.TextField() datetime_created = models.DateTimeField(auto_now_add=True) accepted = models.BooleanField(default=False) -
White space stripped from Django Template tags in PrismJS code blocks
When I render Django template code in a prismjs block, it strips white space {{}} and {%%}. For example, pre-render, the code might be {% image self.search_image thumbnail-400x200 as img %} <img src="{{ img.url }}" alt="{{ img.title }}"> But the rendered code block will be {%image self.search_image thumbnail-400x200 as img%} <img src="{{img.url}}" alt="{{img.title}}"> It's not a case of css, the space is missing from the html. I can set the language to HTML, or even python etc, the same issue remains. Does anyone know of a way to prevent this? -
How Can I implement User Sent Message and Receive Message in Django
I am working on a Django project where I have three types of users: Landlord, Agent, and Prospect. I want the Prospect user to be able to contact the Property Owner by sending a message while on the Property Detail view, and the Property Owner to be able to reply back to the Prospect using the same view. I also want all these users to maintain an Inbox and Sent Message items. I'm struggling to figure out whether my logic is sound and how to implement the functionality using Django. Is there a library that will make user messaging within Django easier? In my code, I maintain different Models for these users with a OneToOneField and use signals for automatic profile creation upon registration. I also have a Profile Model connected through the same relationship, and Message Model. I tried passing the Property Owner ID as the Recipient ID and Property ID on url from the Property Detail view to the send_message function view, but I get the error "No 'User matches the given query'." Here are my views: def property_detail(request, property_id): user = request.user #Check if user is authenticated if not user.is_authenticated: logout(request) messages.warning(request, 'Session expired. Please log in … -
Annotating a value in Django using Extract and OuterRef (or F) leads to TypeError
I'm building an application where users can create posts. If the user don't post anything after some specific time of the day, the server will send a push notification to remember the user to post something. In order to create this query I planned to run a scheduled celery beat task to filter the posts created in the current day, list the user's id and use a simply exclude these IDs from the active users in order to get a queryset with the users that should be notified. The user has a timezone field, which is updated via a middleware that checks some headers frontend send, checks the user saved timezone and update it if necessary. This timezone is the result of running the tzname() method in the datetime that comes in this header. The issue is that the users are spread across multiple timezones, so I need to actually annotate the created_at field in Posts (which are saved taking in consideration the server timezone) with the User's timezone. In Django we have the Extract function that simply does exactly what I need. The issue here is that it would work perfectly if I could use a F expression or … -
What kind of security should I implement in my Django REST API if it doesn't require authentication?
It's my first time building an API and it only processes GET requests. What kind of security would be necessary for this project? Other than using the .gitignore file and making sure my database key is hidden do I need to further secure the database for production? My project uses Django, Django REST, and PostgreSQL. I haven't yet found a host I like enough to deploy to so any recommendations would be appreciated. -
django.db.utils.OperationalError: (2002, "Can't connect to local server through socket '/run/mysqld/mysqld.sock' (2)")
I am trying to dockerize my Django project which includes a MySQL database and nginx. When I run the command docker-compose up --build, I receive the following error: django.db.utils.OperationalError: (2002, "Can't connect to local server through socket '/run/mysqld/mysqld.sock' (2)"). This is my docker-compose.yml file: version: '3.7' services: app: build: ./app env_file: - .env container_name: app restart: always expose: - 8000 command: bash -c "python3 manage.py collectstatic --noinput && python3 manage.py migrate --noinput --fake-initial && \ gunicorn -b 0.0.0.0:8000 veblog.wsgi" environment: - MYSQL_DATABASE=${NAME} - MYSQL_USER=${USER_NAME} - MYSQL_PASSWORD=${PASSWORD} - MYSQL_HOST=sqldb mem_limit: 1g depends_on: - sqldb # - nginx volumes: - ./volumes/app:/app - type: bind source: ./volumes/media target: /app/media - type: bind source: ./volumes/static target: /app/static nginx: build: ./nginx container_name: nginx restart: always ports: - 8000:80 sqldb: image: mysql:latest container_name: sqldb restart: always depends_on: - nginx expose: - 3306 environment: - MYSQL_DATABASE=${NAME} - MYSQL_USER=${USER_NAME} - MYSQL_PASSWORD=${PASSWORD} - MYSQL_ROOT_PASSWORD=${ROOT_PASSWORD} - MYSQL_INITDB_SKIP_TZINFO=true - MYSQL_INIT_COMMAND=SET GLOBAL host_cache_size=0; volumes: - type: bind source: ./volumes/dbdata target: /var/lib/mysql - /usr/share/zoneinfo:/usr/share/zoneinfo:ro This is my Dockerfile in the app directory: FROM python:3 ENV PYTHONDONTWRITEBYCODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir -p /app WORKDIR /app COPY . . RUN apt update RUN apt install gcc python3-dev musl-dev -y RUN pip install --upgrade … -
How to find overlapping with a given start_time and end_time (Weekday/Hour format)
I am attempting to determine overlapping availability for a specialist based on their stored availability, which is stored as a datetime due to timezone changes, but only the weekday and time portion is used. When searching for availabilities, I search them as isoweekday and time. However, I am facing issues when the start time is greater than the end time or the start day is greater than the end day. Here is my SpecialistAvailability model: class SpecialistAvailability(BaseModel): """ Model to store the availability of a specialist """ specialist = models.ForeignKey(Specialist, on_delete=models.CASCADE, null=False, blank=False) start_time = models.DateTimeField(null=False, blank=False) end_time = models.DateTimeField(null=False, blank=False) objects = SpecialistAvailabilityManager() I am using pytz and Django to filter for overlapping availability for a specialist as such: import pytz from django.db import models from django.db.models import Q, F class SpecialistAvailabilityManager(models.Manager): """ Manager for SpecialistAvailabilityDay model """ def get_overlapping_availability(self, specialist, start_time, end_time): """ Method to get overlapping availability of a specialist """ start_day = start_time.isoweekday() end_day = end_time.isoweekday() start_time = start_time.time() end_time = end_time.time() initial_availabilities = self.filter(specialist=specialist) if start_day > end_day: day_availabilities = initial_availabilities.filter( Q(start_time__iso_week_day__gt=F('end_time__iso_week_day')) | Q(start_time__iso_week_day__lte=end_day) | Q(end_time__iso_week_day__gte=start_day) ) else: day_availabilities = initial_availabilities.filter( Q(start_time__iso_week_day__gt=F('end_time__iso_week_day'), start_time__iso_week_day__lte=end_day) | Q(start_time__iso_week_day__gt=F('end_time__iso_week_day'), end_time__iso_week_day__gte=start_day) | Q(start_time__iso_week_day__lte=end_day, end_time__iso_week_day__gte=start_day) ) if start_time > end_time: availabilities … -
New to django, django server not loading home page
I started a Django project and went through the regular setup process: I used the "startproject" command to create a project named "social_clone_project", and I used "startapp" to create an app named "accounts". Then I created a "views.py" file and set up the "urls.py" file. Here's what it looks like: from django.contrib import admin from django.urls import path, include, re_path from . import views urlpatterns = [ re_path(r'^$', views.HomePage.as_view(), name='home'), path("admin/", admin.site.urls), ] Recently, I switched to Ubuntu Debian with the sublime-text editor. I'm new to the Ubuntu OS, and whenever I run the "runserver" command, the default "Congratulations!" page loads instead of my home page. I've created an "index.html" file, which is supposed to load as the home page, but it's not working. Can someone help me solve this issue? -
how to get values from a context (object ) dinamically in django templates
I'm a newbie in django and I'm trying to get values from an object dynamiclly in the template directly, but nothing seems to work: this is what I have in the django template: {% for key, value in edit.changes.items %} <p>{{ translator.get(key) }}</p> I also tried this: {% for key, value in edit.changes.items %} <p>{{ translator[key] }}</p> this is the view: def medical_record_edit_list(request, pk): translator = { "appointment_date" :"Fecha", "diagnosis_type" : " Tipo de Diagnóstico", "main_diagnosis" : "Diagnóstico Principal (CIE-10)", "related_diagnosis" : "Diagnóstico Relacionado (CIE-10)", "objective" : "Objetivo", "mental_exam" : "Exámen Mental", "development" : "Desarrollo", "employed_interventions" : "Intervenciones Utilizadas", "evaluation_instruments" : "Instrumentos de Evaluación", "agreements" : "Acuerdos", "therapeutic_work" : "Expectativas de la Consulta", "evaluation_instruments" : "Instrumentos de Evaluación", "remission" : "Remisiones y Contrarremisiones", "finality" : "Finalidad", "external_cause" : "Causas Externas", "conduct" : "Conducta", "exit_state" : "Estado de Salida", "exit_diagnosis" : "Diagnóstico de Egreso (CIE-10)", "exit_condition" : "Condición de Salida" } medical_record_entry = MedicalRecordEntry.objects.get(pk=pk) edit_list = MedicalRecordEdit.objects.filter(medical_record_entry=medical_record_entry).order_by("edit_date") return render(request, 'medical_record/medical_record_edit_list.html', {'edit_list':edit_list, 'medical_record_entry':medical_record_entry, 'translator': translator}) I'm just trying to get what something like: {{ context.appointment_date }} outputs but for each key of the for loop that I have above -
Define database models for webapp about event in django
I'm trying to build an web app about events in python django. Basically, users can see which events will happen or happened and also their dates, locations, etc. But the problems are in relations. So, I've created accounts, events, boardgames, frp, mtg apps in django. Here is the I've coded models. ## for accounts class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return f"{self.username}" ## for events class Event(models.Model): name = models.CharField(max_length=256, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.CharField(max_length=256, unique=True) organizer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='organized_events') date = models.DateTimeField() location = models.CharField(max_length=256, unique=True) attendees = models.ManyToManyField(User, through='EventMember') situation = models.BooleanField(default=True) def get_absolute_url(self): return reverse('events:single', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) def __str__(self): return self.name class EventMember(models.Model): event = models.ForeignKey(Event, related_name='event_memberships', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_events', on_delete=models.CASCADE) def __str__(self): return self.user.username Bu I want to build the models roughly like this: diagram How can I build these models and how can I code views for them ? I also think you dream what kind of webapp is this. I'm open to every kind of suggestions. Thanks.