Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use django_private_chat2
I want to use this package for my localhost website but it show the error: Using the URLconf defined in dimsum.urls, Django tried these URL patterns, in this order: admin/ profiles/ restaurants/ messages/ [name='all_messages_list'] messages/<dialog_with>/ [name='messages_list'] dialogs/ [name='dialogs_list'] self/ [name='self_info'] upload/ [name='fileupload'] I done all the steps in quick start of this package but it not working. Install django_private_chat2: pip install django_private_chat2 Add it to your INSTALLED_APPS: INSTALLED_APPS = ( ... 'django_private_chat2.apps.DjangoPrivateChat2Config', ... ) Add django_private_chat2's URL patterns into my url file: from django.urls import re_path, include urlpatterns = [ ... re_path(r'', include('django_private_chat2.urls', namespace='django_private_chat2')), ... ] Add django_private_chat2's websocket URLs to my asgi.py: import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from django_private_chat2 import urls os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dimsum.settings') # application = get_asgi_application() django_asgi_app = get_asgi_application() application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AuthMiddlewareStack( URLRouter(urls.websocket_urlpatterns) ), }) I all so run this command before run server python manage.py migrate Please tell me what am I missing? -
Encountring Error While installing django dependency "Building wheel for xmlsec (pyproject.toml) ... error error: subprocess-exited-with-error"
I am using this command to install dependencies for django project pip install -r requirements.txt ` Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done Collecting yarl==1.7.2 (from -r requirements.txt (line 369)) Using cached yarl-1.7.2-cp38-cp38-macosx_10_9_x86_64.whl (121 kB) Collecting zipp==3.1.0 (from -r requirements.txt (line 371)) Using cached zipp-3.1.0-py3-none-any.whl (4.9 kB) Requirement already satisfied: setuptools>=3.0 in ./kit/lib/python3.8/site-packages (from gunicorn==20.1.0->-r requirements.txt (line 154)) (56.0.0) Building wheels for collected packages: xmlsec, django-rest-hooks Building wheel for xmlsec (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for xmlsec (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [65 lines of output] running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.9-x86_64-cpython-38 creating build/lib.macosx-10.9-x86_64-cpython-38/xmlsec copying src/xmlsec/py.typed -> build/lib.macosx-10.9-x86_64-cpython-38/xmlsec copying src/xmlsec/tree.pyi -> build/lib.macosx-10.9-x86_64-cpython-38/xmlsec copying src/xmlsec/init.pyi -> build/lib.macosx-10.9-x86_64-cpython-38/xmlsec copying src/xmlsec/constants.pyi -> build/lib.macosx-10.9-x86_64-cpython-38/xmlsec copying src/xmlsec/template.pyi -> build/lib.macosx-10.9-x86_64-cpython-38/xmlsec running build_ext building 'xmlsec' extension creating build/temp.macosx-10.9-x86_64-cpython-38 creating build/temp.macosx-10.9-x86_64-cpython-38/private creating build/temp.macosx-10.9-x86_64-cpython-38/private/var creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders/0f creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-install-y3izz7rd creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-install-y3izz7rd/xmlsec_1b2a1e6a17e447509a7b6137df7d3b99 creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-install-y3izz7rd/xmlsec_1b2a1e6a17e447509a7b6137df7d3b99/src gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -D__XMLSEC_FUNCTION__=func -DXMLSEC_NO_FTP=1 -DXMLSEC_NO_MD5=1 -DXMLSEC_NO_GOST=1 -DXMLSEC_NO_GOST2012=1 -DXMLSEC_NO_CRYPTO_DYNAMIC_LOADING=1 -DXMLSEC_CRYPTO_OPENSSL=1 -DMODULE_NAME=xmlsec -DMODULE_VERSION=1.3.12 -I/opt/homebrew/Cellar/libxmlsec1/1.3.1_1/include/xmlsec1 -I/opt/homebrew/opt/openssl@3/include -I/opt/homebrew/opt/openssl@3/include/openssl -I/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-build-env-5ws1iwun/normal/lib/python3.8/site-packages/lxml/includes -I/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-build-env-5ws1iwun/normal/lib/python3.8/site-packages/lxml -I/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-build-env-5ws1iwun/normal/lib/python3.8/site-packages/lxml/includes/pycache -I/Users/nehanegi/Downloads/analytickit-first/kit/include -I/Library/Frameworks/Python.framework/Versions/3.8/include/python3.8 -c /private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-install-y3izz7rd/xmlsec_1b2a1e6a17e447509a7b6137df7d3b99/src/constants.c -o … -
Django connection.queries is not running in server
I am executing following code in views.py file on dev server hosted on AWS EC2 instance and my settings.py file has DEBUG = True configured. from django.db import connection from project.models import MyModel mymodels = MyModel.objects.all() print("My models: ", mymodels) raw_queries = connection.queries print("raw query: ", raw_queries) Output is: My models: [<myModel 1>, <myModel 2>,<myModel 3>] raw query: [] I am not sure, what i am missing. why raw query = []. I tried doing with python3 manage.py shell but same thing happend there too. but same result raw query = [] -
Django: Serpy serializer django model JsonField
I am using serpy to serialize my model, so my model has a JSONField containing list of dict. Here is my model: class Section(models.Model): title = models.CharField(max_length=255, null=False) item_count = models.IntegerField(default=0) # The JSON field contents = models.JSONField(blank=True, null=True) I am trying to use serpy.DictSerializer to serialize the contents field but it results in empty dict {} . This is my serializer: class SectionSerializer(serpy.Serializer): title = serpy.StrField() item_count = serpy.IntField() data = serpy.MethodField() def get_data(self, obj): return serpy.DictSerializer(obj.contents, many=True).data As contents is a list of dicts, I have used many=True, But still it is not helping. -
What does this symbol mean "[...]" in docstrings?
I've seen this multiple times now in different python documents. For example: python code The above is from a website that I just saw today and the rest is code written in Django. I see this symbol being regularly used in different documentations. -
Alpine.js x-bind not applying after an HTMX swap
I have an element that is in the initial page load and updates after form post through an HTMX out of bounds swap. On initial load the x-bind formats as expected. After the swap the values from the swapped element display as expected using x-text. The x-bind always fails to apply the formatting that should trigger when staffCount < shiftNeed. When it should apply it quickly flickers immediately after the swap but then goes away. Same flicker is not present when it should not apply. Element on initial page load <tr x-data="{ shiftNeed: {{ day_need }} }"> <td class="fw-bold">Day</td> <td class="fw-bold text-center" x-text="shiftNeed"></td> {% for i, val in day_list|zip:day_staffing %} <td> <div id="dayCount{{ i }}" x-data="{ staffCount: {{ val }} }" x-text="staffCount" x-bind:class="{ 'bg-danger': staffCount < shiftNeed }" ></div> </td> {% endfor %} </tr> Partial template swapped in {% include "schedule/components/schedule_shift_button.html" %} <div id="{{ shift.time_of_day_label|lower }}Count{{ shift.day_num }}" class="text-center rounded" hx-swap-oob="true" x-data="{ staffCount: {{ shift.staff_count }}}" x-text="staffCount" x-init="console.log(staffCount < shiftNeed)" x-bind:class="{ 'bg-danger': staffCount < shiftNeed }" ></div> I added logging statements on the x-init to inspect output, console always displays the expected values of staffCount and shiftNeed and evaluates the criteria used in the x-bind as expected. -
Why when I create an enviroment with anaconda in Visual Studio Code and I try to activate it, shows me an error
I try to activate the env that I already created and everything fine, but when I tried the command "conda activate whynotdata" it shows me this error: PROGRAMACION\Data_base_whynot> conda activate whynotdata usage: conda-script.py [-h] [--no-plugins] [-V] COMMAND ... conda-script.py: error: argument COMMAND: invalid choice: 'activate' (choose from 'clean', 'compare', 'config', 'create', 'info', 'init', 'install', 'list', 'notices', 'package', 'remove', 'uninstall', 'rename', 'run', 'search', 'update', 'upgrade', 'build', 'convert', 'debug', 'develop', 'doctor', 'index', 'inspect', 'metapackage', 'render', 'skeleton', 'verify', 'token', 'pack', 'server', 'env', 'content-trust', 'repo') When I create it with the anaconda prompt everything works fine but in Visual Studio Code I can't complete it, and I want to create my env on the folder that I have on Visual Studio, I am a begginer in the back-end, I am of autodidact learning. Thank you I am trying to create an env on a folder that I create and then install django, I want to use Anaconda to create the project but it didn't work and is rare because on the config of my sistem I added the path to the environments of windows, of the anaconda3 and anaconda3\scripts -
Django cap a DateField value in the database
Sorry I am very new to Django. I have date of birth (DOB) as a field in my model. I use the DOB to calculate the age and get some values from other dataset. class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) dob = models.DateField(blank=True, null=True) The age cannot be higher than 120 years so I raise a ValidationError with the registration and update profile forms whenever they enter a DOB of more than 120 years ago. def clean(self): cleaned_data = super(RegistrationForm, self).clean() dob = self.cleaned_data.get('dob') age = (date.today() - dob).days / 365 if age > 120: raise forms.ValidationError('Sorry but profiles cannot be registered with more than 120 years old due to scientific data unavailability.') elif age < 0: raise forms.ValidationError('Date of birth is in the future. Please enter valid birth date.') However, what if they register as born 119 years ago. In 1 or 2 years, the age would be 121 and my code will fail. Is there a way to always cap the value of the DOB in my database so the DOB is always maximum 120 years old? I checked the documentation for DateField but there is no reference to MinValueValidator as in the case of IntegerField. -
Ingress health check failing on Django GKE Deployemnt
I am deploying a frontend (Nuxt) and a backend (Django) using GKE Autopilot. A CI/CD pipeline has been set up from github to GKE. The frontend gets deployed and easily viewable on xpresstracker.app while the backend spits out server error 501 on backend.xpresstracker.app. Below is the related configurations and error; Error message prodservice.yaml apiVersion: v1 kind: Service metadata: name: prod-xpressbackend-service spec: selector: app: prod-xpressbackend ports: - protocol: TCP port: 8000 targetPort: 8000 type: NodePort prodmanagedcert.yaml apiVersion: networking.gke.io/v1 kind: ManagedCertificate metadata: name: prod-managed-cert spec: domains: - xpresstracker.app - backend.xpresstracker.app prodingress.yaml apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: prod-ingress annotations: kubernetes.io/ingress.global-static-ip-name: xpresstrackerip networking.gke.io/managed-certificates: prod-managed-cert kubernetes.io/ingress.class: "gce" labels: app: prod-xpressbackend spec: rules: - host: xpresstracker.app http: paths: - path: / pathType: Prefix backend: service: name: prod-xpressfrontend-service port: number: 3000 - host: backend.xpresstracker.app http: paths: - path: / pathType: Prefix backend: service: name: prod-xpressbackend-service port: number: 8000 Deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: prod-xpressbackend-deployment labels: app: prod-xpressbackend spec: replicas: 1 selector: matchLabels: app: prod-xpressbackend template: metadata: labels: app: prod-xpressbackend spec: containers: - name: prod-xpressbackend-container image: someimage:production imagePullPolicy: Always resources: requests: memory: "200Mi" cpu: "0.2" limits: memory: "512Mi" cpu: "0.5" ports: - containerPort: 8000 env: - name: SECRET_KEY valueFrom: secretKeyRef: name: proddatabasecredentials key: SECRET_KEY - … -
Custom Django Admin Page/View
Basically I'm trying to create a custom admin web page, like a custom a view. Ideally what I want is something where like once you log in to the admin page, there would be a link somewhere like under the list of models that would redirect you to this admin center. I have a somewhat working version currently, but I would like to have it redirect to a new URL like “ /admin/social/edit/ “ instead and not just render context into the template. I’ve done a ton of googling and I just keep coming across things like “custom admin actions” which is not per se what I’m looking to do. Any help is appreciated. Thank you. -
Trying to delete an item from webpage rendered by django results in all items below it to also be deleted
In my project I have a cart application that displays any items the user decided to add to the cart. Template: {% extends '../main.html' %} {% load static %} {% block title %}Cart Summary{% endblock %} {% block content %} <main class = "pt-5"> <div class = "container"> <h1 class = "h5">Shopping Cart</h1> {% for item in cart %} {% with product=item.product %} <div data-index = "{{product.id}}" class = "row g-3 product-item"> <div class = "col-md-5 col-lg-5 order-mg-first"> <img class = "img-fluid mx-auto d-block" width = "200px" alt = "Responsive image" src = "{{ product.image.url }}" /> </div> <div class = "col-md-7 col-lg-7 ps-md-3 ps-lg-5"> <h1 class="mb-0 h4">{{ product.title }}</h1> <p><span class="lead">{{ product.author }}</span> (Author)</p> <p>{{ product.description|slice:":355" }}...</p> <div class="border"> <div class="col border-bottom"> <div class="row p-3"> <div class="col-6">Hardback</div> <div class="col-6 text-end"><span class="h4 fw-bold">{{ product.price }}€</span></div> </div> </div> <div class="col"> <div class="row p-3"> <div class="col-6"> <label for="select">Qty</label> <select id="select{{product.id}}"> <option selected> {{item.qty}} </option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> <button type="button" id = "update-button" data-index = "{{product.id}}" class="btn btn-secondary btn-sm update-button"> Update </button> <button type="button" id = "delete-button" data-index = "{{product.id}}" class="btn btn-secondary btn-sm delete-button"> Delete </button> </div> </div> </div> </div> </div> {% endwith %} {% endfor %} … -
How can I set group permissions that filter pages according to their owners in Wagtail
I am working on a blog with Wagtail and would like to give users access to create their own content in the Wagtail admin. I would like users to be able to log into the Wagtail admin, but only have access to content that they have created themselves. I have tried to generate permissions by group, however there is no default option to limit content by author, so if I give add, edit and publish permissions, a user could edit content created by other users and could unpublish or even delete that content. I would like to know if there is a way to modify the queryset of pages that appear in the Wagtail admin for a specific user. I don't have much experience with Wagtail. So far I have seen some possible solutions but none have seemed viable or adequate. For example, there are some posts here where they propose to create a Parent page for each user, but then you would have to create a group for each user, which doesn't seem like an efficient way to do it. I appreciate any help or suggestions. Here I share some of the relevant code: class BlogIndexPage(Page): max_count = 1 … -
Django: signal doesn't work well with ForeignKey
models.py from django.db import models class Post(models.Model): text = models.TextField() approved = models.BooleanField(default=False) group = models.ForeignKey('bot_users.BotUserGroup', on_delete=models.SET_NULL, null=True, blank=True) from django.conf import settings from django.db import models import os class PostMedia(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='mediafiles') media = models.FileField(upload_to='post_media/', blank=True) absolute_media_path = models.CharField(max_length=255, blank=True) def save(self, *args, **kwargs): self.absolute_media_path = self.get_absolute_media_path() return super().save(*args, **kwargs) def get_absolute_media_path(self): return os.path.join(settings.BASE_DIR, self.media.path) #Post.objects.last().mediafiles.last().absolute_media_path services.py (functions for aiogram bot and django) async def get_post_path(post_id): url = f'http://localhost:8000/api/get_media_urls/{post_id}/' async with aiohttp.ClientSession() as session: async with session.get(url) as response: if response.status == 200: data_list = await response.json() return data_list else: return None async def register_manager(CHAT_ID: str): fake = Faker() username = fake.user_name() password = fake.password() await bot.send_message(CHAT_ID, f'username: {username}\npassword: {password}\nadmin-panel: http://localhost:8000/admin', reply_markup=set_manager_kb()) # async def send_post(instance): # admin_id = '679553167' # await bot.send_message(admin_id, f'{instance}', reply_markup=set_post_kb()) async def send_post(post): message = post.split('\n') user_id = '679553167' post_id = message[0] media = [] media_paths = await get_post_path(post_id) if media_paths: for photo_path in media_paths: if photo_path.lower().endswith(('.jpg', '.jpeg', '.png')): media_type = types.InputMediaPhoto elif photo_path.lower().endswith(('.mp4', '.avi', '.mkv')): media_type = types.InputMediaVideo else: continue photo_file = open(photo_path, 'rb') input_media = media_type(media=types.InputFile(photo_file)) media.append(input_media) media[0]["caption"] = message[1] await bot.send_media_group(chat_id=user_id, media=media, reply_markup=set_post_kb()) photo_file.close() else: await bot.send_message(user_id, message[1], reply_markup=set_post_kb()) signals.py from django.db.models.signals import post_save from django.dispatch import receiver … -
cant create new model object django rest framework
model.py from django.db import models from django.contrib.auth.models import User class Task(models.Model): title = models.CharField(max_length=30) description = models.TextField() deadline = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey('auth.User', on_delete=models.CASCADE) def __str__(self): return self.title serializers.py from django.contrib.auth.models import User from .models import Task from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): tasks = serializers.PrimaryKeyRelatedField( many=True, queryset=Task.objects.all()) class Meta: model = User fields = ['id', 'username', 'email', 'tasks'] class AuthSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password'] class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ['id', 'title', 'description', 'deadline', 'created_at', 'updated_at'] views class CreateTask(generics.CreateAPIView): authentication_classes = [authentication.SessionAuthentication] permission_classes = [permissions.IsAuthenticated] queryset = Task.objects.all() serializer_class = TaskSerializer in the command line it says 'null value in column "userid" of relation "srctask" violates not-null constraint', do i have to access the userid by another way and attach it to the model object? -
Django - AttributeError: 'Index' object has no attribute 'constraint_type'
I am using Django 4.2.2 This is a model that is throwing the subject jessage in an error, when I run makemigrations: class AnonymousInteractionMonitor(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name='%(app_label)s_%(class)s_content_types', related_query_name='%(app_label)s_%(class)s_content_type') object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') interaction_type = models.PositiveSmallIntegerField(choices=Engagement.ENGAGEMENT_TYPES, null=False) visitor_ip = models.GenericIPAddressField(db_index=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('visitor_ip', 'content_type', 'interaction_type') constraints = [ models.UniqueConstraint(fields=['visitor_ip', 'content_type', 'interaction_type'], name="idx_visitor_inf" ) ] The constraint is not defined on an Index, so why am I getting this error message, and how do I fix it? -
error during installation of virtual environment
I face with folliowing error when I want to install virtual env: C:\Users\MICROSOFT\Desktop\django_project>virtualenv venv 'virtualenv' is not recognized as an internal or external command, operable program or batch file. How it could be tackled? -
new collation (English_world.1252) is incompatible with the collation of the template database (English_World.1252)
I'm trying to test with Django, pytest-django and PostgreSQL on Windows 11. But I got the error below: psycopg2.errors.InvalidParameterValue: new collation (English_world.1252) is incompatible with the collation of the template database (English_World.1252) Even though I set English_World.1252 to LC_COLLATE and LC_CTYPE in run_sql() as shown below. *I wrote the code below to connect to PostgreSQL in conftest.py following the doc: # "conftest.py" import pytest from django.db import connections import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT def run_sql(sql): conn = psycopg2.connect(database='postgres', user='postgres', password='admin') conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = conn.cursor() cur.execute(sql) conn.close() @pytest.fixture(scope='session') def django_db_setup(): from django.conf import settings settings.DATABASES['default']['NAME'] = 'copied_postgres' run_sql('DROP DATABASE IF EXISTS copied_postgres') run_sql(""" CREATE DATABASE copied_postgres LC_COLLATE = 'English_World.1252' # Here LC_CTYPE = 'English_World.1252' # Here TEMPLATE postgres""") yield for connection in connections.all(): connection.close() run_sql('DROP DATABASE copied_postgres') And, this is test_get_username() below in test_ex1.py: # "test_ex1.py" @pytest.mark.django_db def test_get_username(): user = User.objects.create_user("test-user") user.username = "John" assert user.get_username() == "John" So, how can I solve the error? -
Django Integrity error at .... null value in column
New to Django, getting a violates not-null constraint, thats preventing it posting to my DB(elephantSQL), I cant seem to get around this issue even when passing the post.id in urls, in the 'buttons' and the view.... Im not sure what I'm doing wrong hopefully someone can point me in the right direction? I have very little experience with this and im trying to learn I have tried a good few things, tho I cant seem to get it to post. HELP!!!! Views def createReview(request): form = ReviewForm() if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): form.save() return redirect('market_posts/') context = {'form': form} return render(request, 'market/review_form.html', context) Models from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator from cloudinary.models import CloudinaryField STATUS = ((0, "Draft"), (1, "Published")) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="market_posts") updated_on = models.DateTimeField(auto_now=True) content = models.TextField() featured_image = CloudinaryField('image', default='placeholder') excerpt = models.TextField(blank=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) likes = models.ManyToManyField(User, related_name='likes', blank=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() class Comment(models.Model): comment = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() … -
using mongodb with motor driver and django
i'm creating an App, using async driver(motor) for mongodb. I have a telegram bot app and django framework app. I want my telegram and web apps use same database. When i try to create User via integrated CreateView class, by default django uses it's standart auth processing and adds user to its default databases(sqlite, postgre etc.) But i'd like to use mongodb and use it asyncronous(as i understood djongo is syncronous driver) the ways I see to solve this: 1) separate users' auth data(to standart database) and other data, that'll be fetched and overwritten frequently(to mongo). 2) use standart view(e.g. TemplateView, FormView) and my own form, write MyOwnUserClass with hashing and all necessary methods. Shortly I want to use instruments of Django with mongodb, how can I reach that? Well don't know if this is needed here, a piece of my current code: forms.py: class RegisterUserForm(UserCreationForm): username = forms.CharField email = forms.EmailField password = forms.PasswordInput password_confirm = forms.PasswordInput telegram = forms.CharField(required=False) views.py: class Register(CreateView): template_name = 'AIsite/register.html' form_class = RegisterUserForm success_url = reverse_lazy('login-user') -
Django admin page looks primitive
for reference: i am learning django from this page:- https://www.w3schools.com/django/django_admin.php im using virtual environment and running this on a local machine: http://127.0.0.1:8000/admin/ Expected output Reality please help. i have tried asking in subreddit and discord but im not yet able to find a fix. any help is appreciated -
WARNINGS: ?: (staticfiles.W004) The directory '/var/www/static/' in the STATICFILES_DIRS setting does not exist
Estoy aprendiendo django y me aparece el error WARNINGS: ?: (staticfiles.W004) The directory '/var/www/static/' in the STATICFILES_DIRS setting does not exist. y no me deja realizar cambios en mis archivos estaticos y no se como solucionarlo intente probando con import os y cambiando STATICFILES_DIRS por STATICFILES_DIRS = \[os.path.join(BASE_DIR, "static")\] pero aun nada -
How to limit client IP of a Django app? (Through django and/or PaaS)
I am making a Django app and I wish to enhance the security as well as limit users by making sure only clients only from one IP (say a shared VPN) can access it. I plan to host the app on a PaaS like Digital Ocean App Platform or Heroku. How can I limit the client IP through: Django, to prevent other users from accessing the app, and The PaaS, so that potential attackers don't have access to the platform in the first place? (Hopefully some PaaS has this optiont) -
Model registration in django in admin.py multi model (choicefield selection)
here is my admin.py class ResumeAdmin(admin.ModelAdmin): def get_fields(self, request, obj=None): fields = ['category'] if obj: if obj.category == 'Summary': fields.extend(['summary_title', 'summary_description', 'summary_address', 'summary_phone', 'summary_email']) elif obj.category == 'Education': fields.extend(['edu_title', 'edu_course', 'edu_start_date', 'edu_end_date', 'edu_gpa']) elif obj.category == 'Experience': fields.extend(['exp_title', 'exp_date', 'exp_where', 'ext_explanation', 'exp_project_link']) elif obj.category == 'Projects': fields.extend(['project_title', 'project_description', 'project_link']) elif obj.category == 'Certifications': fields.extend(['cert_title','cert_date', 'cert_where', 'cert_explanation','cert_project_link']) return fields admin.site.register(Resume, ResumeAdmin) and this is my model.py class Resume(models.Model): CATEGORY = ( ('Summary', 'Summary'), ('Education', 'Education'), ('Experience', 'Experience'), ('Projects', 'Projects'), ('Certifications', 'Certifications'), ) # view different fields according to the category category = models.CharField(max_length=20, choices=CATEGORY, default='Projects') class Summary(models.Model): resume = models.ForeignKey(Resume, on_delete=models.CASCADE) summary_title = models.CharField(max_length=100) summary_description = models.TextField() summary_address = models.CharField(max_length=200) summary_phone = models.CharField(max_length=20) summary_email = models.EmailField() # 2 Education option will have title, course, start_date, end_date, GPA class Education(models.Model): resume = models.ForeignKey(Resume, on_delete=models.CASCADE) edu_title = models.CharField(max_length=100) edu_course = models.CharField(max_length=100) edu_start_date = models.DateField() edu_end_date = models.DateField() edu_gpa = models.FloatField() # 3 experience filed will have same as education filed class Experience(models.Model): resume = models.ForeignKey(Resume, on_delete=models.CASCADE) exp_title = models.CharField(max_length=100) exp_date = models.CharField(max_length=100) # it holds the start and end year of the course exp_where = models.CharField(max_length=200) # college or school name ext_explanation = models.TextField() exp_project_link = models.URLField() # 4 projects filed will have … -
Heroku can't find styles.css
Trying to deploy a Django app to Heroku for the first time. When I view the app using Django, everything shows up correctly, but when I run it on Heroku, pieces of the UI are missing. I'm not too familiar with the frontend - this was a group project and I was working on backend - and my team isn't willing to help with deployment, so I'm unable to diagnose any frontend issues. Looking at the Heroku logs, I get this error "Not Found: /static/styles.css" - but there is a styles.css file under static. Does anyone know where the root problem might lie? Under settings.py I have specified this STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles')] All functionalities work as expected, I think it has something to do with the base.html file - but this is just a stab in the dark. An example of what it's meant to look like, compared to what it looks like on Heroku. -
Django path not matching with urlpatterns in urls.py
Guys I am not a web developer, I have been learning django for a couple of hours now for my father's small business website and I am hitting a silly error for hours now. the name of the project is mysite and mysite urls.py looks like this from django.contrib import admin from django.urls import include, path urlpatterns = [ path("", include("index.urls")), path("about/", include("about_page.urls")), path("polls/", include("polls.urls")), path("admin/", admin.site.urls), ] mysite's settings.py also includes the correct AppConfig for the app. about_page included. INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'index.apps.IndexConfig', 'about_page.apps.AboutPageConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] about_page's views.py is attached_below from django.shortcuts import render from django.http import HttpResponse from django.template import loader from django.http import Http404 # Create your views here. # return HttpResponse("website under construction !!!") def about_func(request): template = loader.get_template("about/about_page.html") context = { "about":"about_us", } return HttpResponse(template.render(context, request)) about_page's urls.py: from django.urls import path from . import views urlpatterns = [ path("about/", views.about_func, name="about_page"), ] polls and index apps have exact same pattern, i simply don't know why i cannot display about page.