Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to count in django templates
Hi I am trying to count infringement inside templates. The results I am getting for 'a' the counter is 1 1 (two separate values) instead of total count of 2 or 1 1 1 instead of a total of 3. Please help as I am new to programming. html {% for infringer in page_obj %} <tr> <td>{{infringer.id}}</td> <td>{{infringer.created|date:"d M, Y"}}</td> <td>{{infringer.name}}</td> <td>{{infringer.brand_name}}</td> <td>{{infringer.status}}</td> <td> {% with a=0 %} {% for i in inc %} {% if infringer.id == i.infringer.id %} {{ a|add:"1" }} {% endif %} {% endfor %} {% endwith %} views.py > @login_required(login_url='login') def infringerlist(request): q= > request.GET.get('q') if request.GET.get('q') != None else '' > ings= Infringer.objects.filter(Q(created__icontains=q) | > Q(id__icontains=q) | > Q(status__name__icontains=q) | > Q(brand_name__icontains=q) | > Q(name__icontains=q), > customer=request.user.customer, > > ) paginator = Paginator(ings, 10) page_number = request.GET.get('page') page_obj = > paginator.get_page(page_number) > > inc = Infringement.objects.filter(customer=request.user.customer) context= {'page_obj': page_obj, 'inc': inc} return render(request, > 'base/infringers_list.html', context) -
Django rest framework nest two or more viewsets instead of mapping custom actions with @action decorator
So, lets pretend im trying to build an API for a tiny Chat application. Imagine i have 2 models in my Django project, one is for Messages and the other is for Groups. Each group can have multiple messages, but a message belows to only one Group (resulting in an one to many relationship). here are the models: class Group(models.Model): title = models.CharField(max_length=250) def get_messages(self): return self.messages.all() class Message(models.Model): body = models.TextField() group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name="messages") And i have the following Django Rest Framework ViewSets: class GroupViewset(viewsets.ModelViewSet): queryset = Group.objects.all() serializer_class = GroupSerializer class MessageViewset(viewsets.ModelViewSet): queryset = Message.objects.all() serializer_class = MessageSerializer Viewsets are great! Only with those few lines i now have full CRUD operations for both Group and Message instances! I just need to access the following routes: /groups/ -> To make GET, POST operations for Group instances /groups/<group_pk>/ -> To make GET, PUT, PATCH, DELETE operations for Group instances /messages/ -> To make GET, POST operations for Message instances /messages/<message_pk>/ -> To make GET, PUT, PATCH, DELETE operations for Message instances but since a message belows to a Group, and i can get all messages of a group by doing GroupObject.get_messages(), im looking for a better way … -
Why do I keep getting an 'App not compatible with buildpack:' error when trying to deploy my django site to Heroku?
Here's the error: Building on the Heroku-22 stack -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed I've been following YouTube tutorials. Nothing helps. I tried reading the Heroku docs. To no avail. Please help. Thank you! -
How to get Data from Working History Model to the Detail Staff? I am new on Django
I have two seperated models. One with fields of Staff and one for multiple Working History Contract. Now I want to display all the Working History Contract of One Staff data in Staff detail view. What do I have to change in the Staff Detail view and in Staff.html? models.py class Staff(models.Model): nu_identifikasaun = models.CharField(max_length=15, null=False, blank=False,verbose_name="Numeru Identifikasaun") nu_funsionariu = models.CharField(max_length=5, null=False, blank=False, default=0,verbose_name="identifikasaun Funsionariu") naran = models.CharField(max_length=30, null=False, blank=False,verbose_name="Naran Uluk") apelidu = models.CharField(max_length=100, null=True, blank=True,verbose_name="Naran Rohan (Apelidu)") sexu = models.CharField(choices=[('Mane','Mane'),('Feto','Feto')],max_length=10,null=True,verbose_name="Seksu") estadu_sivil = models.CharField(choices=[('Kaben Nain','Kaben Nain'),('Klosan','Klosan'),('Viuvu/a','Viuvu/a'),('Divorsiadu/Separadu','Divorsiadu/Separadu')],max_length=30,null=True,verbose_name="Estadu Sivil") fatin_moris = models.CharField(max_length=100, null=True, blank=True,verbose_name="Fatin Moris") data_moris = models.DateField(null=True,blank=True,verbose_name="Loron Moris") hela_fatin = models.CharField(max_length=100, null=True, blank=True,verbose_name="Hela Fatin") munisipiu = models.ForeignKey(Munisipiu, on_delete=models.CASCADE, null=True,related_name="Munisipiu",blank=True) kontaktu = models.IntegerField(null=True, blank=True,verbose_name="Numeru Telemovel") email_pessoal = models.EmailField(max_length=254,verbose_name="Email Pessoal") email_ofisial = models.EmailField(max_length=254,verbose_name="Email Ofisial") imajen = models.ImageField(upload_to='Funsionariu', null=True,blank=True,verbose_name="Fotografia") def __str__(self): #template = '{0.name}' return self.naran class Meta: verbose_name_plural='6-Dadus_Funsionariu_funsionariu' class ContractHistory(models.Model): funsionariu = models.ForeignKey(Staff, on_delete=models.CASCADE, related_name="funsionariuKSerbisu", verbose_name="Funsionariu") pozisaun = models.ForeignKey(Pozisaun, on_delete=models.CASCADE, null=True,related_name="Pozisaun",blank=True) salariu = models.CharField(max_length=100, null=True, blank=True,verbose_name="Salariu") kontratu_inisiu = models.DateField(null=True,blank=True,verbose_name="Hahu Kontratu") kontratu_remata = models.DateField(null=True,blank=True,default="",verbose_name="Kontratu Remata") divizaun = models.ForeignKey(Divizaun, on_delete=models.CASCADE, null=True,related_name="Divizaun",blank=True) departamentu = models.ForeignKey(Departamentu, on_delete=models.CASCADE, null=True,related_name="Departamentu",blank=True) tipu_kontratu = models.CharField(choices=[('Indeterminadu','Indeterminadu'),('Determinadu','Determinadu')],max_length=25,null=True,verbose_name="Tipu Kontratu") status_kontratu = models.BooleanField(default=True) obs_kontratu = models.TextField(max_length=255, null=True, blank=True,verbose_name="Observasaun") def __str__(self): template = '{0.funsionariu}' return template.format(self) class Meta: verbose_name_plural='7-Dadus_Funsionariu_kontratu-Serbisu' views.py def detailtaff(request,id): group = request.user.groups.all().all() data … -
Can't link my css file in my django project
This is a test im trying to do in order to link the file: first is the index.html file ``` `{% load static %} Document This is the Heading ` Second is the Settings file, i connected the css and the templates folders as well: notice! the name of my app is base which is mentioned in the installed apps from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-r*%-wq-%9jiwjznvwf$12m=286o5v_$)a6+1vc*_9hjq%nqh03' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'testpro.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR, 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'testpro.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { … -
Should data in in json file 'structured using li tags?
[ { "model": "db.service", "pk": 1, "fields": { "catagory_name": "New host", "service_name": "<ul><li>Trip planning</li><li>Host shop</li></ul>" } }, { "model": "db.service", "pk": 2, "fields": { "catagory_name": "TOURING HOSTS", "service_name": "Tour of location" } and it has another 5 written like the second activity. This is shown on the front end as a drop down of the activities (service_name). However the tech lead wants me to show trip planning as a bulleted activity, like this **- Trip Planning Host Shop** All as one selection. In the front end code, the previous intern has used regex to seek the li and ul tags and replace them with || for some reason. He wants me to get rod of those which is easy enough, but I was wondering if I should keep the code to seek the tags and somehow make them into bullet points. I have tried replacing the || with & but get &&, I then try replacing && with & but that doesn't work and there are still || in the code, so I tried replaceAll. However this still doesn't get me bullet points. Front end is react. I tried putting the code in brackets with li tags and that didn't … -
Updating my live project to python 3.10 - ERROR python setup.py bdist_wheel did not run successfully
I've been having some trouble when trying to install certain packages on my live version of my project and realized its because its running version 3.7 instead of my up to date version 3.10. When I try to pip install -r requirements.txt I get a number of errors which I'm having no luck in fixing. installing mysql seems to be the reason for these errors appearing. ERROR1: python setup.py bdist_wheel did not run successfully. ERROR2: Running setup.py install for mysqlclient did not run successfully. ERROR3: error: command '/opt/rh/gcc-toolset-9/root/bin/gcc' failed: No such file or directory error: legacy-install-failure -
Django: Template does not exist
Please can you help me understand what I have done wrong here, I am sure it's a very simple problem but, I am new to django and especially the latest version... I believe and as far to my research that I have routed my views to the best of my knowledge, please may you help identify my issue, I am getting an error: "Page Not Found" url.py from my app from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index') ] views from my app from django.shortcuts import render from requests import request # Create your views here. def index(request): return render(request, 'landing_page/index.html') url from my project folder from django.contrib import admin from django.urls import path, include urlpatterns = [ path('/', include('comp.urls')), path('admin/', admin.site.urls), ] urls from my project and then here is my project and template folders, I have attached an image for your ease of helping me: -
Error when adding AUTH_USER_MODEL to settings.py in DJANGO
i'm getting a "simple" trouble when I try to add AUTH_USER_MODEL constant to settings.py. It returns this error, but when I look to INSTALLED_APPS the app name that I'm still working is there. Here it is: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'PMEapp', ] AUTH_USER_MODEL = "PMEapp.User" This is the error: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'PMEapp.User' that has not been installed My installed apps My file system The user model -> It is in models.py These are the things I've tried to solve the problem: 1-Created a User file including all user types in PMEapp folder with user inside didn't work. 2-Moved User file to a folder called User, got the same error. 3-Put all user types in models.py but User(AbstractUser) was still in User.py . Didn't worked too. 4-I've added a User.py file in models folder and imported it to the file that got all the user types. Same error. -
"POST /......... / ......... / HTTP/1.1" 405 0 - Django
I have a problem, in my work I need to insert a system of likes to published posts but by clicking on the button that should give the post a like, nothing happens and this error comes out..."POST /posts/like/ HTTP/ 1.1" 405 0 views.py @ajax_required @require_POST @login_required def post_like(request): post_id = request.POST.get('id') action = request.POST.get('action') if post_id and action: try: post = Post.objects.get(id=post_id) if action == 'like': post.users_likes.add(request.user) else: post.users_likes.remove(request.user) return JsonResponse({'status': 'ok'}) except: pass return JsonResponse({'status': 'error'}) urls.py from django.urls import path, include from . import views app_name = 'posts' urlpatterns = [ path('like/', views.post_like, name='like'), ] index.html {% with total_likes=post.users_likes.count users_likes=post.users_likes.all %} <div class="post-info"> <div> <span class="count"> <span class="total">{{ total_likes }}</span> like{{ total_likes|pluralize }} </span> <a href="#" data-id="{{ post.id }}" data-action="{% if request.user in users_likes %}un{% endif %}like" class="like"> {% if request.user not in users_likes %} Like {% else %} Unlike {% endif %} </a> </div> </div> <div class="post-likes"> {% for user in users_likes %} <div> <p>{{ user.first_name }}</p> </div> {% empty %} <p>No body likes this post yet</p> {% endfor %} </div> {% endwith %} <p>{{ post.id }}</p> <a class="normal-text" href="{{ post.get_absolute_url }}">Discover more...</a> </div> </div> ajax code <script> {% block domready %} $('a.like').click(function(e){ e.preventDefault(); $.post("{% url … -
.distinct() ordering by date not only rows with group by, but group by as well?
Bid.objects.all() gives me two columns with date and bid_value. I want to have only one bid per date. Bid should be the highes value. So Bid.objects.all().order_by("date","bid_value").distinct("date") gives me proper order. But using last not only takes last row from QuerySet, but it takes last element from group_by made from distinct which i dont want. I would want only last element of queryset without any order changes. 1.Bid.objects.all() 2.Bid.objects.all().order_by("date","bid").distinct("date") 3.Bid.objects.all().order_by("date","bid").distinct("date").last() but it should give me 15.11.2022/50zł and actually list(Bid.objects.all().order_by("date","bid").distinct("date").last())[-1] gives me proper object 4.Bid.objects.all().order_by("date","bid").distinct("date").first() How i can still use .last() / .first() - without taking it into list. Because when i use list(Queryset), i have proper values on last objects. But changing queryset to list is not good standard i suppose. -
How to write a Django filter query for multiple values selected from a form without many if statements?
I have several Django forms of which when submitted I store the values like so if the forms are valid with only the min and max price being required, but the other values may be blank or not: max_budget = price_form.cleaned_data['max_price'] #required max_budget = price_form.cleaned_data['max_price'] #required another_value1 = other_form1.cleaned_data['another_value1'] #string another_value2 = other_form1.cleaned_data['another_value2'] #string another_value3 = other_form2.cleaned_data['another_value3'] #string another_value4 = other_form2.cleaned_data['another_value4'] #string another_value5 = other_form3.cleaned_data['another_value5'] #boolen value of 1 if selected another_value6 = other_form3.cleaned_data['another_value6'] #boolen value of 1 if selected I want to query a model (single database table) by using these variable values which correspond to specific fields in that DB as filters. The problem is that currently, I would have to use numerous carefully planned nested if/else statements each containing a variation of the line below to properly filter the DB based on the different possible values or lack thereof. query_results = Model.objects.filter(price__range=(min_budget, max_budget), field_in_the_DB="another_value1", field_in_the_DB="another_value2", field_in_the_DB__icontains="another_value3", field_in_the_DB__icontains="another_value4", field_in_the_DB="another_value5", field_in_the_DB="another_value6").order_by("Another_field_in_the_DB_not_related_these_values") This is because only the min and max prices are required to be entered so something like this would be required. price__range=(min_budget, max_budget) As for the other variables, some may have values or some may be left blank when submitted. Therefore, how can I filter the DB table … -
Code Coverage with Django 4.1 Raising OSError on run
i am using python 3.10.8, django 4.1.4, and coverage 6.5.0. I tried adding the coverage library to my django project to measure the test coverage, I followed the setup process as shown on the Official Django Documentation on testing. Whenever I run the command below, its raises an error. coverage run --source='.' manage.py test myapp myapp name is a dummy name instead of my custom app name Error: OSError: [WinError 127] The specified procedure could not be found Full Traceback is provided here Traceback (most recent call last): File "C:\Users\DUDO\Desktop\projects\salespace inc\app\web\manage.py", line 28, in <module> main() File "C:\Users\DUDO\Desktop\projects\salespace inc\app\web\manage.py", line 24, in main execute_from_command_line(sys.argv) File "C:\Users\DUDO\.virtualenvs\web-15Kcga0E\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\DUDO\.virtualenvs\web-15Kcga0E\lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Users\DUDO\.virtualenvs\web-15Kcga0E\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\DUDO\.virtualenvs\web-15Kcga0E\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\DUDO\.virtualenvs\web-15Kcga0E\lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "C:\Users\DUDO\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\DUDO\.virtualenvs\web-15Kcga0E\lib\site-packages\django\contrib\auth\models.py", line 3, in <module> from … -
Unable to edit an object which has a foreign key in Django
I want to edit an object that has a foreign key in it. The problem that I am facing is that instead of editing the current object it is creating a new one. I think the issue is caused because of foreign key because in models that do not have foreign keys, I am able to edit their objects without any problem. models.py class Room(models.Model): class Meta: ordering = ['room_number'] room_number = models.PositiveSmallIntegerField( validators=[MaxValueValidator(1000), MinValueValidator(1)], primary_key=True ) ROOM_CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ('King', 'King'), ('Queen', 'Queen'), ) category = models.CharField(max_length=9, choices=ROOM_CATEGORIES) ROOM_CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = models.PositiveSmallIntegerField( choices=ROOM_CAPACITY, default=2 ) advance = models.PositiveSmallIntegerField() room_manager = models.CharField(max_length=30) class TimeSlot(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) available_from = models.TimeField() available_till = models.TimeField() views.py def edit_time_slots(request, pk): if pk: try: time_slot_obj = TimeSlot.objects.get(pk=pk) except Exception: return HttpResponse("Bad request.") else: return HttpResponse("Bad request.") if request.method == 'POST': form = AddTimeSlotForm(request.POST, instance=time_slot_obj) if form.is_valid(): try: Room.objects.get(room_number=time_slot_obj.room.room_number, room_manager=request.user.username) except Exception: return HttpResponse("Bad request.") time_slot = TimeSlot(room=time_slot_obj.room, available_from=request.POST['available_from'], available_till=request.POST['available_till']) time_slot.save() # Implemented Post/Redirect/Get. return redirect(f'../../view_time_slots/{time_slot_obj.room.room_number}/') else: context = { 'form': form, 'username': request.user.username } return render(request, 'add_time_slots.html', context) context = { 'form': AddTimeSlotForm(instance=time_slot_obj), 'username': request.user.username } … -
How can I filter and update my Django model with created_at
I have two models class Records(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) Approved = models.BooleanField(default=False) Date = models.DateTimeField(default=datetime.now, blank=True) class Request(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) Approved = models.BooleanField(default=False) Date = models.DateTimeField(default=datetime.now, blank=True) I want cron to update Record every 1 minutes if Approved in Request is True I tried this... def deposit(): if Deposit_Request.objects.exists(): check=Deposit_Request.objects.get() with transaction.atomic(): if check.Approved == True: Deposit_Records.objects.filter(user=check.user, Date=check.Date).update(Approved=True) Deposit_Request.objects.get().delete() I dont understand why this logic wont work when this two model object was created at the same time and even when i confirm the datetime, the date, minute and second is the same. -
i was trying to make a virtualenv for python django project ,at that time this error came
ERROR:root:failed to read config file C:\Users\heman\AppData\Local\pypa\virtualenv\virtualenv.ini because FileNotFoundError(2, 'No such file or directory') ERROR:root:AttributeError: 'IniConfig' object has no attribute 'has_virtualenv_section' The system cannot find the path specified. The system cannot find the path specified. The system cannot find the path specified. how to solve this is there any commant for that to fix it using terminal -
How To Dynamically Create Elements in JavaScript
I am struggling to dynamically create tags for each Subheading (h2 element) I have in my blog, and then fill those tags with the text of the Subheading. This is what I have tried so far: <script> const subheadings = document.querySelectorAll("h2"); subheadings.forEach(function(x) { document.getElementById("contents").innerHTML=x; <a href='#' id="contents"></a> }); </script> This resulted in nothing appearing. Any help or advice in which direction to look is greatly appreciated. -
Django database (PostgreSQL) test setup and teardown for user groups not working
In setup I have: new_group, created = Group.objects.get_or_create(name='Sales Manager') SALES_MANAGER = 1 new_group, created = Group.objects.get_or_create(name='Team') TEAM = 2 There a five of these groups. I then use the these variables like this: user.groups.add(TEAM) In the teardown of with: Group.objects.get(name='Team').delete() The first build the test database works fine, but the second produces empty group sets for all my users. I tried not deleting the groups in the teardown, but that made now difference. -
Should I use Node.js or Django for my application?
I'm planing to build a cross-platform app as my first big project. I'm not yet familiar with any of the former frameworks, but I am looking forward to learning them. So far I am familiar with C, C++ and Python. The app will function as following: User uploads a photo, from which text is extracted and stored in associated file (I want to process images on front end, because I can't afford to process everything on the back end) Data is sent to the back end where it is stored With machine learning, data is being analyzed and organized into new groups (in the future I also want to add some AI to find answers to questions posed in the written text on the image) User can access reorganized groups, answers, his profile... So basically I want to do heavy processing on front end; organize everything, enhance data and store profiles/images on back end; implement a smart organization system; be able to access everything again on front end in a package as addictive as Instagram. I know I can easily implement OpenCV and make machine learning algorithms in Python, but I don't know how to make that on front end; … -
Python library to use
I need fill the web application form so which library should I use in Python that help to automate the form filling of website. Python library to used for auto form filling . -
how to reset id whenever a row deleted in django?
i wanted to start id from 1 . whenever a row deleted it skips that number and jump to next number. like in this image it skips number from 1-6 and 8. i want to set it as 1,2,3 this is my models.py class dish(models.Model): id = models.AutoField(primary_key=True) dish_id = models.AutoField dish_name = models.CharField(max_length=255, blank=True, null=True) dish_category = models.CharField(max_length=255, blank=True, null=True) dish_size = models.CharField(max_length=7, blank=True, null=True) dish_price = models.IntegerField(blank=True, null=True) dish_description = models.CharField(max_length=255, blank=True, null=True) # dish_image = models.ImageField(upload_to="images/", default=None, blank=True, null=True) dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) #here added images as a foldername to upload to. dish_date = models.DateField() def __str__(self): return self.dish_name this is views.py def delete(request, id): dishs = dish.objects.get(id=id) dishs.delete() return HttpResponseRedirect(reverse('check')) -
Django toggle yes and no
I am having difficulty creating a toggle for Django. This Django is a Chores table listed from the description, category, and is_complete. The is_complete is what I am having trouble with. The toggle should be a href that when you click "yes" it will change to "no" Model.py class ChoresCategory(models.Model): category = models.CharField(max_length=128) def __str__(self): return self.category class Chores(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.CharField(max_length=128) category = models.ForeignKey(TaskCategory, on_delete=models.CASCADE) is_completed = models.BooleanField(default=False) I tried creating a view.py def toggle(request): -
Django channels consumer not receiving data
I'm trying to write a websocket consumer that gets all unread notifications as well as all notifications being created while the client is still connected to the websocket. I'm able to connect to the consumer and it's showing me all active notifications. The problem is that it doesn't show me new notifications when they're being created and sent from the model's save method. consumers.py class NotificationConsumer(WebsocketConsumer): def get_notifications(self, user): new_followers = NotificationSerializer(Notification.objects.filter(content=1), many=True) notifs = { "new_followers": new_followers.data } return { "count": sum(len(notif) for notif in notifs.values()), "notifs": notifs } def connect(self): user = self.scope["user"] if user: self.channel_name = user.username self.room_group_name = 'notification_%s' % self.channel_name notification = self.get_notifications(self.scope["user"]) print("Notification", notification) self.accept() return self.send(text_data=json.dumps(notification)) self.disconnect(401) async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) count = text_data_json['count'] notification_type = text_data_json['notification_type'] notification = text_data_json['notification'] print(text_data_json) await self.channel_layer.group_send( self.room_group_name, { "type": "receive", "count": count, "notification_type": notification_type, "notification": notification } ) models.py class Notification(models.Model): content = models.CharField(max_length=200, choices=NOTIFICATION_CHOICES, default=1) additional_info = models.CharField(max_length=100, blank=True) seen = models.BooleanField(default=False) users_notified = models.ManyToManyField("core.User", blank=True) user_signaling = models.ForeignKey("core.User", on_delete=models.CASCADE, related_name="user_signaling") def save(self, *args, **kwargs): if self._state.adding: super(Notification, self).save(*args, **kwargs) else: notif = Notification.objects.filter(seen=False) data = { "type": "receive", "count": len(notif), "notification_type": self.content, … -
instance in Django not working properly unable to get pre populate data
i am trying to populate the fileds in django automatically using the instance but its not working for me so someone help to solve this issue so here is the code def Editquestion(request): askit = askm.objects.get(question = "apple") print(askit) getformdata = editquestf(instance = askit) return render(request, "editquestpage.html", {'edit':getformdata}) -
Django filter queryset
Django framework has a product model with about ten values that need to be filtered (color, type..). I'm trying to create a filter like this: views: ` class FilterCctvView(QuerySetsFromCctv, ListView): paginate_by = 32 def get_queryset(self): queryset = Cam.objects.filter( Q(maker__in = self.request.GET.getlist("maker")) | Q(type_of_cam__in = self.request.GET.getlist("type_of_cam")) ) return queryset in html: <form action="{% url 'filter' %}" method = 'GET'> <ul> <p><strong>Manufacturers</strong></p> {% for cam in view.get_cctv_makers %} <li> <input type="checkbox" class="checked" name="maker" value="{{cam.maker}}"> <span>{{cam.maker}}</span> </li> {% endfor %} </ul> <ul> <p><strong>Type of cameras</strong></p> {% for cam in view.get_cctv_type %} <li> <input type="checkbox" class="checked" name="type_of_cam" value="{{cam.type_of_cam}}"> <span>{{ cam.type_of_cam}}</span> </li> {% endfor %} </ul> <button class="btn btn-success btn-sm" type="submit">Find</button> </form> ` enter image description here But the filter doesn't work correctly! How do I do this correctly?