Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Static files won't load
I`ve created a new Django project and ran into a problem with static images. So, apparently when i was connecting my css and javascript files with static it worked well, but when i tried to connect images they won't load. here is my settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_DIRS = ['static'] # Default primary key field type # https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' LOGIN_REDIRECT_URL = '/' urls.py from django.contrib import admin from django.urls import path, include from store import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('mstore.urls')), ] if settings.DEBUG: from django.conf.urls.static import static urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) here is example of how i display it in template <a href="#" class="item__image"> <picture><source srcset="img/collections/featured/02.webp" type="image/webp"><img src="{% static 'mstore/img/collections/featured/02.png' %}" alt="Lore Walnut"></picture></a> Please, before answering note that i checked the src of the image in browser, and it worked. src of image in browser i copied this link and pasted in browser and got this enter image description here Besides, css and js works great, so i think the problem is in images I tried to run python manage.py collectstatic and it worked perfectly. -
unable to fetch the data of uploaded JSON file in database Django
I am trying to create a panel where the user uploads his JSON file and it shows result in a specific manner using the D3.js library but it causing some error here is the code models.py class JSONFile(models.Model): user = models.ForeignKey(User ,on_delete=models.CASCADE,related_name='file') files = models.FileField(upload_to='json_files', null=True) uploaded_at = models.DateTimeField(default=timezone.now,editable=False) views.py def home(request): if request.method == 'POST': form = JSONFileUploadForm(request.POST, request.FILES) if form.is_valid(): json_data = json.load(form.cleaned_data['files']) json_str = json.dumps(json_data) return render(request, 'visualization.html', {'json_str': json_str}) else: form = JSONFileUploadForm() return render(request, 'home.html', {'form': form}) and in Visualization.html <h2>Data Visualization</h2> <div id="visualization"></div> <script src="https://d3js.org/d3.v7.min.js"></script> <script> var jsonData = {{ json_str|safe }}; </script> the file gets uploaded in my media but I am unable to show it in visualization.html traceback -
having issue to update user profile in Django
I wanted to make an update profile function where users can update their data by filling out a form. My website is running well without any errors, but whenever I fill up the form & hit submit the profile doesn't update itself & also new data is not saved. Here are my codes: views.py: def userProfile(request): return render(request, 'home/profile.html') def updateProfile(request): if request.method == 'POST': profile = UserProfile.objects.get(pk=request.user.profile.pk) profile_form = UserProfile(request.POST, instance=profile) if profile_form.is_valid(): profile_form.save() return redirect('profile') else: profile = UserProfile.objects.get(pk=request.user.profile.pk) profile_form = UserProfile(instance=profile) return render(request, 'profile.html', { 'profile_form': profile_form, 'errors': profile_form.errors() }) forms.py from django import forms from .models import user class UserProfile(forms.ModelForm): class Meta: model = user fields = ['username', 'first_name', 'last_name', 'email'] models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Contact(models.Model): sno= models.AutoField(primary_key=True) name= models.CharField(max_length=255) phone= models.CharField(max_length=13) email= models.CharField(max_length=100) content= models.TextField() timeStamp=models.DateTimeField(auto_now_add=True, blank=True) def __str__(self): return "Message from " + self.name + ' - ' + self.email profile.html {% extends 'base.html' %} {% block title %} User Profile {% endblock title %} {% block body %} <div> <h1 class="m-4" style="color: teal;">User Profile</h1> <h2 class="m-4"> Welcome {{user.username}} </h2> <h2 class="m-4"> First Name: {{user.first_name}} </h2> <h2 class="m-4"> Last … -
Registering custom path converters in django
I am learning Django custom path converter and its registration while I understand all the string integer sledge and uuid Types of url modifications but while registering a custom path converter I have problems and I didn't understand the syntax of its registration need help to solve this problem class FourDigitYearConverter: regex = "[0-9]{4}" def to_python(self, value): return int(value) def to_url(self, value): return "%04d" % value what is the use of regex class level variable , and the use of to_python , to_url methods below is Registration code but i cna understand it if i understand the above code from django.urls import path, register_converter from . import converters, views register_converter(converters.FourDigitYearConverter, "yyyy") urlpatterns = [ path("articles/2003/", views.special_case_2003), path("articles/<yyyy:year>/", views.year_archive), ..., ] I want to understand the core functionality of To_url and to_python method and the use of class level regex variable -
SQL query to find exact words in any order
I have a postgres table Article which has three columns - title, description, categories. All the three columns contain plain text. I have 2 search words - say word1, word2 I want to find the records where title+description+categories contains all the exact search words, in any order. need exact case-insensitive matches. Ex. man shouldn't match against woman. The search words can appear in any order Ex. If we search for "pollution global warming" - it should match against "... global abc warming adds to toxic mix of pollution..." Need help in implementing a procedure(if not possible by query) where we can pass in the list of search words and it should return the list of records. Any pointer will be a great help. On a side note, I intend to consume this in django. If this requirement can be better achieved using django ORM, that should also suffice. -
Why doesn't my javascript work in django?
I am trying to run a simple html file using VUE framework: <!DOCTYPE html> <html> <head> <title>Vue.js Example</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <h1>{{ message }}</h1> <input v-model="inputText" type="text"> <p>You typed: {{ inputText }}</p> </div> <script> new Vue({ el: '#app', data: { message: 'Hello from Vue.js!', inputText: '' } }); </script> </body> </html> It works perfectly fine but when I put the same html into a Django framework, the h1 tag and the inputText area does not show at all. My html code in Django is as follow: <!DOCTYPE html> <html> <head> {% load static %} <title>Vue.js and Django Integration</title> <script src="{% static 'js/vue.min.js' %}"></script> </head> <body> <div id="app"> <h1>{{ message }}</h1> <input v-model="inputText" type="text"> <p>You typed: {{ inputText }}</p> </div> <script> new Vue({ el: '#app', data: { message: 'Hello from Vue.js!', inputText: '' } }); </script> </body> </html> How can I fix this issue? -
Update user profile in Django
I wanted to make an update profile function where users can update their data by filling out a form. My website is running well without any errors, but whenever I fill up the form & hit submit the profile doesn't update itself & also new data is not saved. Here is the code: views.py: def updateProfile(request): if request.method == 'POST': profile_form = updateProfile(request.POST, instance=request.user.profile) if profile_form.is_valid(): profile_form.save() return redirect('profile') else: profile_form = UserProfile(instance=request.user.profile) return render(request, 'profile.html', {'profile_form': profile_form}) Please check out my function. -
Join Query in Django ORM to Create Report
I have the following models structure: class Student(models.Model): full_name = models.CharField(max_length=100) std_class = models.CharField(max_length=50) class Teacher(models.Model): full_name = models.CharField(max_length=100, unique=True) class Attendance(models.Model): att_date = models.DateField(default=date.today) teacher = models.ManyToManyField(Teacher) subject_name = models.CharField(max_length=50) std_class = models.CharField(max_length=50) total_students = models.IntegerField(default=0) class Entry(models.Model): attendance = models.ForeignKey(Attendance, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) I want to build a report like below for all students in the given class: Student Name Attendance Date 1,Teachers Name Attendance Date 2,Teachers Name ... Student 1 P A ... Student 2 A P ... Student 3 P P ... ... ... ... ... Student N A A ... The P (Present) should be marked if Entry has a row that contained attendance for a given student otherwise A (Absent). I've built the code and it working correctly, but it is very inefficient. report_dict = {} all_students = Student.objects.filter(std_class=class_full_name) for name in all_students: report_dict[name.full_name] = [] attendance_list = Attendance.objects.filter(Q(std_class=class_full_name) & Q(att_date__month=curr_month)).order_by('att_date') for rec in attendance_list: # Make absent all student initially for key in report_dict: report_dict[key].append("A") # Get all attendance for current attendance id entries = Entry.objects.filter(attendance=rec) # Mark present to the selected student for e in entries: if report_dict[str(e.student)] != None: report_dict[str(e.student)][-1] = "P" Is there a better approach to solving … -
Removing 'Add' link in Django admin sidebar
The Django admin index page lists models in a left side sidebar, each with an 'Add' link to instantiate a new object. I want to remove that 'Add' link for just one of the models (Appointments) in the side bar, while retaining it within inline views. First try: set add_url to false. # admin.py class AppointmentAdmin(admin.ModelAdmin): add_url = False This did not work. The 'Add' link still appears. The docs say add_url is an AdminSite method, but I don't want to apply it site-wide. Second try: override the app_list.html template. This works, but seems like the brute force way. There must be something more elegant? I've looked at defining-a-custom-app-list-in-django-admin-index-page, much more complex, not directly applicable, and uses AdminSite (I'm assuming I need to be working local to this app, i.e. admin.ModelAdmin). {% if app_list %} {% for app in app_list %} <div class="app-{{ app.app_label }} module{% if app.app_url in request.path|urlencode %} current-app{% endif %}"> <table> <caption> <a href="{{ app.app_url }}" class="section" title="{% blocktranslate with name=app.name %}Models in the {{ name }} application{% endblocktranslate %}">{{ app.name }}</a> </caption> {% for model in app.models %} <tr class="model-{{ model.object_name|lower }}{% if model.admin_url in request.path|urlencode %} current-model{% endif %}"> {% if model.admin_url %} <th … -
Cancel create when data is wrong
I have this class view which is connected to Model class DrawingViewSet(viewsets.ModelViewSet): queryset = m.Drawing.objects.all() serializer_class = s.DrawingSerializer def create(self, request, *args, **kwargs): request.data._mutable = True request.data['update_user'] = request.user.id request.data['create_user'] = request.user.id try: isDataGood(request.data) except: logger.error("data is not good") return Response(data={'error': 'This file is not pdf'}, status=406) In create method, I check the data in isDataGood and then return error when data is not good. However, even data is not good, it makes the row in model Drawing. I would like to cancel the creating row too. Is there any way to do this? -
Beget "doesn't see" DEBUG=False
I am hosting my test site on Beget and installed Django on it using CMS. I set the DEBUG=False in settings.py, but I think it "doensn't know" about it, because it's still showing me the Django introduction page, despite the fact that I've changed urls.py too and it must return my template. Also it keeps throwing this error "The Cross-Origin-Opener-Policy header has been ignored, because the URL's origin was untrustworthy. It was defined either in the final response or a redirect. Please deliver the response using the HTTPS protocol. You can also use the 'localhost' origin instead". Now it's trying to fetch 'http://domain/favicon.ico' and it throws 404. I don't know why is it like that. Can someone help me? EDITED: The last 404 error disappeared, lol -
I am Unable to toggle my completed todo on the backend as well as on the frontend
I am unable to toggle my completed todo on the backend as well as on the frontend, If once completed set to true is not returning back to false import { useContext, useEffect, useState } from "react"; import AuthContext from "../context/AuthContext"; const TodoApp = () => { // const [clicked , setClicked] = useState(false) const { authTokens, fetchTasks, tasks, user, createTask, updateTask, deleteTask, setButtonClicked, setTasks, buttonClicked, updateComplete, } = useContext(AuthContext); // console.log('authTokens in TodoApp:', authTokens); useEffect(() => { console.log("buttonClicked:", buttonClicked); if (user) { fetchTasks(); } // console.log("rendered"); // console.log(fetchTasks()); }, [user]); const handleButtonClick = async (id) => { await updateComplete(id); }; return ( <> <form onSubmit={(e) => { e.preventDefault(); createTask(e.target.taskTitle.value); e.target.taskTitle.value = ""; }} className="bg-white md:w-[60vw] w-[90vw] md:h-24 h-16 md:p-4 p-2 flex gap-2 shadow-lg shadow-indigo-500/50 " > <input type="text" name="taskTitle" placeholder="Username" className="input input-bordered w-[72%] md:h-16 h-11 text-black flex-[3_1_0] " /> <button className=" btn btn-success md:h-16 h-6 w-[25%] text-3xl" type="submit" > + </button> </form> <br /> <div className="h-[calc(100vh-200px)] w-[100vw] mt-2 overflow-y-auto overflow-x-hidden"> {user && user ? ( tasks.map((ele) => ( <div key={ele.id} className=" h-24 w-[100vw] p-1"> <form onSubmit={(e) => e.preventDefault()} className=" m-auto border h-16 w-[90vw] md:w-[70vw] md:text-2xl rounded p-3 font-serif relative overflow-hidden" > {ele.completed ? ( <strike className="w-[50vw] text-black" key={ele.id}> {ele.title} … -
Problem in a customized permission in django rest framework
I tried to make a customized permission class which ensures that the user is authenticated and the authenticated user trying to access the endpoint is accessing information related to him not another user. This is the customized class: from rest_framework.permissions import BasePermission class IsAuthenticatedAndSameUser(BasePermission): def has_object_permission(self, request, view, obj): if request.method == "GET" or request.method == 'DELETE': print(request.user) if request.user.is_authenticated and (request.user == obj.user): return True else: return False I gave the Viewset the new customized class in permission classes. class AccountViewset(viewsets.ModelViewSet): queryset = Account.objects.all() serializer_class = AccountSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticatedAndSameUser,) @action(detail=True, methods=['get'], permission_classes=(IsAuthenticatedAndSameUser, )) def orders(self, request, pk, *args, **kwargs): The permission class works fine when I try to access endpoints related to the Account model directly like: http://127.0.0.1:8000/api/accounts/2/ But it doesn't work as expected on the action decorator. When I use the endpoint related to the action decorator: http://127.0.0.1:8000/api/accounts/2/orders/. The class uses the has_permission function instead of has_object_permission function in IsAuthenticatedAndSameUser class. I want it to use the has_object_permission function. Models used: Account model class Account(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) user = models.OneToOneField(User, on_delete=models.CASCADE) balance = models.DecimalField(decimal_places=2, max_digits=9) def __str__(self): return f'Name: {self.user.username} / Balance: {self.balance}' Order model: class Order(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, … -
Don't see models in db.sqlite3(Python, Django)
I'm trying to make a custom user model using, abstract user, but yet can't see them on DB. https://codesandbox.io/p/sandbox/condescending-archimedes-h7lx22?file=%2Fsettings.py%3A158%2C23 I used abstract user to modify the original User class. I then procced to make a seralizer, did migrations(without any errors), and then added the AUTH_USER_MODEL = 'base.CustomUser' to settings.py. And still I don't see the models on the DB file. https://codesandbox.io/p/sandbox/condescending-archimedes-h7lx22?file=%2Fsettings.py%3A158%2C23 -
User online status functionality not working
I am making a django website where users can log in. One of the functionality I need in this website is the "is_active" functionality which basically means data that stores whether the user is offline or online is stored in the database. The following is the code which I will explain below: base.html (the file that is being extended in all pages of the website): {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" contents="'ie=edge"> <link rel="stylesheet" type="text/css" href="{% static 'base.css' %}"> {% block stylesheet %} {% endblock %} <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous"> {% if title %} <title>{{ title }}</title> {% else %} <title>Random title</title> {% endif %} </head> <body> <nav> <div class="logo">Website Name</div> <ul class="nav-links"> <li><a href="{% url 'common-anime-chat-home' %}">Home</a></li> <li><a href="{% url 'register' %}">Register</a></li> {% if request.user.is_authenticated %} <li><a href="{% url 'logout' %}">Logout</a></li> <li><a href="{% url 'profile' %}">Profile</a></li> {% else %} <li><a href="{% url 'login' %}">Login</a></li> {% endif %} <li><a href="">About Us</a></li> </ul> <form class="search-form"> <input type="text" placeholder="Search..."> <button type="submit">Search</button> </form> </nav> {% if messages %} <div class="alert alert-success" role="alert" style="margin-bottom: 0px;"> {% for message in messages %} {{ message }} <br> {% endfor %} </div> {% endif %} {% … -
DRF prefetch related still causing N+1 queries
Models: class GradePolicy(models.Model): name = models.CharField(max_length=30) minScore = models.DecimalField(default=0, max_digits=4, decimal_places=1, db_column="minscore") maxScore = models.DecimalField(max_digits=4, decimal_places=1, default=100, db_column="maxscore") policyChoices = ( ('Numerical', 'Numerical'), ('Textual', 'Textual') ) type = models.CharField(max_length=30, default='Textual', choices=policyChoices) class GradeLevel(models.Model): name = models.CharField(max_length=30) score = models.DecimalField(decimal_places=2, max_digits=5) abbreviation = models.CharField(max_length=4) policy = models.ForeignKey(GradePolicy, null=True, blank=True, on_delete=models.DO_NOTHING) Views: class GradePolicyViewSet(viewsets.ModelViewSet): """ Retrieve grade policies """ queryset = GradePolicy.objects.prefetch_related('gradelevel_set').order_by('pk') serializer_class = GradePolicySerializer class GradeLevelViewSet(viewsets.ModelViewSet): queryset = GradeLevel.objects.all().order_by('pk') serializer_class = GradeLevelSerializer I'm getting reports from Sentry that calling /gradepolicies, which is the list endpoint for GradePolicy, is causing N+1 queries. Looking at the queries, that does seem to be the case: (0.004) SELECT "gbook_gradepolicy"."id", "gbook_gradepolicy"."name", "gbook_gradepolicy"."minscore", "gbook_gradepolicy"."maxscore", "gbook_gradepolicy"."type" FROM "gbook_gradepolicy" ORDER BY "gbook_gradepolicy"."id" ASC; args=() (0.005) SELECT "gbook_gradelevel"."id", "gbook_gradelevel"."name", "gbook_gradelevel"."score", "gbook_gradelevel"."abbreviation", "gbook_gradelevel"."policy_id" FROM "gbook_gradelevel" WHERE "gbook_gradelevel"."policy_id" = 2 ORDER BY "gbook_gradelevel"."score" DESC; args=(2,) (0.001) SELECT "gbook_gradelevel"."id", "gbook_gradelevel"."name", "gbook_gradelevel"."score", "gbook_gradelevel"."abbreviation", "gbook_gradelevel"."policy_id" FROM "gbook_gradelevel" WHERE "gbook_gradelevel"."policy_id" = 3 ORDER BY "gbook_gradelevel"."score" DESC; args=(3,) (0.001) SELECT "gbook_gradelevel"."id", "gbook_gradelevel"."name", "gbook_gradelevel"."score", "gbook_gradelevel"."abbreviation", "gbook_gradelevel"."policy_id" FROM "gbook_gradelevel" WHERE "gbook_gradelevel"."policy_id" = 4 ORDER BY "gbook_gradelevel"."score" DESC; args=(4,) (0.001) SELECT "gbook_gradelevel"."id", "gbook_gradelevel"."name", "gbook_gradelevel"."score", "gbook_gradelevel"."abbreviation", "gbook_gradelevel"."policy_id" FROM "gbook_gradelevel" WHERE "gbook_gradelevel"."policy_id" = 5 ORDER BY "gbook_gradelevel"."score" DESC; args=(5,) (0.001) SELECT "gbook_gradelevel"."id", "gbook_gradelevel"."name", "gbook_gradelevel"."score", "gbook_gradelevel"."abbreviation", "gbook_gradelevel"."policy_id" FROM "gbook_gradelevel" WHERE "gbook_gradelevel"."policy_id" = 6 … -
useRef error appears in console while not using it
null is not an object (evaluating 'R.current.useRef') I get this error in my console after building my React App, i’m not using useRef in my code, only dependencies i’m installing are react-router-dom. I get no errors when building, everything is imported correctly, my react version is 18.2.0, react router dom version is v6, I tried every combination possible of the routers, I don’t know if the error is a React router error or another thing, but my app is still not complex, all of the pages are blank or with a header. here is my App.js import React from "react"; import { Route, Routes } from "react-router-dom"; // Make sure to import Route and Routes correctly import Home from "./pages/Home"; import NoPage from "./pages/NoPage"; import Admin from "./pages/Admin"; import Search from "./pages/Search"; import Song from "./pages/Song"; import Artist from "./pages/Artist"; import Album from "./pages/Album"; import Layout from "./pages/Layout"; function App() { return ( <Routes> <Route path="/" element={<Home />} /> <Route path="/search" element={<Search />} /> <Route path="/song" element={<Song />} /> <Route path="/album" element={<Album />} /> <Route path="/artist" element={<Artist />} /> <Route path="/admin" element={<Admin />} /> </Routes> ); } //<Route path="*" element={<NoPage />} /> export default App; here is my index.js import … -
Synching Django Session with Database
Please I'm working on an E-Commerce website with Django. I'm currently trying to build the shopping cart but there's a challenge. The shopping cart was built with the Django session. However, I need to retain this cart for each user even after logout, because it wipes the session upon logout. I understand I have to make use of a database in some way. I need help to get this done, please. views.py from django.contrib.auth import user_logged_out, user_logged_in from django.dispatch import receiver from django.shortcuts import render, get_object_or_404, redirect from django.views.decorators.http import require_POST from chollo_cart.chollo_cart import Cart from chollo_cart.forms import CartAddProductForm from chollo_main.models import Product # Create your views here. @require_POST def add_to_cart(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): clean_data = form.cleaned_data cart.add(product=product, quantity=clean_data['quantity'], overide_quantity=clean_data['override']) return redirect('chollo_cart:cart_detail') # Note the addition of 'id=' that was not formerly there @require_POST def remove_from_cart(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('chollo_cart:cart_detail') def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm(initial={ 'quantity': item['quantity'], 'override': True }) return render(request, 'chollo_main/cart-details.html', {'cart': cart}) Here's the cart.py from decimal import Decimal from django.conf import settings from chollo_main.models import Product class Cart: def __init__(self, request): """ … -
django.urls.exceptions.NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name
I got the error: django.urls.exceptions.NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. when write https://chalets.com:8000/accounts/login in URL. I notice that when remove namespace and app_name of accounts from urls.py, the URL reverse to login successfully. I want to know why raise error when use namespace? and how solve the error? Here is urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('accounts/', include('accounts.urls', namespace='accounts')), path('social-auth/', include('social_django.urls', namespace='social')), path('', include('homepage.urls', namespace='home')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and the urls.py of accounts: from django.urls import path from accounts.views import SignUpView, LogoutView, LoginView app_name = 'accounts' urlpatterns = [ path('signup', SignUpView.as_view(), name='signup'), path('login', LoginView.as_view(), name='login'), path('logout', LogoutView.as_view(), name='logout') ] views.py: class SignUpView(generic.CreateView): form_class = SignUpForm template_name = 'signup.html' def form_valid(self, form): # get data from form email = form.cleaned_data['email'] password1 = form.cleaned_data['password1'] password2 = form.cleaned_data['password2'] # save user in database with hash password user = User(email=email, password=password1) user.set_password(password1) user = user.save() # authenticate, login, and redirect to home user = authenticate(email=email, password=password1) login(self.request, user) return redirect('home') class LoginView(generic.FormView): template_name = 'login.html' form_class = LoginForm def form_valid(self, form): # get data from for and authenticate … -
celery beat dynamically scheduler
I have a database with time and metadata for dynamically scheduled tasks. from __future__ import absolute_import, unicode_literals import os from celery import Celery from concentrApp import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'concentrApp.settings') app = Celery('concentrApp') # You can add celery settings in settings.py starting with CELERY_ app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda : settings.INSTALLED_APPS) # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'concentrApp.settings') app.conf.timezone = "Asia/Jerusalem" I made functions that take the data from the database and insert into the celery: from datetime import datetime from application.models import Schedule from concentrApp.celery import app from celery.schedules import crontab def get_data_from_database(): return Schedule.objects.all() # hour, min should be int, change day_of_week to "0-3" def create_celery_schedule(hour, minute): return crontab(minute=int(minute), hour=int(hour), day_of_week="0-6") def update_or_delete_scheduled_task(task_data, new_schedule=None): task_name = task_data.id expo_token = task_data.participant.expo_token if new_schedule: app.conf.beat_schedule[task_name] = { "task": "concentrApp.tasks.notify", # Replace with the actual task path "schedule": new_schedule, "args": (expo_token, task_data.context,), # Additional arguments if needed } else: del app.conf.beat_schedule[task_name] def update_celery_beat_schedule(): tasks = get_data_from_database() for task_data in tasks: hour, minute = task_data.ping_times.split(':') schedule = create_celery_schedule(hour, minute) update_or_delete_scheduled_task(task_data, new_schedule=schedule) print(app.conf.beat_schedule) @app.task(name="notify") def notify(participant_token, context): current_datetime = datetime.datetime.now() formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S") with open('output.txt', 'a') as file: file.write(formatted_datetime + participant_token + '\n') When I print app.conf.beat_schedule, I can … -
Django Admin - Custom Action with forms
I'm attempting to build a custom admin action. When users trigger this action, it should open a new window featuring a dropdown. They'll choose an option, and upon submission, the selected value will update multiple rows. Currently, I've managed to create this functionality, but I'm encountering an issue. When the form submits and redirects back to the admin interface, the selected value isn't present in the request's POST data. model.py: class Intervencao(models.Model): .... responsavel = models.ForeignKey(Responsavel, blank=True, null=True, on_delete=models.CASCADE,verbose_name="Responsavel") ..... class Responsavel(models.Model): nome = models.CharField("Responsável", max_length=200) admin.py: class IntervencaoAdmin(admin.ModelAdmin): .... def assign_all_view(self, request, queryset): form = AssignResponsavelForm(request.POST or None) print("POST data:", request.POST) # Debug: Print the entire POST data print("new_responsavel_id:", request.POST.get('new_responsavel')) # Debug: Print the new_responsavel_id if request.method == 'POST': if form.is_valid(): new_responsavel = form.cleaned_data['new_responsavel'] selected_items = form.cleaned_data['selected_items'] # Debug print statements print("New Responsável ID:", new_responsavel.id) print("Selected Items:", selected_items) Intervencao.objects.filter(pk__in=selected_items).update(responsavel=new_responsavel) # Debug message print("Responsável updated successfully") context = { 'form': form, 'queryset': queryset, } return render(request, 'admin/assign_all_view.html', context) actions = [assign_all_view] form.py class AssignResponsavelForm(forms.Form): new_responsavel = forms.ModelChoiceField(queryset=Responsavel.objects.all(), label="Novo Responsável") selected_items = forms.ModelMultipleChoiceField(queryset=Responsavel.objects.all(), widget=forms.MultipleHiddenInput()) assign_all_view.html {% load static %} {% block content %} <div class="module"> <h2>Trocar de Responsável</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Trocar Responsável" class="default" … -
How remove passwords in Django signup form
I'm using Django CustomerUser model , and as most webapp today just ask for email for sigup and later on after email confirmation user can set the password wondering how can implement this workflow in django authentication. from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): email = models.EmailField( verbose_name="email address", max_length=255, unique=True, ) def __str__(self): return self.email from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser from django import forms class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ["email"] class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ["email"] -
Zoom In Zoom out (like fly in-text )
XYZ should be at the top level. When I zoom in, it should display the agent, and when I zoom in on the agent, it should show their details. There might be other functionalities as well. Additionally, I am using ReactJS for the frontend and Django for the backend. How can i achieve that? I am new to react. Give me some examples -
Django db not updating using Docker on production
Using Django and Postgres for my project, I can't update my database on the production environment. I also tried running migration commands manually on the server, but it doesn't seem to work, as it always says the migrations are already applied and no changes are detected. When I check the migrations folder, I can see my new changes are specifically written, but the migrations aren't applied because I get a db error when I open the django admin panel; so I have no choice but to run docker compose down -v to delete the db and start fresh. (which is terrible cause I loose all my db records) I believe it might be a cause of ignoring my migrations files, so the only things pushed to the server are regular files and migrations/__init__.py, so django can detect the app and apply the migrations. Note that pushing all my migrations files to the server is not an option, because it's not efficient to go through all the changes I had in my local environment. Is there any way I can solve this problem? Dockerfile: FROM python:3.10-buster RUN apt-get update #RUN useradd -m myapp RUN mkdir -p /home/myapp/app WORKDIR /home/myapp/app ENV PYTHONDONTWRITEBYTECODE=1 … -
Separate TabularInline format page in Django Admin Panel
I was implementing Tabularinline in my code, Admin.py class EmpEducationInline(admin.TabularInline): model = EmpEducation extra = 1 min_num = 1 max_num = 10 class EmployeeAdmin(admin.ModelAdmin): list_display = ('get_serial_number', 'employee_id', 'name', 'department_name', 'design', 'doj', 'salary', 'display_img', 'edit_emp', 'delete_emp') list_per_page = 25 search_fields = ('emp_id', 'name') inlines = [EmpEducationInline] admin.site.register(Employees, EmployeeAdmin) class EmpEducationAdmin(admin.ModelAdmin): list_display = ('emp_id', 'degree', 'depart', 'institution', 'year') list_filter = ('emp_id', 'degree', 'depart', 'institution') admin.site.register(EmpEducation, EmpEducationAdmin) my output EmployeeAdmin EmpEducation Admin Here Tabular inline Format was showing in Employee Admin Page, But I want Separate TabularInline Format in EmpEducation Admin based on My model. I want to Enter education related details separately in another model. Becaz I want to implement the concept of bulk creation here. In Employee Education form look, employee Id was in Dropdown remaining details below like image Employee Education Separate Here below I shared my models.py code class EmpEducation(models.Model): emp_id = models.ForeignKey( 'Employees', models.PROTECT, db_column='emp_id') degree = models.CharField(max_length=45) depart = models.CharField(max_length=45) institution = models.CharField(max_length=45) year = models.IntegerField() class Meta: managed = False db_table = 'emp_education' Thanks in advance...