Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how do I add an item to the cart without the page reloading?
So I wanna add an item to the cart without the page reloading every time, So is there a way to go about this, that won't be slow? if so, how would I fix this? also not the best with javascript so if u can explain stuff a bit, I would really appreciate your help, thx! link to the rest main code: https://gist.github.com/StackingUser/34b682b6da9f918c29b85d6b09216352 template: {% load static %} <link rel="stylesheet" href="{% static 'store/css/shop.css' %}" type="text/css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript"> var user = '{{request.user}}' function getToken(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getToken('csrftoken'); function getCookie(name) { // Split cookie string and get all individual name=value pairs in an array var cookieArr = document.cookie.split(";"); // Loop through the array elements for(var i = 0; i < cookieArr.length; i++) { var cookiePair = cookieArr[i].split("="); /* Removing whitespace at the beginning of … -
How to make Django user specific (data) in a to do app?
I am trying to separate tasks between all users that log in, but nothing I've tried has worked. All users are able to see other users' tasks, which isn't what I want. Below is the model and view function that I am using to create a task. Thanks in advance. class Tasks(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) complete = models.BooleanField(default=False) finish = models.CharField(max_length=50) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ['complete'] Task View def taskList(request): q = request.GET.get('q') if request.GET.get('q') != None else '' tasks = Tasks.objects.filter(title__contains=q,user=request.user) tasks_count = tasks.count() context = {'tasks':tasks, 'tasks_count':tasks_count} return render(request, 'base/home.html', context) Am I missing something in my models? -
Setup login session for sub domain from main domain in Django
I have a main domain example.com and a subdomain tenant.example.com. A user comes to http://example.com/login and logs In, By default, Django set a session cookie for example.com. What I want is that Django set the session cookie for tenant.example.com instead of example.com. How can I implement this? -
Errorvalue: Field 'phone' expected a number but got 'Admin@gmail.com'
When I was trying to login with email it shows error message but I need it has a comment .The code should not show "ValueError: Field 'phone' expected a number but got 'Admin@gmail.com'".and " ValueError: Field 'phone' expected a number but got 'Admin@gmail.com'." Below are the code of views.py and login.html and my checkbox is also not working. views.py def loginf(request): if request.method=='POST': phone=request.POST.get('phone') password=request.POST.get('password') user = authenticate(username=phone, password=password) try: remember = request.POST['checkbox'] if remember: settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = False except: is_private = False settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = True u = User.objects.filter(phone=phone,otp=password).exists() if u and user is not None: r=User.objects.filter(phone=phone,otp=password) status=r[0].status if status=="Active": role=r[0].role if role == "Employee": login(request,user) return redirect('listtask') elif role == "Consultant": userid=r[0].id login(request,user) return redirect('consultatntbilling',userid=userid) else: messages.info(request,"Account is Inactive") return render(request,'login.html') else: messages.info(request," Invalid Phone Number or Password") return render(request,'login.html') return render(request,'login.html')` login.html` Login to continue.. <div class="container"> {% for message in messages %} <div class="alert alert-warning alert-dismissible fade show" role="alert"> {{ message }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="close"></button> </div> {% endfor %} </div> <form method ="POST" action="{% url 'loginf' %}"> {% csrf_token %} <div class="form-group"> <label class="form-control-label">Phone Number</label> <input class="form-control" name="phone" required> </div> <div class="form-group"> <label class="form-control-label">Password</label> <input class="form-control" name="password" required> </div> <!-- <div class="form-group"> <div class="fxt-transformY-50 fxt-transition-delay-3"> <input … -
Django NoReverseMatch at / '{'pk': ''}' not found
django make post detial page NoReverseMatch at / Reverse for 'blog_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)/\Z'] how can i fix it please help me templates <header class="mb-4"> {% for list in postlist %} <!-- Post title--> h1><a href="{% url 'blog_detail' pk=post.pk %}" class="fw-bolder mb-1">{{list.title}</a</h1> urls from . import views urlpatterns = [ path('', views.index, name='index'), path('post/<int:pk>/', views.blog_detail, name='blog_detail'), ] views from .models import Post from django.shortcuts import render, get_object_or_404 def index(request): postlist = Post.objects.all() return render(request, 'main/blog_post_list.html', {'postlist':postlist}) def blog_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'main/blog_detail.html', {'post': post}) -
Django ELasticBeanstalk error Deploy requirements.txt - EB
So, I was using SQlite but, i switched to MySQL, then i did the command pip install mysqlclient and i connected to the database, did python manage.py makemigrations and python manage.py migratre I only got this message from the log but I guess it's not important: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/4.0/ref/databases/#mysql-sql-mode then i excluded my requirements.txt then i did pip freeze > requirements.txt, did the deploy and did eb logs to get the error below Collecting mysqlclient==2.1.0 Using cached mysqlclient-2.1.0.tar.gz (87 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' 2022/04/25 05:42:23.880429 [INFO] error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 \u2570─> [16 lines of output] /bin/sh: mysql_config: command not found /bin/sh: mariadb_config: command not found /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-52csz_by/mysqlclient_d55944e3cacc47d8998c991cac209734/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-52csz_by/mysqlclient_d55944e3cacc47d8998c991cac209734/setup_posix.py", line 70, in … -
SystemCheckError: System check identified some issuess:
When I added this profile model then only I am getting this error. I really don't know what to do here. please help me out this. models.py: class Profile(User): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.TextField(max_length=200,null=False) contact_number = models.PositiveIntegerField(null=False) ut=(('Admin','Admin'),('Operator','Operator'),('Ticket generator User','Ticket generator User'),('Inspector','Inspector'),('User 80','User 80'),('Final Inspection','Final Inspection'),('Maintenance','Maintenance'),('Ticket Admin','Ticket Admin'),) user_type = models.CharField(max_length=200, null=False, choices=ut) Erros: raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: Master.Profile.user: (fields.E304) Reverse accessor for 'Master.Profile.user' clashes with reverse accessor for 'Master.Profile.user_ptr'. HINT: Add or change a related_name argument to the definition for 'Master.Profile.user' or 'Master.Profile.user_ptr'. Master.Profile.user: (fields.E305) Reverse query name for 'Master.Profile.user' clashes with reverse query name for 'Master.Profile.user_ptr'. HINT: Add or change a related_name argument to the definition for 'Master.Profile.user' or 'Master.Profile.user_ptr'. Master.Profile.user_ptr: (fields.E304) Reverse accessor for 'Master.Profile.user_ptr' clashes with reverse accessor for 'Master.Profile.user'. HINT: Add or change a related_name argument to the definition for 'Master.Profile.user_ptr' or 'Master.Profile.user'. Master.Profile.user_ptr: (fields.E305) Reverse query name for 'Master.Profile.user_ptr' clashes with reverse query name for 'Master.Profile.user'. HINT: Add or change a related_name argument to the definition for 'Master.Profile.user_ptr' or 'Master.Profile.user'. System check identified 4 issues (0 silenced). -
Any python/django libraries that convert datetime and timedeltas to phrases like "tonight at 8pm" or "tomorrow evening"?
I'm looking for a python or django library to give me humanized timedates to read like "tomorrow evening at 8pm" or "tonight at 8pm" or "next Monday at 8pm". I've seen django.contrib.humanize and arrow but neither give that level of humanization. Does such a library exist? (Obviously not rocket science to write it myself, but I figure I'm not the first person to want such a thing...) -
Can't debug in VS Code for Django?
When I use VS Code IDE to debug, I get an error message: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Why? How do I fix it? Thanks. -
Openstack Trove - Polling request timed out
We are trying to deploy OpenStack environment for our application and while deploying trove service we are facing the below error: File "/usr/lib/python3/dist-packages/trove/common/utils.py", line 207, in wait_for_task return polling_task.wait() File "/usr/lib/python3/dist-packages/eventlet/event.py", line 125, in wait result = hub.switch() File "/usr/lib/python3/dist-packages/eventlet/hubs/hub.py", line 313, in switch return self.greenlet.switch() File "/usr/lib/python3/dist-packages/oslo_service/loopingcall.py", line 154, in _run_loop idle = idle_for_func(result, self._elapsed(watch)) File "/usr/lib/python3/dist-packages/oslo_service/loopingcall.py", line 349, in _idle_for raise LoopingCallTimeOut( oslo_service.loopingcall.LoopingCallTimeOut: Looping call timed out after 870.99 seconds During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/trove/taskmanager/models.py", line 434, in wait_for_instance utils.poll_until(self._service_is_active, File "/usr/lib/python3/dist-packages/trove/common/utils.py", line 223, in poll_until return wait_for_task(task) File "/usr/lib/python3/dist-packages/trove/common/utils.py", line 209, in wait_for_task raise exception.PollTimeOut trove.common.exception.PollTimeOut: Polling request timed out.``` -
TypeError at /mark_your_attendance Can't parse 'center'. Sequence item with index 0 has a wrong type
Hello guys! i am working on attendance system using Face Recognition, i have trained the captured images once want to mark the attendance it gives me following error, i have used django at backend. TypeError at /mark_your_attendance Can't parse 'center'. Sequence item with index 0 has a wrong type Request Method: GET Request URL: http://127.0.0.1:8000/mark_your_attendance Django Version: 2.2.2 Exception Type: TypeError Exception Value: Can't parse 'center'. Sequence item with index 0 has a wrong type Exception Location: /home/saifullah/Desktop/attendance/attendance-system/env/lib/python3.8/site-packages/imutils/face_utils/facealigner.py in align, line 68 Python Executable: /home/saifullah/Desktop/attendance/attendance-system/env/bin/python3 Python Version: 3.8.10 Python Path: ['/home/saifullah/Desktop/attendance/attendance-system', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/saifullah/Desktop/attendance/attendance-system/env/lib/python3.8/site-packages'] Hereby i am sharing the code can anyone please help how to solve it. Code def mark_your_attendance(request): detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor( 'face_recognition_data/shape_predictor_68_face_landmarks.dat') # Add path to the shape predictor ######CHANGE TO RELATIVE PATH LATER svc_save_path = "face_recognition_data/svc.sav" with open(svc_save_path, 'rb') as f: svc = pickle.load(f) fa = FaceAligner(predictor, desiredFaceWidth=96) encoder = LabelEncoder() encoder.classes_ = np.load('face_recognition_data/classes.npy') faces_encodings = np.zeros((1, 128)) no_of_faces = len(svc.predict_proba(faces_encodings)[0]) count = dict() present = dict() log_time = dict() start = dict() for i in range(no_of_faces): count[encoder.inverse_transform([i])[0]] = 0 present[encoder.inverse_transform([i])[0]] = False vs = VideoStream(src=0).start() sampleNum = 0 while(True): frame = vs.read() frame = imutils.resize(frame, width=800) gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces … -
How to override excel file before saving on disk in django-import-export?
I used django-import-export for exporting excel files. I want to add an extra row including our company name before the actual data. Actual data: id name 1 Jack 2 Sara ... ... My desired output: An extra row before the header including "This excel has been created by Our Brand". How can I modify the generated excel file before saving on disk? -
whilw performing CURD operation i got error. Using the URLconf defined in Student.urls, Django tried these URL patterns, in this order:
Using the URLconf defined in Student.urls, Django tried these URL patterns, in this order: admin/ emp [name='emp'] show [name='show'] edit/int:roll_no [name='edit'] update/int:roll_no [name='update'] delete/int:roll_no [name='delete'] The current path, update/, didn’t match any of these. While Performing django CURD operation I got above error.. my code from main( student urls.py):- from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('stud_details.urls')) from app stud_details(urls.py) from stud_details import views urlpatterns = [ path('',views.index), path("emp",views.emp, name='emp'), path("show",views.show, name='show'), path("edit/<int:roll_no>",views.edit, name='edit'), path("update/<int:roll_no>",views.update, name='update'), path("delete/<int:roll_no>",views.destroy, name='delete') from views.py: from stud_details.forms import Stud_form from stud_details.models import Stud_class def emp(request): if request.method == "POST": form = Stud_form(request.POST) if form.is_valid(): try: form.save() return redirect('/show') except: pass else: form = Stud_class() return render(request,'index.html',{'form':form}) def show(request): students = Stud_class.objects.all() return render(request,"show.html",{'students':students}) def index(request): return render(request,"index.html") def edit(request, roll_no): students = Stud_class.objects.get(roll_no=roll_no) return render(request,'edit.html', {'students':students}) def update(request, roll_no): students = Stud_class.objects.get(roll_no=roll_no) form = Stud_form(request.POST, instance = students) if form.is_valid(): form.save() return redirect("/show") return render(request, 'edit.html', {'Stud_class': employee}) def destroy(request, roll_no): students = Stud_class.objects.get(roll_no=roll_no) students.delete() return redirect("/show") What I'm doing wrong -
My django project keeps blinking and loading
my project was working before but now that cleaned my cache it keeps blinking. It keeps loading with no end in sight. The table in my project appears and disappears again and again blinking. The navbar and thead are fine but my tbody keeps doing it. Does anyone know how to fix this? -
Q : run a python function in Django project but output repeat result
I want to detect the number of files when run a django project.But there are two output results in terminal . def fileChecker(path): print('Child process %s.' % os.getpid()) dirs = os.listdir(path) size = len(dirs) while True : tdirs = os.listdir(path) if len(tdirs) > size : print( 'folder contains %s files '%( len(tdirs) ) ) size = len(tdirs) dirs = tdirs def main(): """Run administrative tasks.""" print('Child process %s.' % os.getpid()) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'parkSystem.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': print('Parent process %s.' % os.getpid()) p1 = Process( target=main ) p2 = Process( target=fileChecker, args=('.\\pictures\\car_img',)) p1.start() p2.start() p1.join() p2.join() the terminal like this : enter image description here -
How to streamline code with a for statement
I am trying to find the number of students enrolled by teacher. The code below produces the result I want. However, the code seems to be inefficiently long. I tried to simplify the code by using a "for" functiib, but couldn't solve it, so I posted a question to the experts for help. The number registered in SPECIAL CLASS must be obtained separately. The register condition is student with 1 entered in the day field. monthly_kwargs = { 'jan': Count('student_id', filter=Q(register_date__gte='2022-01-01', register_date__lte='2022-01-31')), 'feb': Count('student_id', filter=Q(register_date__gte='2022-02-01', register_date__lte='2022-02-28')), 'mar': Count('student_id', filter=Q(register_date__gte='2022-03-01', register_date__lte='2022-03-31')), 'apr': Count('student_id', filter=Q(register_date__gte='2022-04-01', register_date__lte='2022-04-30')), 'may': Count('student_id', filter=Q(register_date__gte='2022-05-01', register_date__lte='2022-05-31')), 'jun': Count('student_id', filter=Q(register_date__gte='2022-06-01', register_date__lte='2022-06-30')), 'jul': Count('student_id', filter=Q(register_date__gte='2022-07-01', register_date__lte='2022-07-31')), 'aug': Count('student_id', filter=Q(register_date__gte='2022-08-01', register_date__lte='2022-08-31')), 'sept': Count('student_id', filter=Q(register_date__gte='2022-09-01', register_date__lte='2022-09-30')), 'oct': Count('student_id', filter=Q(register_date__gte='2022-10-01', register_date__lte='2022-10-31')), 'nov': Count('student_id', filter=Q(register_date__gte='2022-11-01', register_date__lte='2022-11-30')), 'dec': Count('student_id', filter=Q(register_date__gte='2022-12-01', register_date__lte='2022-12-31')), 'total': Count('student_id', filter=Q(register_date__year=today.year)), 'SPECIAL_jan': Count('student_id', filter=Q(register_date__gte='2022-01-01', register_date__lte='2022-01-31', student__class__id__in=SPECIAL)), 'SPECIAL_feb': Count('student_id', filter=Q(register_date__gte='2022-02-01', register_date__lte='2022-02-28', student__class__id__in=SPECIAL)), 'SPECIAL_mar': Count('student_id', filter=Q(register_date__gte='2022-03-01', register_date__lte='2022-03-31', student__class__id__in=SPECIAL)), 'SPECIAL_apr': Count('student_id', filter=Q(register_date__gte='2022-04-01', register_date__lte='2022-04-30', student__class__id__in=SPECIAL)), 'SPECIAL_may': Count('student_id', filter=Q(register_date__gte='2022-05-01', register_date__lte='2022-05-31', student__class__id__in=SPECIAL)), 'SPECIAL_jun': Count('student_id', filter=Q(register_date__gte='2022-06-01', register_date__lte='2022-06-30', student__class__id__in=SPECIAL)), 'SPECIAL_jul': Count('student_id', filter=Q(register_date__gte='2022-07-01', register_date__lte='2022-07-31', student__class__id__in=SPECIAL)), 'SPECIAL_aug': Count('student_id', filter=Q(register_date__gte='2022-08-01', register_date__lte='2022-08-31', student__class__id__in=SPECIAL)), 'SPECIAL_sept': Count('student_id', filter=Q(register_date__gte='2022-09-01', register_date__lte='2022-09-30', student__class__id__in=SPECIAL)), 'SPECIAL_oct': Count('student_id', filter=Q(register_date__gte='2022-10-01', register_date__lte='2022-10-31', student__class__id__in=SPECIAL)), 'SPECIAL_nov': Count('student_id', filter=Q(register_date__gte='2022-11-01', register_date__lte='2022-11-30', student__class__id__in=SPECIAL)), 'SPECIAL_dec': Count('student_id', filter=Q(register_date__gte='2022-12-01', register_date__lte='2022-12-31', student__class__id__in=SPECIAL)), 'SPECIAL_total': Count('student_id', filter=Q(register_date__year=today.year, student__class__id__in=SPECIAL)) } value_list_args = ['teacher__first_name', 'jan', 'feb', 'mar', … -
SocialApp matching query does not exist (Django)
I am trying social logins with Google and I configured localhost:8000/admin/ with the following details: socialapp . provider: Name: Client id: App ID, or consumer key Key: Secret: etc . In settings.py: INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.sites', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'ckeditor_uploader', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'offline', } } } I set SITE_ID = 2 When I go to: http://127.0.0.1:8000/login/google/login/ I get: Error : `SocialApp matching query does not exist. Can anyone help me? -
i want to get all product of specific merchant in html here is my code
i want to get all product of specific merchant in html here is my code so these should i write in html to get the products that merchant uploaded class ProductList(ListView): model=Product template_name="merchant/product_list.html" paginate_by=3 def get_queryset(self): filter_val=self.request.GET.get("filter","") order_by=self.request.GET.get("orderby","id") if filter_val!="": products=Product.objects.filter(Q(added_by_merchant__contains=filter_val) | Q(product_description__contains=filter_val)).order_by(order_by) else: products=Product.objects.all().order_by(order_by) # Product.MerchantUser.objects.all(user=MerchantUser) product_list=[] for product in products: product_media=ProductMedia.objects.filter(product_id=product.id,media_type=1,is_active=1).first() product_list.append({"product":product,"media":product_media}) return product_list def get_context_data(self,**kwargs): context=super(ProductList,self).get_context_data(**kwargs) context["filter"]=self.request.GET.get("filter","") context["orderby"]=self.request.GET.get("orderby","id") context["all_table_fields"]=Product._meta.get_fields() return context -
How to create multiple model instances with Django Rest Framework using generics?
I would like to save and update multiple instances using the Django Rest Framework with one API call, using generics. I have tried the solutions proposed for the following links, but I would very much appreciate some help. Create several objects at once with Django Framework Generic Views How to save multiple objects with Django Rest Framework Django Rest Framework Doc for serializing multiple objects # serializers.py class AssetSerializer(serializers.ModelSerializer): class Meta: model = Asset fields = '__all__' #fields = ('id', 'name', 'amount') # views.py class CreateAssetView(generics.CreateAPIView): serializer_class = AssetSerializer(many=True) def perform_create(self, serializer): serializer.save(user=self.request.user) # urls.py urlpatterns = [ ... path('create_asset', CreateAssetView.as_view()), ] -
Auto-submit django form without causing infinite loop
I have an issue on my app that I can't work out the best way to approach the solution. I'm learning Django and have little to no experience in Javascript so any help will be appreciated. This may be a design flaw, so am open to other ideas. Problem When a user reaches their dashboard page for the first time, they would need to select the currency rate on a form they want to view their data in e.g USD, AUD, GBP etc. Once they submit their currency, their dashboard will become active and viewable. I would like this selection to remain submitted on refresh/load or auto submit on refresh/load. Hence, that currency will remain, unless the user submits another currency. See before/after images for context (ignore values as they are inaccurate): Attempted solution I have tried using Javascript to auto submit on load which causes and infinite loop. I have read to use action to redirect to another page but i need it to stay on the same page. Unless this can be configured to only submit once after refresh/load I don't think this will work <script type="text/javascript"> $(document).ready(function() { window.document.forms['currency_choice'].submit(); }); </script> <div class="container"> <div> <span> <h1>My Dashboard</h1> … -
Django QuerySet exists() returns True for empty set?
Something curious I found recently is that exists() evaluates to True for an empty QuerySet: In [1]: MyModel.objects.all() Out [1]: <QuerySet []> In [2]: MyModel.objects.all().exists() Out [2]: True When used with filter(), I get the expected result: In [3]: MyModel.objects.filter(id=1).exists() Out [3]: False This is behaving contrary to how I would expect as the empty QuerySet returned by the filter() is equivalent to MyModel.objects.all() which is empty. Why does this happen? It seems inconsistent. -
how do I add an item to the cart without the page reloading?
So I wanna add an item to the cart without the page reloading every time, I've used ajax in a previous project and the response time wasn't pretty, so is there a better way to go about this, that won't be slow? if so, how would I fix this? also not the best with javascript so if u can explain stuff a bit, I would really appreciate your help, thx! link to the rest main code: https://gist.github.com/StackingUser/34b682b6da9f918c29b85d6b09216352 template: {% load static %} <link rel="stylesheet" href="{% static 'store/css/shop.css' %}" type="text/css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript"> var user = '{{request.user}}' function getToken(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getToken('csrftoken'); function getCookie(name) { // Split cookie string and get all individual name=value pairs in an array var cookieArr = document.cookie.split(";"); // Loop through the array elements for(var i = 0; i < … -
Toggle Switch Button using HTMX
is there any method to use Toggle Switch Button with HTMX? if there, I need to pass a value to another button like my previous question. the Toggle Button is named 'Toggle' and have two (on/off) values and I need to pass them as: <button class="btn btn-primary" hx-get="{% url 'plotlybar' %}" hx-include="[name='fields'],[name='Toggle']" hx-target="#plotlybar"> Plot the bar Well Serv </button> My previous question So how to get this Button with HTMX All my best -
How to add serializer for Django with ManyToManyField with through
models.py looks like this from django.db import models class Sauce(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Sandwich(models.Model): name = models.CharField(max_length=100) sauces = models.ManyToManyField(Sauce, through='SauceQuantity') def __str__(self): return self.name class SauceQuantity(models.Model): sauce = models.ForeignKey(Sauce, on_delete=models.CASCADE) sandwich = models.ForeignKey(Sandwich, on_delete=models.CASCADE) extra_sauce = models.BooleanField(default=False) def __str__(self): return "{}_{}".format(self.sandwich.__str__(), self.sauce.__str__()) How would I create a serializer for SauceQuantity so I can add and read SauceQuantity? I looked through the docs but I am still confused. Thanks! -
Django: How to run a celery task only on start up?
I have a django app that uses celery to run tasks. Sometimes, I have a "hard shutdown" and a bunch of models aren't cleaned up. I created a task called clean_up that I want to run on start up. Here is the tasks.py from my_app.core import utils from celery import shared_task @shared_task def clean_up(): f_name = clean_up.__name__ utils.clean_up() Here is what celery.py looks like: import os from celery import Celery from celery.schedules import crontab from datetime import timedelta os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_app.settings") app = Celery("proj") app.config_from_object("django.conf:settings", namespace="CELERY") # Load task modules from all registered Django apps. app.autodiscover_tasks() app.conf.beat_schedule = { "runs-on-startup": { "task": "my_app.core.tasks.clean_up", "schedule": timedelta(days=1000), }, } @app.task(bind=True) def debug_task(self): print(f"Request: {self.request!r}") How can I change celery.py to run clean_up only on start up? Extra info: this is in a docker compose, so by "hard shutdown" I mean docker compose down By "on start up" I mean docker compose up