Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display a friend request button on each post?
I'm trying to make each post from all users have a friend request button for each specific user who uploaded post on homepage. This code below is what I have tried but friend request button is not displayed on each post. I have also tried using a boolean field but still same problem. What could I have been doing wrong? class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) class Post(models.Model): poster_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, blank=True,null=True) caption = models.TextField(blank=True, null=True) class FriendRequest(models.Model): from_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='from_user') to_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='to_user') def ForYouView(request): page_title = "For You" poster_profile = Post.objects.all() all_profile_users = [] button_status_list = [] for user_obj in p: u = user_obj.user all_profile_users.append(u) # sent_friend_requests = FriendRequest.objects.filter(from_user=u) # rec_friend_requests = FriendRequest.objects.filter(to_user=u) friends = Profile.objects.filter(user=request.user, friends__id=user_obj.id).exists() button_status = 'none' if not friends: button_status = 'not_friend' if len(FriendRequest.objects.filter( from_user=request.user).filter(to_user=u)) == 1: button_status = 'cancel_request_sent' if len(FriendRequest.objects.filter( from_user=u).filter(to_user=request.user)) == 1: button_status = 'follow_back_request' button_status_list.append(button_status) context = { 'page_title': page_title, 'poster_profile': poster_profile, 'profile_and_button_status': zip(p,button_status_list), 'u': all_profile_users, } return render(request, 'foryou.html', context) {% if poster_profile %} {% for user in poster_profile %} <div>{{ user.poster_profile }}</div> {% if not user == request.user %} {% for user in profile_and_button_status %} {% if user.1 == 'not_friend' %} <a href="" class="friend-request"> <button type="button" class="btn"> … -
I have this while running django
error faced (venv) PS C:\Users\Personal\Desktop\Onblu_VW1_API\api_vw1> python manage.py makemigrations Traceback (most recent call last): File "C:\Users\Personal\Desktop\Onblu_VW1_API\api_vw1\manage.py", line 22, in <module> main() File "C:\Users\Personal\Desktop\Onblu_VW1_API\api_vw1\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Personal\Desktop\Onblu_VW1_API\venv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\Personal\Desktop\Onblu_VW1_API\venv\Lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "C:\Users\Personal\Desktop\Onblu_VW1_API\venv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Personal\Desktop\Onblu_VW1_API\venv\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\Personal\Desktop\Onblu_VW1_API\venv\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Personal\AppData\Local\Programs\Python\Python312\Lib\importlib\__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 991, in exec_module File "<frozen importlib._bootstrap_external>", line 1129, in get_code File "<frozen importlib._bootstrap_external>", line 1059, in source_to_code File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed SyntaxError: source code string cannot contain null bytes -
How to send OTP to Gmail using Django Rest Framework? [closed]
I'm trying to implement an OTP verification system using Django Rest Framework (DRF). The goal is to send a 6-digit OTP to the user's Gmail address during registration or login. Here's what I've done so far: Generated a random 6-digit OTP using Python. -
How to pass pk to form (ForeignKey) and views - from template when following link?
How to pass pk to the form (ForeignKey) and views - from the template when clicking on a link? Good day! I have a model. Which is displayed in the template. And the transition to another template is configured by a link. But my form is not displayed there. I also wanted to ask how I can pass (pk) to the form in order to enter data only for the object by which the transition was made by the link? I click on the link and get to a specific object. I wanted to fill in its properties through the form. How can I fill in specifically for the object by (pk) that I clicked on the link to the view and form? For some reason, my form is not displayed. class ArkiObject_1 (models.Model): city = models.CharField(choices=TYPE_CITY, verbose_name="Городской округ") nameobject = models.TextField(verbose_name="Наименование объекта") typeobject = models.CharField(choices=TYPE_OBJECT, verbose_name="Тип объекта") param_1 = models.FloatField(verbose_name="Мощность котельной, МВт") param_2 = models.FloatField(verbose_name="Диаметры трубопроводов, мм") def __str__(self): return self.nameobject class ArkiGpr (models.Model): name = models.ForeignKey(ArkiObject_1, on_delete=models.CASCADE) work = models.TextField(verbose_name="Наименование работы") peoples = models.IntegerField(verbose_name="Количество людей") --- class FormOne (forms.ModelForm): class Meta: model = ArkiObject_1 fields = "__all__" class Form_GPR (forms.ModelForm): class Meta: model = ArkiGpr fields = "__all__" … -
Best practice to create a django user connected to a stripe customer
I'm trying to create a simple website for selling a digital good. Frontend is html/js, backend is django (using allauth, with simple email registration and a Custom User model) and I'm using stripe to handle payments. I've implemented a checkout workflow where a (anonymous) user can order via the hosted stripe checkout. However in order to properly handle the user's access to the digital goods, I need to somehow sync the stripe customer to a django user. The workflow, respectively best practice for this is unclear to me. Should I create a checkout session for the anonymous user and then use the stripe webhook confirmation to create a user (maybe sending the user a login link)? (What if the email has a typo?) Should I create a local user first, then via strip API a stripe customer (mapping the id as meta-data) and include the customer_id in the checkout? (seems clunky with multiple steps for the user, when they don't have an account yet) Something else from the stripe API (PaymentIntent)? ...? What are best practices for this? What are advantages / disadvantages of the respective approaches? I'm aware that this is a bit vague and will depend on the … -
Routing Problem from sign in page to a users account
The Issues is routing a user after creating an account on the webapp platform to the users dashboard created for the user. I can provide with the sign in and authcontext.js page which helps with this. signin.js import React, { useState, useEffect } from 'react'; import { Link, useNavigate, useLocation } from 'react-router-dom'; import { useAuth } from '../../../contexts/AuthContext'; import './Login.css'; const Login = () => { const [formData, setFormData] = useState({ email: '', password: '' }); const [error, setError] = useState(''); const [loading, setLoading] = useState(false); const { login, isAuthenticated } = useAuth(); const navigate = useNavigate(); const location = useLocation(); // Redirect if already logged in useEffect(() => { if (isAuthenticated) { const from = location.state?.from?.pathname || '/'; navigate(from, { replace: true }); } }, [isAuthenticated, navigate, location]); const handleChange = (e) => { const { name, value } = e.target; setFormData(prev => ({ ...prev, [name]: value })); // Clear error when user starts typing if (error) setError(''); }; const handleSubmit = async (e) => { e.preventDefault(); setError(''); setLoading(true); try { const { email, password } = formData; const result = await login(email, password); if (result.success) { // Redirect to the dashboard or previous page const from = … -
Can users and superusers have the same email/username in a Django application?
I have a CustomUser class for my users which is as follows. class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=150, unique=True, null=True, blank=True) email = models.EmailField(max_length=240, unique=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = CustomUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'password'] class Meta: verbose_name = 'user' It works pretty much as expected, I am able to signup, signin with normal users. The issue is when I try to create a superuser with the same email/username. I encounter the following error,django.db.utils.IntegrityError duplicate key value violates unique constraint "accounts_customuser_email_key". I understand that there is a uniqueness constraint on the username and email field, but shouldn't a user be able to create a user and an admin account with the same credentials ideally? I have a user with the following username and email. username: test_user email:test_user@test.com, I decided to create an admin with the same email and usernames. Doing so leads to a unique constraint violation. I expected that Django would internally handle this. -
Indexing multiply nested models with django_elasticsearch_dsl
I'm trying to use Elasticsearch in my Django app. I have Lemma models that can have multiple Forms with one citation form that can, in turn, have multiple Spellings. I'm trying to execute a search on (1) the Lemma's citation form, (2) any Lemma's Form's citation form, or (3) any Lemma's Form's Spelling's Latin character spelling. The structure in my models.py: class Lemma(models.Model): cf = models.CharField(max_length=200) pos = models.ForeignKey(Pos, blank=True, null=True, on_delete=models.SET_NULL) notes = models.TextField(blank=True) sortform = models.CharField(max_length=200) class LemmaDef(models.Model): lemma = models.ForeignKey(Lemma, on_delete=models.CASCADE, related_name="definitions") definition = models.TextField() class Form(models.Model): lemma = models.ForeignKey(Lemma, on_delete=models.CASCADE, related_name="forms") cf = models.CharField(max_length=200, blank=True) formtype = models.ManyToManyField(FormType, blank=True) class Spelling(models.Model): form = models.ForeignKey(Form, on_delete=models.CASCADE, related_name="spellings") spelling_lat = models.CharField(max_length=200) spelling_cun = models.CharField(max_length=200, blank=True) note = models.CharField(max_length=200, blank=True) In documents.py, I've got: from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry from .models import Lemma, Pos, LemmaDef, Form, Spelling @registry.register_document class LemmaDocument(Document): pos = fields.ObjectField(properties={ "term": fields.TextField() }) definitions = fields.ObjectField(properties={ "definition": fields.TextField() }) forms = fields.ObjectField(properties={ "cf": fields.TextField(), "spellings": fields.ObjectField(properties={ "spelling_lat": fields.TextField() }) }) class Index: name = "lemma" settings = { "number_of_shards": 1, "number_of_replicas": 0 } class Django: model = Lemma fields = [ "id", "cf", "sortform", "notes", ] related_models = [Pos, LemmaDef, Form, Spelling] … -
In django which logout option is best custom logout or LogoutView?
Actually i'm using django 5.2.3 in that version LogoutView is always gives error. Any other way is there for LogoutView because i try all the way?............................................................................................................................................ -
How can I make GrapesJS pages dynamic with real-time data from a Django backend in a React app?
I’m building a page builder application using GrapesJS, React, and Django (as the backend). I’ve successfully integrated GrapesJS into the React frontend, and I can design and save pages. However, I’m struggling to figure out how to make the created pages dynamic — meaning, I want the content to be fetched from the backend (Django) in real time so that it reflects live data (e.g., from a database or API). My goals: Make parts of the GrapesJS-generated pages update dynamically using backend data. Possibly insert dynamic components or placeholders in GrapesJS that get populated with real data on render. What I’ve tried: Saving and rendering raw HTML from GrapesJS. Embedding static content works, but it doesn’t update with backend data. I considered injecting React components into GrapesJS, but I’m not sure how to wire that with Django data properly. What I need help with: A general approach or architecture to achieve dynamic pages with GrapesJS. How to integrate real-time (or at least live) data from Django into the pages built with GrapesJS. Any open-source examples or patterns that solve this. Any guidance or resources would be much appreciated! -
Django static files not loading for one app when DEBUG=False
I'm working on a Django project with multiple apps (Home, student, login, etc.). When I set DEBUG = False in settings.py, the static files (CSS and JS) from my Home app load fine, but the static files from the student app return 404 errors in the browser console like: GET /static/student/css/dashboard.css 404 (Not Found) GET /static/student/js/dashboard.js 404 (Not Found) However, the static files from the Home app still load correctly. Here's what I've already done: My student app has this structure: student/ ├── static/ │ └── student/ │ ├── css/ │ │ └── dashboard.css │ └── js/ │ └── dashboard.js I'm using {% load static %} in the template and referring like this: <link rel="stylesheet" href="{% static 'student/css/dashboard.css' %}"> <script src="{% static 'student/js/dashboard.js' %}"></script> In settings.py DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' I ran python manage.py collectstatic, and it successfully copied all static files into the staticfiles/ directory. I also added this in urls.py: from django.conf import settings from django.conf.urls.static import static if not settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My Question: Why are the static files from the Home app working, but the ones from student are not, even though both … -
How to change django default files storage to cloudinary storage for media files?
I am working on django project. It is working fine with local storage and decided to use cloudinary for media storage then for some reason the file storage is not changing to cloudinary media storage. Here's my settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "listings", "rest_framework", "rest_framework_simplejwt", "corsheaders", 'django_filters', 'cloudinary_storage', 'cloudinary', ] # Cloudinary config CLOUDINARY_STORAGE = { "CLOUD_NAME": config("CLOUDINARY_CLOUD_NAME"), "API_KEY": config("CLOUDINARY_API_KEY"), "API_SECRET": config("CLOUDINARY_API_SECRET"), } cloudinary.config( cloud_name = config('CLOUDINARY_CLOUD_NAME'), api_key = config('CLOUDINARY_API_KEY'), api_secret = config('CLOUDINARY_API_SECRET') ) DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' model.py file: class Amenity(models.Model): name = models.CharField(max_length=100, unique=True) icon = models.ImageField(upload_to='amenity_icons/', null=True) I tried to upload with admin panel. It stores locally despite settings DEFAULT_FILE_STORAGE to 'cloudinary_storage.storage.MediaCloudinaryStorage' The environment configuration is loaded properly (I checked by printing). Here's debugging shell output: >>> from django.conf import settings >>> from django.core.files.storage import default_storage >>> print(settings.DEFAULT_FILE_STORAGE) cloudinary_storage.storage.MediaCloudinaryStorage >>> print(default_storage.__class__) <class 'django.core.files.storage.filesystem.FileSystemStorage'> I will work if I manually specify storage in every image field in every model. from cloudinary_storage.storage import MediaCloudinaryStorage class Amenity(models.Model): name = models.CharField(max_length=100, unique=True) icon = models.ImageField( upload_to='amenity_icons/', null=True, storage=MediaCloudinaryStorage ) -
Django - S3: collectstatic does not create new folder, even with all permissions and write privileges
Cursor ai called it a "strange problem", so we're back to the original home of solutions. I upgraded django from 2.2 to 5.2, and upgraded my storages, tinymce,.. etc modules along with it. STORAGES = { 'staticfiles': { 'BACKEND': 'storages.backends.s3boto3.S3Boto3Storage', 'OPTIONS': {'location': 'static'}, }, 'default': { 'BACKEND': 'storages.backends.s3boto3.S3Boto3Storage', 'OPTIONS': {'location': 'media'}, }, } i added a new app after the upgrade, and everything worked well in development. The issue is, when i run collectstatic in production, the static and media files that have already been synced from previous deployments remain available, but some of the static and media subfolders/files from recent upgrades do not get uploaded - even as they are all have the same static and media root directory. How is it that django-storages can "pick and choose" the folders to create within an identified static or media directory? i'm not sure what other code to include to explain this further, but if anyone needs to see something else, let me know and i'll add code snippets. Thanks. -
Performance Degradation & Timeouts Since Django & Stack Upgrades
We’ve been experiencing significant performance issues and intermittent timeouts on our app ever since we upgraded: Django from v2.x to v4.2 Heroku stack from 20 to 22 Prior to these upgrades, our response times were solid and timeouts were virtually non-existent. Over the past week, we’ve noticed: a) Longer page-load times (up to 5–10 seconds on endpoints that were previously sub-second) b) Occasional H12 request timeout errors during moderate traffic spikes c) Increased memory usage and dyno restarts that correspond to those timeouts We’ve checked our application logs, continue to optimize database queries, and temporarily scaled up our dynos, but the root cause still seems tied to the upgrades themselves. I) Have you experienced similar behavior when upgrading to Django 4.2 or the Heroku-22 stack? II) Any learnings, recommendations or best practices for tuning our configuration to restore performance to pre-upgrade levels? If there are known workarounds — whether it’s specific buildpack versions, config vars, or tweaking dyno settings — any guidance would be helpful. -
Integrating New Google Maps Autocomplete API into Django Project
I'm using the new Google PlaceAutocompleteElement() API function (not the legacy google.maps.places.Autocomplete) and would like help integrating it into my Django project. Specifically, I want to add an address search bar to my application.html template. I've tried connecting the initMap() JavaScript function to the form in several ways, updating all the corresponding files below, but the form submission always fails, and the data never reaches the database. Here's more information about the this Google API: Place Autocomplete Element Take a look of my attempt before the address implementation: models.py class Applicant(models.Model): Name = models.CharField(max_length=101) DOB = models.DateField() High_School = models.CharField(max_length=100) Major = models.CharField(max_length=100) SSN = models.CharField(max_length=11) Phone = models.CharField(max_length=15) def __str__(self): return self.Name views.py def application_page(request): form = ApplicationForm() return render(request, "DunesApp/application.html", { 'form': form, 'google_maps_key': settings.GOOGLE_MAPS_API_KEY }) def submit_application(request): if request.method == "POST": form = ApplicationForm(request.POST) if form.is_valid(): form.save() return JsonResponse({"status": "success"}) return JsonResponse({"status": "error"}) forms.py class ApplicationForm(forms.ModelForm): class Meta: model = Applicant fields = "__all__" script.js (called inside layout.html) function submitApplication() { const form = document.getElementById('application-form'); const formData = new FormData(form); fetch('/submit_application/', { method: 'POST', body: formData, headers: { 'X-CSRFToken': formData.get('csrfmiddlewaretoken') } }) .then(response => response.json()) .then(data => { const messageBox = document.getElementById('application-message'); if (data.status === 'success') { … -
Celery healthcheck fails in `set -e; cmd1;cmd2` and functions in `set -e; cmd1 && cmd2`
Problem docker compose fails app container for django celery app only in one of the 4 potential use cases. macos: set -e; cmd1;cmd2 or set -e; cmd1 && cmd2 work identically ubuntu: set -e; cmd1;cmd2 fails, set -e; cmd1 && cmd2 works In the failure case we see that django call to celery health check times out. I don't understand how set -e and && result in different behaviors given the following entry-point scripts Failing ubuntu case set -e ... python my_django_app.py start celery-worker celery-beats celery-healthcheck-worker daphne -b 0.0.0.0 -p 8000 my_django_app.asgi:application Passing all cases set -e ... python my_django_app.py start celery-worker celery-beats celery-healthcheck-worker && daphne -b 0.0.0.0 -p 8000 my_django_app.asgi:application Puzzle In my understanding , the set -e with cmd1; cmd2 and set -e with cmd1 && cmd2 should result in the identical behavior but it doesn't seem to. The fact that the error is around a call celery -A my_django_app status make me suspect the relationship of django, celery to daphne and suggests some kind of race condition but this seems like it should not be so Again, given that set -e is set, 1st failure terminates the entry point. There's a relationship change introduced by && but … -
Node npm error - could not determine executable to run
I was trying to install tailwind css using npm on my python django project in vscode, and for some reason kept running into the following error messages: npm ERR! could not determine executable to run So then i tried it with other project folders, same error. Other IDE's, same error. I then uninstalled and reinstalled node altogether, and yet that did not fix it. I now cant use tailwind in my project because of this as im unable to install it using npm, or even the django-tailwind packages. Any idea whats wrong with my Node? How do I fix it? -
Handle POST Request in DJANGO
I am new to DJANGO, and I am currently working on a project where I upload a file through a react page to a back-end handled by the DJANGO REST framework, after receiving the file I have to do some data processing. After some research I found that this logic is supposed to be in the views.py. So how do I create function which does this processing and how do I get it called whenever the server receives a new file or a POST request has been made. views.py from .models import FileStorage from rest_framework import viewsets from .serializers import FilesSerializer class FileViewSet(viewsets.ModelViewSet): queryset = FileStorage.objects.all() serializer_class = FilesSerializer -
Django - How to display image file in template
What I am trying to accomplish: I uploaded multiple images(3) and I am trying to display each images in different image tag. Here is my code; How are you doing it: I have attached my code to the question and explained the difficulties I have found in the code. codes below; Models.py class MultipleFile(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True) files = models.FileField(upload_to ='PostImages/%Y/%m/%d/', null=True, blank=True) is_image = models.BooleanField(default=False) is_video = models.BooleanField(default=False) Views.py def ForYouView(request): page_title = "For You" #All posters posts poster_profile = Post.objects.filter( Q(poster_profile=request.user)) #Post form if request.method == "POST": form = PostForm(request.POST) form_upload = MultipleFileForm(request.POST, request.FILES) if form.is_valid() and form_upload.is_valid(): post = form.save(commit=False) post.poster_profile = request.user post.save() form.save_m2m() my_files = request.FILES.getlist('files') for items in my_files: post_files = MultipleFile.objects.create(post=post, files=items) # Determine if it's an image or video based on mime type mime_type, _ = mimetypes.guess_type(post_files.files.name) if mime_type and mime_type.startswith('image/'): post_files.is_image = True elif mime_type and mime_type.startswith('video/'): post_files.is_video = True post_files.save() return redirect('site:foryou_view') else: form = PostForm() form_upload = MultipleFileForm() context = { 'page_title': page_title, 'poster_profile': poster_profile, 'form': form, 'form_upload': form_upload, } return render(request, 'foryou.html', context) Template.html {% if poster_profile %} {% for user in poster_profile %} {% if user.multiplefile_set.all|length == 3 %} {% for field in user.multiplefile_set.all … -
Can i connect my Youtube Channel Store to a Django E-commerce Website?
I am Django developer and I have a client who wants to connect his youtube store with the website that i'm gonna build with django. now i am confused that youtube will successfully connect the website or not. Anyone knows about this? Please let me know. -
How to select from the second field in the form - filtering data depending on the values of the first field?
Is it possible to somehow adapt something similar to my problem? I would like a list to appear in the form based on data from another list Select from the second field - filtering data - (contents) depending on the received values of the first field. For example. London Cafe London Restaurant London Fast Food Manchester Pizzeria Manchester Burgers I select a city in the form field and the second field is filtered by establishments. How to select from the second field in the form - filtering data depending on the values of the first field? class ExcludedDateForm(ModelForm): class Meta: model = models.ExcludedDate exclude = ('user', 'recurring',) def __init__(self, user=None, **kwargs): super(ExcludedDateForm, self).__init__(**kwargs) if user: self.fields['category'].queryset = models.Category.objects.filter(user=user) class FilterByUserMixin(LoginRequiredMixin): """ Filters the queryset with `self.request.user` in a specified `user_field` field. `user_field` defaults to "user". """ user_field = "user" def get_queryset(self, *args, **kwargs): return ( super() .get_queryset(*args, **kwargs) .filter(**{self.user_field: self.request.user}) ) class Book(models.Model): author = models.ForeignKey(MyUser, on_delete=models.RESTRICT) number_pages = models.PositiveIntegerField() title = models.CharField(max_length=1000) class BookUpdateView(FilterByUserMixin, UpdateView): model = Book template_name = "book/my_book_update_template.html" fields = ["number_pages", "title"] success_url = reverse_lazy("book-update-success") user_field = "author" . . .. .. ........ -
Best resourcefor learning django restframework?
I am learning drf on my own and i am having difficulties in understanding all the things by researching and i am also not sure that i am doing it correclty. So help me by suggesting best resources except official documentation. -
Why are my messages not showing in real-time using HTMX and WebSockets in Django?
I'm building a simple two-way chat system as a part of my web-app using HTMX WebSockets (htmx-ext-ws). The goal is to display incoming messages in real time without requiring a manual page refresh. The setup mostly works — messages are being saved to the database, and the WebSocket connection seems to establish correctly. However, new messages only appear after a page reload, and not in real time as expected. Here’s an overview of what I have: #chat.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Chat</title> <script src="https://unpkg.com/htmx.org@1.9.12"></script> <script src="https://unpkg.com/hyperscript.org@0.9.12"></script> <script src="https://unpkg.com/htmx-ext-ws@2.0.2"></script> <link rel="stylesheet" href="{% static 'css/chat.css' %}"> </head> <body> <div class="chat-container"> <div class="chat-header"> Chat Room </div> <div class="chat_messages" > {% for message in messages %} <div class="message-row {% if message.author.user == user %}my-message{% else %}other-message{% endif %}"> {% include "chat_rt/chat_message.html" %} </div> {% empty %} <div>No messages yet.</div> {% endfor %} </div> <form class="chat-input-area" id="chat-form" autocomplete="off" method="POST" hx-ext="ws" ws-connect="ws://127.0.0.1:8000/ws/chatroom/private-chat" ws-send _="on htmx:wsAfterSend set #chat-input.value to ''"> {% csrf_token %} {{ form.body }} <button type="submit">Send</button> </form> </div> <script src="{% static 'js/chat2.js' %}"></script> </body> </html> #chat_message.html {% if message.author.user == user %} <div class="message-content"> <div class="message-meta right"> <span class="time">{{ message.created|date:"H:i" }}</span> </div> <div class="body">{{ … -
Django/PostgreSQL: Unique constraint with a dynamic condition like expires_at > now()
I'm building a secure OTP system in Django. The model looks like this: class OTP(models.Model): MAX_ATTEMPTS = 3 DEFAULT_EXPIRE_IN_MINUTES = 1 class Purposes(models.IntegerChoices): LOGIN = 1, "Login" REGISTER = 2, "Register" VERIFY_PHONE = 3, "Verify Phone" VERIFY_EMAIL = 4, "Verify Email" otp_hash = models.CharField(max_length=64) purpose = models.IntegerField(choices=Purposes) phone = PhoneNumberField(null=True, blank=True) email = models.EmailField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) expires_at = models.DateTimeField() failed_attempts = models.PositiveSmallIntegerField(default=0) used = models.BooleanField(default=False) used_at = models.DateTimeField(null=True, blank=True) What I want to enforce: A user should not receive another OTP if there is already an unexpired (based on expires_at field), unused (used=False) OTP for the same purpose. The condition should apply either for: (phone, purpose) if phone is set, or (email, purpose) if email is set. And this logic must hold true even under concurrent requests. What I've tried so far: Application-level check with OTP.objects.filter(...) before creating a new one — this is not safe under race conditions. Adding a is_expired boolean field and a conditional UniqueConstraint like this: class Meta: constraints = [ models.UniqueConstraint( fields=["phone", "purpose"], condition=Q(is_expired=False), name="unique_active_phone_otp" ), models.UniqueConstraint( fields=["email", "purpose"], condition=Q(is_expired=False), name="unique_active_email_otp" ), ] But this requires updating the is_expired field manually or periodically when expires_at < now(), which adds operational complexity and is … -
{"status":"error","message":"An unexpected error occurred","errors":"[Errno 5] Input/output error"}
This problem occurs when I create an order in my project. I hosted it on GoDaddy, and the problem occurred only after hosting. If I run this locally, it will create the order. Understand this error Error saving data: dl {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …} this is the error it shows in the react front end {"status":"error","message":"An unexpected error occurred. "errors": "Input/output error"} and this is the error shows in the flutter app while creating the order