Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What if I forgot to activate virtual environment working on Django project?
I have been working on a Django project in Python Crash Course 2nd edition. In the book it was said that I need to create virtual environment and that I need to activate it every time. I did create it but at some point I forgot about it and stopped activating venv. I made a LOT of changes since the last time I activated it. Now I know that virtual environment has to be activated, I read about it on several websites including Stack Overflow. And I do know how to do it. But I couldn't find what would happen if I didn't activate venv? Will there be some kind of consequences? If yes, how to fix it? -
How do I add a javascript file in the default model form in admin.py?
I want to add a javascript function in the default model form that renders on the django admin site. I do not have a separate html template that loads the form. I have used the Media class inside the model form but where do I load it from? Any clues? I have created an 'Example' model in models.py. I have added additional fields to render on the admin panel. admin.py class ExampleForm(forms.ModelForm): class Meta: model = Example fields = "__all__" username = forms.CharField(required=False, max_length=100) password = forms.CharField(widget=forms.PasswordInput, required=False, max_length=100) class Media: js = ('static/tenants/js/custom.js',) I looked for solutions online which asks to include the script tag in the html template. But I am not using a template. Assuming I have to add a template to add javascript on that form, which template do I use? I don't want to change the default design that django provides. -
Django Jenkins pipeline using wsl
I have a silly question, can we make a CI/CD pipeline for a django project using Jenkins and I don't have any access to cloud portals, can I do it using wsl Till now I have not seen any article or video doing this, is it possible.? I don't have any idea as I want to learn this thing -
DJANGO_MIGRATION_NOT_WORKING_gETTING_CONSTANT_ERROR_IN_SHOP_URL
I have been trying to make a project for my internship and i am constantly getting error while migrating in django and its the same error in shop urls. Any type of help will be appreciated as this internship is important to me and i dont wanna waste this opportunity url.py in myproject url.py in `shop image of the error shown I tried renaming and rechecking the names assigned and tried renaming them yet no improvement was found I even tried using chatgpt and restarted my server yet no sign of improvement I was expecting that my project will start by doing these changes -
No url reverse match of pk with a correct setup (most likely)
I'm trying to implement inline editing feature using HTMX in Django form. I've checked the url routing several times and am pretty sure, that everything should be correct. I'm gettings django.urls.exceptions.NoReverseMatch: Reverse for 'update_work_hours' with arguments '('',)' not found. 1 pattern(s) tried: ['nuomotojo\\-platforma/darbo\\-laikas/atnaujinti/(?P<pk>[0-9]+)/\\Z'] error while executing get request. Template (delete works perfectly fine, so I assume, that hours.pk is passed correctly): <div id="work_hour_day" class="flex flex-col md:flex-row items-center my-2"> <span>{{ hours.get_day_of_week_display }}: {{ hours.opening_time }}-{{ hours.closing_time }}</span> <div class="flex gap-2 mx-2"> <button hx-get="{% url 'rentals:update_work_hours' hours.pk %}" hx-target="closest #work_hour_day" hx-swap="outerHTML" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">Keisti</button> <button hx-delete="{% url 'rentals:delete_work_hours' hours.pk %}" hx-target="closest #work_hour_day" hx-swap="outerHTML swap:1s" hx-trigger='confirmed' onClick="Swal.fire({title: 'Confirm', text: 'Do you want to continue?', icon: 'question'}).then((result)=>{ if(result.isConfirmed){ htmx.trigger(this, 'confirmed'); } })" class="focus:outline-none text-white bg-red-700 hover:bg-red-800 focus:ring-4 focus:ring-red-300 font-medium rounded-lg text-sm px-5 py-2.5 dark:bg-red-600 dark:hover:bg-red-700 dark:focus:ring-red-900" type="button">Ištrinti</button> </div> </div> Views.py: class UpdateRentalWorkingHours(View): def get(self, request, pk): working_hours = get_object_or_404(RentalWorkingHours, pk=pk) form = UpdateWorkingHoursForm(instance=working_hours) day_of_week = working_hours.get_day_of_week_display() # If request from cancel button in the form, return the initial data trigger = request.headers.get("HX-Trigger") if trigger == "get_working_hours_row": return render( request, "rentals/partials/work_hour_row.html", {"hours": working_hours}, ) else: context = {"form": form, "day_of_week": day_of_week} return render( request, … -
Django and WebSocket in production
I'm working with real-time updates in my Django project for the first time, and it works well locally, but I have an error in production (Microsoft Azure). Note: I read a couple of articles about using Redis instead of InMemoryChannelLayer. The Error WebSocket connection to 'wss://mydomain.com/ws/orders/' failed: (anonymous) @ orders/:288 The Code index.html <script type="text/javascript"> const orderId = '{{ order.id }}'; let url = `wss://${window.location.host}/ws/orders/`; const orderSocket = new WebSocket(url) orderSocket.onmessage = function(e){ let data = JSON.parse(e.data); document.querySelector('.backdrop').classList.remove('d-none'); setTimeout(() => { location.reload(); }, 3000); } </script> settings.py ALLOWED_HOSTS = ['mydomain.com', '127.0.0.1', 'localhost'] # my domain refers to my website domain CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", }, } ASGI_APPLICATION = 'core.asgi.application' INSTALLED_APPS = [ 'channels', # other apps... ] routing.py from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/orders/', consumers.OrdersCustomers.as_asgi()), ] Things I've tried: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "host": "redis://localhost:6379", }, }, } But didn't know how to configure the host. -
Modelform using Django
i am using a form from modelform class.but its showing an error of "ValueError at /list/ ModelForm has no model class specified". enter image description here my model form- from django.forms import ModelForm from . models import Student class StudentForm(ModelForm): class meta: model=Student fields='all' i tried everything and checked again and again...but not getting the desire output -
i have a issue with inserting image filed in django database
this is my model: from django.db import models class Topic(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Article(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) title = models.CharField(max_length=6000) featured_image = models.ImageField(null=True,blank=True, default="default.jpg") # i want to add this filed content = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title i installed python -m pip install pillow and this is my setting configuration: import os STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] in the admin panel i am expecting the apparition of featured image filed that sets the image with the default.jpg if the on the article creation the admin doesn't insert a image. After i run python manage.py makemigrations it is always giving me this: It is impossible to change a nullable field 'topic' on article to non-nullable without providing a default. This is because the database needs something to populate existing rows. Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Ignore for now. Existing rows that contain NULL values will have to be handled manually, for example with a RunPython or RunSQL operation. Quit and manually define a default value … -
how to connect multiple clients with Django channels and client should be authenticated by server before opening the channel
So I'm working on a desktop based app that requires a socket to handle multiple authenticated clients with a Django channel, and clients should be authenticated by the server before opening the channels. The server is running on one different system, and clients are connecting to multiple systems. I have tried to connect a server with a different platform with much effort, but I have failed to connect it. Is it possible to connect clients on different platforms to the server? If yes, please help me to resolve this issue because I am new to this technology. I need your valuable suggestions or feedback would be highly appreciated. thank your ! -
Value Error when registering user in Django
In my mobile app, whenever I try to register a user in the Django backend, I get "ValueError: Cannot query "user@example.com": Must be "User" instance." Here's the serializer(django): class UserSerializer(serializers.ModelSerializer): friends = serializers.SerializerMethodField() class Meta: model = User fields = ['id', 'name', 'email', 'date', 'password', 'profile_picture', 'friends'] extra_kwargs = {'password': {'write_only': True, 'required': True}} def get_friends(self, obj): return [friend.email for friend in obj.get_friends()] def create(self, validated_data): user = User.objects.create_user(**validated_data) user.save() print(user) print(type(user)) Token.objects.get_or_create(user=user) print("user created") return user Here's the react native where I send the post request to the server. const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const onChange = (field, value) => { if (field === 'name') setName(value); else if (field === 'email') setEmail(value); else if (field === 'password') setPassword(value); }; const onSubmit = async () => { try { let response = await fetch('http://localhost:8000/api/users', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ name: name, email: email, password: password, }), }); let json = await response.json(); console.log("JSON response:", json); if (response.status === 201) { // Registration successful // You can dispatch a success action here console.log("Registration Successful"); } else { // Registration failed // You can dispatch … -
unique user based caching in django
In django 3.2 what's the cleanest way to access a user id in functions called from views or outside views? I want to implement caching in my project but it needs to be specific to each user. I thought I could simply access the user id and integrate it in the cache key. The problem is doing so requires access to the request object and I often need access within functions called by a view. I don't want to change all my functions to add a request object, unless that's the best solution. Can something like a global be set for the duration of the request to access it anywhere once it hits the view? It looks like this gets into threads and seems hacky. FWIW Currently I'm using django-cache-memoize which does everything I need https://github.com/peterbe/django-cache-memoize and memcached which I also like. -
This field may not be null when creating a task
When I create a task that can have multiple subtasks, I get the error from Django {"subtasks":[{"task_id":["This field may not be null."]}]}. The problem is that I don't know the task_id when I create it. That's why I can't assign a task_id to the subtask yet. How can I solve this problem? { "id": null, "title": "Task", "subtasks": [ { "task_id": null, "description": "aa", "is_done": false } ] } -
Python Project not able to post on schedule time on Facebook or Instagram using Django
not able to post on schedule time on Facebook and Instagram with schedule time i am able to post but i need to sort the schedule time issue not any error appears. Here is the code (VIEWS.PY) def index(request): post_form = BasicForm() if request.method == 'POST': post_form = BasicForm(request.POST, request.FILES) try: if post_form.is_valid(): fss = FileSystemStorage() file = fss.save(request.FILES['post_file'].name, request.FILES['post_file']) file_url = fss.url(file) post_description = post_form.cleaned_data['post_description'] is_schedule = post_form.cleaned_data['schedule_check'] if is_schedule: schedule_time = post_form.cleaned_data['schedule_time'] if schedule_time: # Ensure schedule_time is timezone-aware if timezone.is_naive(schedule_time): aware_schedule_time = timezone.make_aware(schedule_time, timezone.get_default_timezone()) else: aware_schedule_time = schedule_time SchedulePost.objects.create( post_description=post_description, post_file=file_url, fb_check=post_form.cleaned_data['fb_check'], insta_check=post_form.cleaned_data['insta_check'], whatsapp_check=post_form.cleaned_data['whatsapp_check'], schedule_check=True, my_datetime=aware_schedule_time, ) logger.info(f"Scheduled time (selected): {aware_schedule_time.strftime('%Y-%m-%d %H:%M:%S %Z')}") logger.info("Record scheduled...!") return redirect('index') # Redirect to index after scheduling (SETTING.PY) LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Karachi' USE_I18N = True USE_TZ = True Kindly let me know if any more details are required [28/Jun/2024 02:17:11] "GET /index/ HTTP/1.1" 200 13741 [28/Jun/2024 02:17:54] "POST /index/ HTTP/1.1" 302 0 Tried : The first step is to add USE_TZ = True to your settings file. Also tried the naive_datetime aware as well -
Optimizing Django app for displaying aggregated data from multiple related objects efficiently
I'm developing a Django app where users can create and manage hierarchical data structures with multiple levels (in my case only 4 levels). The app needs to efficiently display aggregated data (e.g., averages, sums, and other more complicated metrics) for each level based on the aggregated data of the level below it. Here's a simplified version of my data models: from django.db import models class Level1(models.Model): name = models.CharField(max_length=100) class Level2(models.Model): level1 = models.ForeignKey(Level1, on_delete=models.CASCADE) name = models.CharField(max_length=100) class Level3(models.Model): level2 = models.ForeignKey(Level2, on_delete=models.CASCADE) name = models.CharField(max_length=100) class DataPoint(models.Model): level3 = models.ForeignKey(Level3, on_delete=models.CASCADE) value = models.FloatField() For example, aggregated data for Level3 objects will be based on DataPoints, aggregated data for Level2 objects will be based on the aggregated data for its related Level3 objects, and aggregated data for Level1 models will be based on the aggregated data of its related Level2 objects. This means that I really only have to re-compute the aggregated data of a level if data from a level under it changes. Currently, I calculate the aggregated data every time they get requested, but this probably isn't good for performance (e.g. I'm displaying the aggregated data of multiple Level1 objects at once, meaning I have to … -
how to connect multiple authenticated clients' with Django channels Websocket and clients should be connected before opening the channels
so I'm working on the desktop based app that requires a socket handle multiple authenticated clients with Django channel and clients should be authenticated by server before opening the channels and server running on one different system and clients connecting multiple system. I have tried to connect socket with different platform with much effort, I have failed to connect it. is it possible to connect clients in different platform to the server? if yes please help me to resolve this issue because I am new in this technology. my question is using the code below how would be able to have multiple clients connected? I have tried lists, but I just cant figure out the format for that. How can accomplished where multiple clients connected at Websocket and l am able to send a data to a specific or multiple clients? and how can I add channels in below code? server.py import socket serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serversocket.bind(('localhost', 8080)) serversocket.listen(10) # become a server socket connections while True: connection, address = serversocket.accept() buf = connection.recv(64) if len(buf) > 0: print(buf) break here client script I don't want to send data using api any other way to get … -
django-auditlog change list customization in django admin
I've started using django-auditlog in my project. I was able to successfully log entries for changes to my model, however I want to make a tweak on how audit log displays change list in django admin. The problem is I've a ForeignKey in my Task model, it does have a __str__ method defined. When I make change to stage field on my Task model, the entry is logged, but it shows the stage id instead of stage.name as per defined in __str__ (i believe this is how it's supposed to work. Here is my models.py class Stage(models.Model): name = models.CharField(max_length=64) def __str__(self): return self.name class Task(models.Model): name = models.CharField(max_length=64) stage = models.ForeignKey(Stage, on_delete=models.SET_NULL, null=True) ## other unrelated fields... def __str__(self): return self.name Here is how the Log Entry is displayed currently: Here is the expected result: I've read the documentation of django-auditlog but couldn't found any help. Any suggestion? -
Django: Maintaining a local set of migrations differing from upstream
I have written patches for a Django project that take forever to be integrated upstream (or may not even be). Due to this, I have local migrations that I need to maintain. However, due to the way the migration numbering system works, I have to update their numbers everytime upstream adds a new migrations, and that doesn't even work properly as it creates conflicts with the database state. I've been trying to move them to a separate app, but it doesn't seem to be possible to apply them to the original app then. How to properly maintain your own set of migrations? -
Django and multithreading
I have Django view: def func(): ... instance = ...create() func2(instance) instance.attr = attr etc... So func() creates an instance, calls func2() and keeps on working. def func2(instance): request = request(instance) wait response response.data.save() The result of function 1 and function 2 are in no way related. Function 2 is related to output/input operations. Function 2 must be called by function 1 and must not block the operation of function 1. In the current project version, func2 is called with celery. But I'm not sure that's the right way, and it's better to call func2 with another thread. def func(): ... instance = ...create() thread = threading.Thread(target=func2, args=instance) thread.run() instance.attr = attr etc... Am I right? Thanks a lot! -
How to Connect Multiple Clients to a Django Socket Server Across Different Platforms
We have created a socket server using Django and need to connect multiple clients to it. Our setup involves the server running on one platform and clients connecting from different platforms. We have a few specific requirements: The Django server should be opened for immediate connectivity. We need to ensure that client and server connectivity works seamlessly, even when the client and server are on different platforms. Our goal is to understand if we are on the right track with our current implementation. 1.Are we on the right track with our current implementation for handling multiple client connections on a Django socket server? 2.How can we ensure the server handles clients from different platforms efficiently? 3.Are there any improvements or best practices we should follow to enhance connectivity and performance? -
Checkboxes in Django and JS not working properly
I have a serious problem with checkboxes. I'm creating a ToDo style application and I want it to save the changes (item_done = False or True) when the checkbox is clicked. I have implemented a JS script to make everything come out "smoothly", I am using jQuery. Unfortunately the following error appears: when clicking on the first item in the list, everything works smoothly but when clicking on the second, the change happens in the first and vice versa when clicking on the first the change happens in the second. I can't to figure out what I am doing wrong. I have included the code below. HTML with Django, list of items in task: <div class="card-header bg-transparent" ><h3>To-do list</h3></div> <div class="text-start"> <br/> <ul class="list-group"> {% if list_items %} {% for item in list_items %} {% if item.item_done %} <li class="list-group-item"> <input class="form-check-input" type="checkbox" checked="checked" value="{{ item.id }}" id="un-check-box"> {{ item.title }} </li> {% else %} <li class="list-group-item"> <input class="form-check-input" type="checkbox" value="{{ item.id }}" id="check-box"> {{ item.title }} </li> {% endif %} {% endfor %} {% else %} <p class="text-center">the task list is empty</p> {% endif %} </ul> JS code: <script> // Check if checkbox pressed $(document).on('click', '#check-box', function(e){ e.preventDefault(); $.ajax({ … -
Errors not displaying in login form in Django
In my Django project, I use django.auth for authentication. I have two similar HTML templates for registration and login. The problem is that while displaying errors (e.g., passwords don't match, password too short) works for registration, it doesn't for logging in. For example, if I enter an incorrect username and password and click the submit button, errors won't show up, the page refreshes, the username remains in the input box, but the password box is empty. That's all. If I provide the correct credentials, it logs me in correctly. If I display the form using {{ form.as_p }}, errors work fine. Below are both forms: Registration: <form method="post"> {% csrf_token %} <!-- Username --> {% if form.username.errors %} <ul> {% for error in form.username.errors %} <li class="small-red-text">{{ error }}</li> {% endfor %} </ul> {% endif %} {{form.username|add_class:"form-control"|attr:"id:register-username-input"|attr:"placeholder:Username"}} <!-- Password 1 --> {% if form.password1.errors %} <ul> {% for error in form.password1.errors %} <li class="small-red-text">{{ error }}</li> {% endfor %} </ul> {% endif %} {{form.password1|add_class:"form-control"|attr:"placeholder:Password"}} <!-- Password 2 --> {% if form.password2.errors %} <ul> {% for error in form.password2.errors %} <li class="small-red-text">{{ error}}</li> {% endfor %} </ul> {% endif %} {{form.password2|add_class:"form-control"|attr:"id:register-password-input"|attr:"placeholder:Confirm password"}} <button class="small-blue-button" type="submit" name="register">Register</button> </form> Logging: <form id="login-form" method="post"> … -
Django partial template rendering not updating the page, but showing up in console
I have a django-based webpage I am working on. This page allows for clicking on a item in a table and the intention is to display subitems related to the item, without redrawing the whole page. Though my subtemplate is being seen by Django and acted upon, instead of updating the portion of the html in the page, the resulting html is being dumped in the console. Here are some code snippets: main.html contains, among many other things, the following positioned where I want the content: {% include '_subtemplate.html' %} _subtemplate contains: {% for subitem in subitems %} <tr> <td><a onclick='mySubItemClick("{{ subitem.date }}")'>{{ subitem.date }}</a></td> <td>{{ subitem.my_note }}</td> </tr> {% endfor %} views.py contains: def get_my_subitems(requests, site_id): subitems = # code to get a list of objects return render(request, '_subtemplate.html', { 'subitems': subitems }) urls.py contains a correct path entry in urlpatterns: path('myitems/mysubitems/<int:site_id>/', views.get_my_subitems, name='get_my_subitems'), I have a javascript file that contains a method which makes a working ajax call where 'path: /myitems/mysubitems/' + obj.site_id Instead of seeing my list of subitem content reload in the html page, when I open the browser console, I am seeing the correctly templated html there and not in the page. <tr> <td><a onclick='mySubItemClick("June … -
How to build a search function in react native app?
I have a react native app. And I have a search function. The problem I am facing is that the search function only works when the whole word has been entered in the textfield. So for example Edelhert works. But if a user types in: Ed - then nothing happens. And if a user waits for a second in the search textfield. Then this error pops up: VM270:1 Uncaught SyntaxError: Unexpected identifier 'Promise' So the search api looks: import { API_URL } from "@env"; import { retrieveToken } from "../../services/authentication/token"; export const fetchAnimalData = async (text) => { const token = await retrieveToken(); try { if (token) { const response = await fetch(`${API_URL}/api/animals/?name=${text}`, { method: "GET", headers: { Authorization: `Token ${token}`, Accept: "application/json", "Content-Type": "application/json", }, }); return await response.json(); } else { throw new Error(token); } } catch (error) { console.error("There was a problem with the fetch operation:", error); throw error; } }; and the search context: /* eslint-disable prettier/prettier */ import React, { createContext, useEffect, useState } from "react"; import { fetchAnimalData } from "./animal/animal.service"; export const SearchAnimalContext = createContext(); export const SearchAnimalContextProvider = ({ children }) => { const [searchAnimal, setSearchAnimal] = useState([]); const [results, setResults] = … -
I am currently learning from the meta backend course and I have front end knowledge , do suggest some knowledge and path that will help me
I am a beginner in backend development , I want to get some advice from some experts backend developers about the learning path , what should I learn , where to start , provide me some free resources from where I can learn. I have knowledge of front end . I am expecting some real ans that will help me -
Is there any way to export an existing Django model information into a visual form
I understand that I can create .dot files using django-extensions. I am also able to create SVGs from the .dot file using pygraphviz. However, the outputs are huge, ugly and difficult to navigate. Are there any tools that people can recommend that might include some form of filtering, auto layout etc.