Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way in Django to expose only a certain range of URLs based on some predefined variable?
I am basically trying to expose a a range of defined URLs in an application. E.g., I have 10k x2 resources which I'm hosting at /metadata/type1_1 and /metadata/type2_1 where each resource grouping iterates up to type1_10000 and type2_10000 respectively (20,000 stored assets I intend to serve over a manually-driven interval). As such, I'm trying to define a URL scheme such that max_available_metadata = current_limit [e.g. this may be 300, 7777 etc.] and I only want to configure the URLs within the pattern up to this limit. e.g., if I sent it to 25, type1_1, type1_2...25 and likewise type2_1, type2_2... type2_25 would all map properly but attempting to go to metadata/type1_26 through type1_10000 would all return 404s, likewise for type 2. I'll probably want to configure setting this via the django admin but this isn't part of the question. -
Reverse for 'category' with keyword arguments '{'category': ''}' not found. 1 pattern(s) tried: ['category\\/(?P<category>[^/]+)\\/$']
name of the error is Reverse for 'category' with keyword arguments '{'category': ''}' not found. 1 pattern(s) tried: ['category\\/(?P<category>[^/]+)\\/$'] I know that there is a lot on this topic on this forum but my case is somewhat special due to that my views are working on other menu. To Be more accurate I have 2 navbars and if click one link on navbar A everything is good but then I click link on navbar B and I get the error I have a category model that looks like this. If the Navbar field is True I'm putting the category name and link on the navbar B. All fields are visible on navbar A class Category(models.Model): category = models.CharField(max_length=20,unique=True) navbar = models.BooleanField(null=False, blank=False, default=True) def __str__(self): return self.category Due to menu layout ( B ) looking like this I need to set nav links manually nav - nav - language_changer - nav - nav\ So I've set them like this <a href='{% url "category" category="{navbarList.0.id }" %}'> {{ navbarList.0.category }} </a> <a href='{% url "category" category="{navbarList.1.id }" %}'> {{ navbarList.1.category }} </a> the A navbar {% for x in categoryList %} <a href="{% url 'category' category=x.category %}" > {{ x.category }} … -
Docker-compose up runs perfectly localy ,but on gcp i get error could not translate host name db to address: Temporary failure in name resolution
line 187, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.9/site-packages/psycopg2/init.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution On my local machine everything works perfectly. my docker file FROM python:3.9-slim-buster # RUN apt-get update && apt-get install -y libpq-dev \ # gcc \ # postgresql-client # set work directory WORKDIR /opt/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt /opt/app/requirements.txt RUN chmod +x /opt/app/requirements.txt RUN pip install -r requirements.txt # copy project COPY . /opt/app/ RUN chmod +x /opt/app/docker-entrypoint.sh EXPOSE 8000 ENTRYPOINT [ "/opt/app/docker-entrypoint.sh" ] Here is my docker-compose.yml version: '3.9' services: db: image: postgres restart: always environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_PASS=postgres volumes: - postgres_data:/var/postgres/data/ app: restart: always build: context: . dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 container_name: myproj volumes: - ./app/:/usr/src/app/ ports: - "8000:8000" depends_on: - db volumes: postgres_data: driver: local my entrypoint echo "Apply database migrations" python manage.py makemigrations python manage.py migrate echo "Starting server" python manage.py runserver 0.0.0.0:8000 exec "$@" my database settings 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': … -
How to add Q lookups with the get_queryset in Django rest framework?
I have written some filtering code in get_qeuryset function. Also I have a separate search filter api which searches based on the string provided in the query parameter search. Now what I want is add the search query into the former filtering logic so that user can search only in the filtered results and not from the whole database again. My model: class Product(models.Model): WARRANTY = ( ('no_warranty', 'No Warranty',), ('local_seller_warranty', 'Local Seller Warranty',), ('brand_warranty', 'Brand Warranty',), ) merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) category = models.ManyToManyField(Category, blank=False) sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True) mini_category = models.ForeignKey(Minicategory, on_delete=models.SET_NULL, blank=True, null=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) featured = models.BooleanField(default=False) # is product featured? /.........other codes.........../ My filtering view: class ProductAPIView(ListAPIView): permission_classes = [AllowAny] serializer_class = ProductSerializer queryset = Product.objects.all() pagination_class = CustomPagination def get_queryset(self): brand = self.request.GET.get('brand', None) sub_category = self.request.GET.get("sub_category", None) warranty = self.request.GET.get("warranty", None) if brand is not None: brand_values = brand.split(",") if sub_category is not None: sub_category_values = sub_category.split(",") if warranty is not None: warranty_values = warranty.split(",") return Product.objects.filter(brand__name__in=brand_values, sub_category__name__in=sub_category_values, warranty__in=warranty_values) /..........other codes........../ My url to call this localhost/api/products?brand=Samsung,Lg&warranty=no_warranty Q lookup search view: from django.db.models import Q class PrdouctSearchAPIView(ListAPIView): permission_classes = [AllowAny] queryset = Product.objects.all() serializer_class = ProductSerializer pagination_class = … -
How to delete a single data from database in django (not deleting the entire row)
To give you an understanding of my problem, I am showing my code first, then my question. In models.py: class Post(models.Model): content = models.CharField(max_length=140) date_created = models.DateTimeField(auto_now_add=True) poster = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.IntegerField(default=0) liked_by = models.ForeignKey( User, on_delete=models.CASCADE, related_name='liked_by', blank=True, null=True) def serialize(self): return { "id": self.id, "poster": self.poster.username, "poster_image_url": self.poster.image_url, "date_created": self.date_created.strftime("%b %d %Y, %I:%M %p"), "content": self.content, "likes": self.likes,} In views.py: @csrf_exempt def get_post(request, post_id): post = Post.objects.get(pk=post_id) if request.method == "GET": return JsonResponse(post.serialize()) elif request.method == "PUT": data = json.loads(request.body) if data.get('likes') is not None: if data['likes'] > post.likes: post.likes = data['likes'] post.liked_by = request.user else: post.likes = data['likes'] post.liked_by.remove(request.user) post.save() return HttpResponse(status=204) I need to remove request.user from liked_by column in the post object. But this error occurs: AttributeError: 'User' object has no attribute 'remove' How can I solve the problem? -
Django : Add extra action to a SetViewModel while using NestedViewSetMixin
I am trying to add an action to a SetViewModel in Django, this SetViewModel is already using NestedViewSetMixin succefully : here is the structure of my api call : /api/startups/1/investments So this will list all investments for startup with id 1. Now I would like to add an extra action to only display investments for a specific startups that are in active status. The api call would be this way : /api/startups/1/investments/get_active_investment/ At the moment I am getting this error code : AttributeError at /api/startups/1/investments/get_active_investment/ Got AttributeError when attempting to get a value for field `collected_amount` on serializer `InvestmentSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'collected_amount'. Request Method: GET Here is my code for the SetViewModel : class InvestmentViewSet(NestedViewSetMixin, ModelViewSet): """ A viewset that provides `retrieve`, `create`, and `list` actions for Investments. """ model = Investment serializer_class = InvestmentSerializer queryset = Investment.objects.all() @action(detail=False, methods=['Get']) def get_active_investment(self, *args, **kwargs): """Get active investment Only One investment/startup is active """ queryset = self.get_queryset().filter(active=True) serializer = self.get_serializer(queryset, many=False) return Response(serializer.data) -
NoReverseMatch. Reverse for '' not found
I have a django project called main and an application called tracking. I created a register form but when I want to open the register page, I get this error: NoReverseMatch at /tracking/worker_register/ Reverse for 'worker_register' not found. 'worker_register' is not a valid view function or pattern name. My Error: `NoReverseMatch at /tracking/worker_register/ Reverse for 'worker_register' not found. 'worker_register' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/tracking/worker_register/ Django Version: 3.2.9 Exception Type: NoReverseMatch Exception Value: Reverse for 'worker_register' not found. 'worker_register' is not a valid view function or pattern name. Exception Location: X:\Projects\dJira_app\.venv\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: X:\Projects\dJira_app\.venv\Scripts\python.exe Python Version: 3.7.0 Python Path: ['X:\\Projects\\dJira_app\\main', 'X:\\Projects\\dJira_app\\.venv\\Scripts\\python37.zip', 'C:\\Users\\anubi\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\anubi\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\anubi\\AppData\\Local\\Programs\\Python\\Python37-32', 'X:\\Projects\\dJira_app\\.venv', 'X:\\Projects\\dJira_app\\.venv\\lib\\site-packages'] Server time: Mon, 29 Nov 2021 17:49:26 +0000` The urls.py: from django.urls import path from .import views urlpatterns=[ path('register/', views.register, name='register'), path('worker_register/', views.worker_register.as_view(), name=''), path('manager_register/', views.manager_register.as_view(), name=''), ] main URLs: from django.contrib import admin from django.urls import include, path from tracking import views urlpatterns = [ path('tracking/', include('tracking.urls')), path('admin/', admin.site.urls), ] HTML: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h1 class="mt-2">Worker registration</h1> <hr class="mt-0 mb-4"> <form action="{% url 'worker_register' %}" method="POST" novalidate> {% csrf_token %} {{ … -
upload file in django admin without model and use it to update database
I want to upload a CSV file in the admin that adds information to a model. I extended the change_form.html and I overwrote the response_change function in the admin.py: change_form.html: <form method="post" enctype="multipart/form-data"> <input type="file" name="uploadCSV" /> <input type="submit" name="submit" value="upload CSV" accept=".csv"/> </form> admin.py: class StoreAdmin(admin.ModelAdmin): list_display = [..] def response_change(self, request, obj): if "uploadCSV" in request.POST: with open(request.POST["uploadCSV"], encoding="utf8") as f: data = f.read() ... return redirect(".") I end up with: No such file or directory: 'test.csv' because the file is not read in yet, but just a string with the location. How can I actually load the file (temporarily)? -
django.setup(): ModuleNotFoundError: No module named 'api.apps' when DJANGO_SETTINGS_MODULE is set
I am attempting to add entries to a Django Database from an external Python script, but have run into errors when attempting to import my Django Models. I am using venv for both the database and the individual Python script I used the following link: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured to attempt to setup Django before importing my Model, but now I am running into the following error: ModuleNotFoundError: No module named 'api.apps' I also set the Python Path to be at the top of my project directory, which is above both my Database and Python Script. The Python file I am attempting to create is in a different folder from my Database, and here is the code: (Note that my Django database name is database, and is the main part as well. I have "api" as a separate directory.) import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.database.database.settings') import django django.setup() from database.api.models import Example This fails on django.setup(). I have done an alternate attempt with "from database.database.wsgi import *" that results in the same Error. I am unsure of what causes this, as when I run the database, the models in "api" appear just fine, and I do add … -
Django crispy form itself is saving the form, but crispy fields is not saving to the database
This code is saving my form <form method="POST" role="form" enctype="multipart/form-data" id="form-container"> {{ my_form|crispy }} <button type="submit">Submit form</button> </form> But when I use as_crispy_field, It is not submitting at all. <form method="POST" role="form" enctype="multipart/form-data" id="form-container"> {{ my_form.lastName|as_crispy_field }} {{ my_form.firstName|as_crispy_field }} {{ my_form.middleName|as_crispy_field }} {{ my_form.birthData|as_crispy_field }} {{ my_form.nation|as_crispy_field }} {{ my_form.birthPlace|as_crispy_field }} <button type="submit">Submit form</button> </form> -
Invalind linking throws 'id' expected a number but got '{{ navbarList.0.category }}'
I have probably a very simple error but I can't figure it out. I have a category model that looks like this. Navbar field is for putting the category name and link to it in the navbar section on the page. class Category(models.Model): category = models.CharField(max_length=20,unique=True) navbar = models.BooleanField(null=False, blank=False, default=True) def __str__(self): return self.category Due to menu layout looking like this I need to set nav links manually nav - nav - language_changer - nav - nav\ So I've set them like this <a href='{% url "category" category="{navbarList.0.id }" %}'> {{ navbarList.0.category }} </a> <a href='{% url "category" category="{navbarList.1.id }" %}'> {{ navbarList.1.category }} </a> And this throws error ValueError at /category/{{ navbarList.0.id }}/ Field 'id' expected a number but got '{{ navbarList.0.id }}'. -
How to display an error message with a function?
I want to create a basic function for payment. I have several cards and when the user click the button, if the card did not receive a payment this month, it should be refilled, but if did receive a payment this month I want to display an error message in the front end. How can I do it? views.py def paycheck(request, id): card = Card.objects.get(id=id) today = format(datetime.date.today() - datetime.timedelta(days=1), '%B %Y') if card.last_payment != today: if card.type == "City": card.amount = 500 else: card.amount = 300 card.last_payment = today card.save() else: print("Some error message for client") return redirect(request.META['HTTP_REFERER']) def card(request, id): card = Card.objects.get(id=id) restaurants = Restaurants.objects.filter(is_member=True) logs = CardLogs.objects.filter(card_id=id) context = { 'card': card, 'restaurants': restaurants, 'logs': logs } return render(request, "card.html", context) card.html ... <a class="btn btn-success" href="{% url 'paycheck' card.id %}" > Make Payment </a> ... -
save large json objects in postgres, Django
I have a model in db: class Test(models.Model): title = models.CharField(max_length=32, verbose_name='title', default='') json = models.JSONField(default=dict) ... I get the data from the front and save it to the db, requests come in quite often. The average weight of a json field is 10MB, but it can vary greatly and I don’t understand how it would be better for me to save and give it, I don’t do any work with json on server. To begin with, I think need to compress this json and save it to the database and, when requested to receive it, decompress it. Can you please advise me on the best way to save memory and query execution time. Also, is it worth removing this json in a separate table so that changing other data in the test table takes less time, or is it better to use Test.objects.update()? -
Why the login_required decorator doesn't work?
Working on a simple project using Django 3.2 and the loqin_required decorator is not working. When I close the server and re-open it again, it works the first time but not anymore. It used to work very well, but I'm not sure what I changed in the code that it doesn't work anymore. views.py from django.http.response import HttpResponse from django.shortcuts import render, redirect from django.utils import timezone from django.db.models import Count from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.contrib import messages from .models import * from .models import __str__ from .forms import CreateUserForm # Create your views here. @login_required(login_url='login/') def home(request): count_item = todo.objects.count() all_items = todo.objects.all().order_by("created") context = {'all_items': all_items, 'count_item':count_item} return render(request, 'html/home.html', context) @login_required(login_url='login/') def add_todo(request): current_date = timezone.now() new_item= todo(content = request.POST["content"]) new_item.save() return redirect('/') @login_required(login_url='login/') def delete_todo(request, todo_id): item_to_delete = todo.objects.get(id=todo_id) item_to_delete.delete() return redirect('/') urls.py from django.urls import path from django.views.generic.base import RedirectView from . import views app_name = 'todo' urlpatterns = [ path('', views.home, name="home"), path('add_todo/', views.add_todo), path('delete_todo/<int:todo_id>/', views.delete_todo), path('login/', views.login_user, name='login'), path('logout/', views.logoutUser, name='logout'), path('register/', views.register_user, name="register"), ] Any suggestion or response would appreciate it Thanks! -
Can I run 2 gunicorn doing different tasks to one and other on one server?
Currently I am running with 1 worker. I want to increase my number of workers. But now if I increase the number of workers my background services will also increase. Leads to duplicate data. For example: I have an email inbox scanning service that runs on repeat every minute. If there is new email will generate data in mongoDB. So if run with 1 worker it's fine. but when increase to 3 workers it will loop, resulting in 1 email coming it will scan 3 times and generate 3 data on mongoDB. My idea would be to separate the services that run repeatedly for a period of time that will run gunicorn with 1 worker. The remaining Gunicorn will run with 3 workers to increase API processing performance. According to the manual: recommend (2 x $num_cores) + 1 as the number of workers to start off with. My computer has 4 CPUs. So I will follow the formula (2 * core) + 1. We get (2 * 4) + 1 = 9 is the number of workers that are suitable for the system. - I use 8 workers to run the first Gunicorn to process the API with port 8000: … -
How to create a tag input field in django
I am trying to create an input field for tags in django. I've see streamlit enables to do it (https://discuss.streamlit.io/t/new-component-streamlit-tags-a-new-way-to-do-add-tags-and-enter-keywords/10810), and I am sure it is doable in django. I'd like to have all tags be read from a list/dict and possibly even have the autocomplete suggestions. I did see it on many sites, but I can't find a tutorial to insert it into the django project. Thanks! -
Getting a JSON string via the Django API in Android
I'm trying to get a JSON string by JSON with the API. The API is self-made (very simple) on Django. If you open /127.0.0.1:8000/get_last_data in the browser, then everything is displayed. I tried to run it on the emulator (using /10.0.0.2:8000/get_last_data) I get an error - Failed to connect to /10.0.0.2:8000. I tried to run on a real device (/192.168.0.104:8000/get_last_data) I get - Failed to connect to /192.168.0.104:8000. I tried using a third-party API - it works. Tell me what to do? I apologize for my English -
I get a invalid TemplateSyntaxError in Django for using the {% else %}-statement
My django-project (a tutorial https://www.youtube.com/watch?v=PtQiiknWUcI) keeps crashing on the basis that it doesn't accept my '{% else %}'-statement. I can't wrap my head around it. {% if request.user.is_authenticated %} <div class="header__user"> <a href="profile.html"> <div class="avatar avatar--medium active"> <img src="{{request.user.avatar}}" /> </div> <p>{{request.user.username}} <span>{{request.user.username}}</span></p> </a> <button class="dropdown-button"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"> <title>chevron-down</title> <path d="M16 21l-13-13h-3l16 16 16-16h-3l-13 13z"></path> </svg> </button> </div> {% else %} <a href="{% url 'login' %}"> <img src="./assets/avatar.svg" /> <p>Login</p> </a> {% endif %} Django gives me a TemplateSyntaxError with the text: 'Invalid block tag on line 82: 'else'. Did you forget to register or load this tag?' The if-statement is there to control if the user is logged in. The 'else-statement' is there to show someone the inlog-page when not logged in. I tried to google this. But for other people this 'error' comes up when they wrote there if-statement wrong. I hope that someone can help me. It's so frustrating. -
Django interprets safe filter weirdly
at start I will mention that I'm not a backend developer, so please be gentle :p We have a django template however I have a strange problem with data that is a rich-text. Example: template: <p class="correctClass">{{team.description|safe}}</p> source code for team.description in our CMS: <p>Correct text</p> result: <p class="correctClass"></p> <p>Correct text</p> <p></p> without safe filter it's like that: <p class="correctClass"> <p>Correct text</p> (this line is text, not parsed as html) </p> Of course wanted output is: <p class="correctClass">Correct text</p> -
Model in Django training course project
I was adding training courses to my project, but in the model writing section I came across a question: The question was whether I should have a model for the specifications of all training courses (including name, description, price, etc.) along with a Have a model for the content of all courses (including course content and textbooks)? I did the same, but when I wanted to go to the next section for each textbook with the help of id, he realized that the content of another course might come because maybe the next ID is for another course! Please help me in this regard and tell me how should I write my model? And if I have to write like this, do I have to put a field in the content model to specify which period the content is from? But I think this method is not very suitable. Pictures of models: -
How to make users edit field.options in Django?
I am making an app where users can track their income and expenses. I want each transaction to be categorized based on where it is stored - like in checking, credit, savings, wallet, gift card, venmo, etc. I am planning to use Django Field.choices but the options are permanent and I want the users to edit their own choices. How can I do that? -
How to display your queries using filter?
So I am trying to set up a filter for my website and it is not working; It does not give me an error and the url updates like a query is being made but when I click "submit" it still shows all of the content in the page. I can't quite figure out what is wrong. filters.py import django_filters from django_filters import DateFilter from .models import * class UserpostFilter(django_filters.FilterSet): start_date = DateFilter(field_name = "date_published", lookup_expr='gte') end_date = DateFilter(field_name = "date_published", lookup_expr='lte') class Meta: model = Userpost fields = '__all__' exclude = ['image', 'user', 'date_published'] models.py class Userpost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) Year = models.CharField(max_length = 4) Mileage = models.CharField(max_length = 8) Make = models.CharField(max_length = 50) Model = models.CharField(max_length = 50) Price = models.DecimalField(max_digits=15, decimal_places=2) email = models.EmailField() date_published = models.DateField(default = timezone.now) image = models.ImageField(null = True, blank = True, upload_to = r"C:\Users\gabri\Desktop\test\ecommerce\static\images") def __str__(self): return self.Year + " " + self.Make + " " + self.Model @property def imageURL(self): try: url = self.image.url except: url = '' return url views.py def posts(request): cars = Userpost.objects.all() p = Paginator(Userpost.objects.all(), 9) page = request.GET.get('page') cars_list = p.get_page(page) nums = "a" * cars_list.paginator.num_pages myFilter = UserpostFilter(request.GET, queryset = … -
FieldError when creating User Model Types
I have been trying to customise User Model such that it can have different roles and i'm stuck. I can't figure out what i'm missing or when i went in the wrong direction. I'm supposed to create 4 roles Teacher, Student, Parent and HeadTeacher. Here is my models.py: #importing modules from django.db import models from django.db.models.fields import proxy from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin, AbstractUser from django.utils import timezone from class_apps.models import Classes from class_apps.models import Subjects from phone_field import PhoneField ####MODELS #Managers class UserManager(BaseUserManager): def _create_user(self, username, password, is_staff, is_superuser, is_active, **extra_fields): if not username: raise ValueError('Users must have an username') now = timezone.now() user = self.model( username=username, is_staff=is_staff, is_active=is_active, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, username=None, password=None, is_active=True, **extra_fields): return self._create_user(username, password, False, False, is_active, **extra_fields) def create_superuser(self, username, password, **extra_fields): user = self._create_user(username, password, True, True, True, **extra_fields) user.save(using=self._db) return user def save(self, *args, **kwargs): if not self.pk: self.type = User.Types.STUDENT return super().save(*args, **kwargs) class TeacherManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter(base_type=User.Types.TEACHER) class StudentManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter(base_type=User.Types.STUDENT) class ParentManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter(base_type=User.Types.PARENT) def create_parent(self, user, title, surname,other_names,email,phone_no,address,gender,marital_status,proposed_wards): … -
Modify model value when retrieved in django
I have a model that save created_at in UTC format in database. When I want to show it to the user I want the datetime is shown in TIME_ZONE that I set in settings.py(which is 'Asia/Jakarta'). Right now every time I want to show it to the user, I have to manually change it using timezone.localtime(). Is there a way to automatically set the datetime to 'Asia/Jakarta' when field is retrieved from the model? Here is my model: from django.db import models class Product(models.Model): name = models.CharField(max_length=255) quantity = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'product' def __str__(self): return self.name -
Multiple Websites in Django - Gunicorn-Nginx
Please i have deploy a project in Digital Ocean and made all theese Made The DB mkdir pyapps 3 .python3 -m venv ./venv 4 .source venv/bin/activate 5 .pip install -r requirements.txt 6 .Made the settings.py try: from .local_settings import * except ImportError: pass Run Migrations python manage.py makemigrations 8 . python manage.py migrate 9 .Create super user 10 . Create static files 11 .python manage.py collectstatic 12 .Create exception for port 8000 python manage.py runserver 0.0.0.0:8000 I made the above until there TWICE for 2 websites in Django and of course there are working when i go in their seperated VENV and make python manage.py runserver 0.0.0.0:8000 After all these Gunicorn comes up.... i made a full search and i can not find Nowhere what happens if i can run both of them in a single droplet. There need to be 2 sockets? 2 services and after that 2 sites available? and link to 2 sites enable folder????! do i miss something because i canot not understand..do you have any tutorial for multiple websites deploy in droplet with nginx and gunicorn?