Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
form.is_valid() not working as intended django
I am neew to django and I am trying to make an attendance system where the user can type their name and press clock in or clock out but when I test the code. But whenever I type a name and press clock In it does not save the name and time to the database. views.py: def home(response): form = CreateNewList() empName = employeeName.objects.all if response.method == "POST": form = CreateNewList(response.POST) if 'clockIn' in response.POST: if form.is_valid(): n = form.cleaned_data["name"] now = datetime.now() current_time = now.strftime("%H:%M:%S") t = Name(name = n, timeIn=current_time) t.save() return redirect('/') else: form = CreateNewList() return render(response, "main/home.html", context={"form":form, "empName":empName}) models.py: class employeeName(models.Model): employee = models.CharField(max_length=200) total_Hours_Worked = models.CharField(max_length=8, default="Empty") def __str__(self): return self.employee class Name(models.Model): name = models.ForeignKey(employeeName, null=True,on_delete=models.CASCADE) timeIn = models.TimeField() timeOut = models.TimeField(default=datetime.now()) date = models.DateField(auto_now=True) def __str__(self): return str(self.name) forms.py: class CreateNewList(forms.ModelForm): def __init__(self, *args, **kwargs): super(CreateNewList, self).__init__(*args, **kwargs) self.fields['name'].widget = TextInput() class Meta: model = Name fields = ['name'] home.html: <label>Enter Your Full Name:</label> {{form.name}} <datalist id="attendance"> {% for empName in empName %} <option value="{{empName.employee}}"> {% endfor %} </datalist> <button type="submit" name="clockIn" value="clockIn" class="btn btn-outline-primary">Clock In</button> I tried testing whenever I press the clockIn button to print something in the terminal … -
Django project run manage.py results in no module named django
I was working on a django project served as a backend for a small personal site, the built-in localhost server by django runs smoothly until I accidentally removed the app execution alias of python in windows 10(It just happened after done that, might not be the culprit). the situation is that when I use manage.py, it always results in a no module named "django" (venv) C:\Users\hongl\PycharmProjects\fluentdesign>manage.py runserver Traceback (most recent call last): File "C:\Users\hongl\PycharmProjects\fluentdesign\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\hongl\PycharmProjects\fluentdesign\manage.py", line 22, in <module> main() File "C:\Users\hongl\PycharmProjects\fluentdesign\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHO NPATH environment variable? Did you forget to activate a virtual environment? I tried to resolve it a bit and was only baffled to find the terminal, with which the venv had already been activated, was always being attached to the system-wise python when running which has no django installed in it. The following is python console from venv: (venv) C:\Users\hongl\PycharmProjects\fluentdesign>python Python 3.8.9 (tags/v3.8.9:a743f81, Apr 6 2021, 14:02:34) [MSC … -
How to avoid n+1 queries in Django when you are not able to use select_related?
This is a problem I encounter quite often. Lets say I have three models: class CourseType(models.Model): name = models.CharField(max_length=50) class CourseLevel(models.Model): name = models.CharField(max_length=50) course_type = models.ForeignKey(CourseType, on_delete=models.CASCADE) class Course(models.Model): name = models.CharField(max_length=50) course_level = models.ForeignKey(CourseLevel, on_delete=models.CASCADE) def __str__(self): return "{}-{}: {}".format(self.course_level.course_type.name, self.course_level.name, self.name) If I were to iterate over Course.objects.all() and print the Course objects, that would be a n+1 query. This is easily solved by using select_related: Course.objects.select_related('course_level', 'course_level__course_type') The problem with this is I have to remember to use select_related every time. Its also ugly, especially if you have another model in there, like CourseDetails. One solution to this is to use a custom manager: class CourseManager(models.Manager): def with_names(self): return self.select_related('course_level', 'course_level__course_type') I can then use Course.with_names.all() and no longer need to add in the select_related every time. This has a major limitation - I can only take advantage of the manager when directly using Course. Very often I will iterate over Course objects through foreign keys, and again I will need to remember to use select_related and litter it all over my code. An example: class Student(models.Model): name = models.CharField(max_length=50) class StudentCourseEnroll(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) Now if I want to print … -
Django project Page not Found
I am trying the basic Django tutorial: https://docs.djangoproject.com/en/3.1/intro/tutorial01/ The admin page is up and running but getting a 404 on the http://localhost:8000/polls/ page: I cannot understand what this code is doing: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls) ] I didn't define any polls.urls, so how will it know how to route the request? Total beginner here. Coming from the old Tomcat/JBoss world. -
IntegrityError while I am programmatically committing user to database - Django
In Django I am trying to create a log-in view that would accept a default username and default password. This would allow the log-in view to just accept the username 'test' and password 'test', this would allow the user to be authenticated without registration. The problem I am running into is utilizing create_user(). I have tried to create the variable default_user = User.objects.create_user(username = 'test', password = 'test') This just gives me an IntegrityError. I have tried to create code to handle the IntegrityError in a try/except block but continue to bump my head against the wall. Any help is appreciated. Thanks. views.py def index(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(request, username = cd['username'], password = cd['password']) if user is not None: if user.is_active: login(request, user) return HttpResponse('Authenticated '\ 'successfully') else: return HttpResponse('disabled account') else: return HttpResponse('Invalid Login') else: form = LoginForm() return render(request, 'server/index.html', {'form': form}) -
Django not sending data back to javascript fetch
I wrote this simple fetch post: document.querySelector('#retardo').addEventListener('click', function (e) { e.preventDefault(); let info = JSON.stringify({ retotitulo: document.querySelector('#retotitulo').value, retodescripcion: document.querySelector('#retodescripcion').value, retoprecio: document.querySelector('#retoprecio').value, }) let formData = new FormData(); formData.append('info', info); fetch(`http://127.0.0.1:8000/reto/crear`, { method: 'POST', body: formData, headers: { "X-CSRFToken": getCookie('csrftoken') } }) .then(response => response.json()) .then(result => { console.log(result) }) }) And this is how i manage the data from the server: def retocrear(request): if request.method == "POST": jsoninfo = json.loads(request.POST['info']) retotitulo = jsoninfo['retotitulo'] retodescripcion = jsoninfo['retodescripcion'] retoprecio = jsoninfo['retoprecio'] print(retotitulo) print(retodescripcion) print(retoprecio) return JsonResponse(jsoninfo) What works? The data is successfully sent to the server and I can see the variables printed on my terminal, also e.preventDefault(); works fine. What doesnt work? .then(result => {console.log(result)}) This line of code is not working. When I check my js console, nothing gets printed. Any idea why? Thank you in advance -
add confirm to change email for user using usercreationform - django
i have option that allow user to change email in his profile but without confirm new email so when he enter new email i want activate email to save it in his profile , how to add confirm my code | forms.py : # Profile Form class EmailChangeForm(forms.ModelForm): email = forms.EmailField(required=True,label='Email',widget=forms.EmailInput(attrs={'class': 'form-control center container','style': 'width:85%;text-align: center;background-color:#f6f6f6','placeholder':' Enter Your New E-mail '}) ) class Meta: model = User fields = [ 'email', ] def clean_email(self): email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).count(): raise forms.ValidationError('Email is already in use, please check the email or use another email') return email views.py : # Edit Profile View class EmailChange(UpdateView): model = User form_class = EmailChangeForm success_url = reverse_lazy('home') template_name = 'user/commons/EmailChange.html' def get_object(self, queryset=None): return self.request.user urls.py : from django.urls import path from blog_app.views import SignUpView, ProfileView, ActivateAccount,EmailChange urlpatterns = [ path('profile/change-email/me/', EmailChange.as_view(), name='emailchange'), ] html page : <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="fadeIn fourth" style="background-color:#7952b3" value=" change "> </form> what is the next step will be to add activation when user enter new email ? -
Webpack Error: Can't resolve style-loader from my webpack.config.js
I created a django project with django apps, one of which contains React. I am basically capturing the data in a Django Rest API then sending data to my REact and thus rendering "dynamic" views. But, when I try to style my react or do pretty much anything except use Javascript, I run into an error. The error I have right now is after installing the css loader for webpack via the documentation page: https://www.npmjs.com/package/css-loader, the error says: ERROR in ./src/index.js 3:0-21 Module not found: Error: Can't resolve 'style-loader' in 'C:\Users\andrew.bregman\Documents\AppDev\django-react\django_react\frontend' Here is my webpack.config.js: module.exports = { module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } }, { test: /\.css$/i, use: ["style-loader", "css-loader"], }, ] } }; Please let me know what other files you would like. Thanks in advance! -
how to push docker compose to AWS ECR and make it work on AWS Fargate
I have the following docker-compose file configuration, which is a mix of django (DRF) backend and react frontend, using postgresql as database. docker-compose.yml version: "3.7" services: backend: build: ./backend stdin_open: true tty: true restart: "on-failure" env_file: .env volumes: - ./backend:/backend - ./backend/static:/backend/static ports: - 8000:8000 depends_on: - db db: image: postgres:11 restart: "on-failure" environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - postgres_data:/var/lib/postgresql/data/ frontend: build: ./frontend restart: "on-failure" command: yarn start volumes: - ./frontend:/frontend ports: - 3000:3000 depends_on: - backend volumes: postgres_data: When I do docker images, I do have the 3 images below: I am a bit lost on how exactly to push the three images below as a single image (if it is possible or the right way to approach docker compose) to AWS ECR because normally you can only push 1 image at the time after creating a ECR repository in AWS. drf_react_frontend latest 32d2u1db5e21 21 minutes ago 605MB drf_react_backend latest fe9c48895844 21 minutes ago 962MB postgres 11 24cb8b5cb381 2 days ago 282MB My ultimate goal is to have react on port 3000 work and django on 8000 on aws fargate under a single domain (for now i believe i can use a load balancer) but just … -
Django respond to a search result in a database from navbar
I'm working on a django app that has a database with various posts. These posts have names and ids. The ids are in sub urls like sitename.com/1. On every page of the django app, I have a navbar which was extended from base.html. The navbar has a search bar which is really a form submission. When I want to execute a search, I can take in the search data and use filters on it with the given database. However, the views.py has a function for each sub url. With each sub url that has a form on it, the function on views.py is handling the post request for the form. How am I going to handle the requests from the search bar form? Do I have to make a function that handles it and then copy paste a call for that function at the beginning of the functions for every other page I want to make? Is there an easier way to do this? I've heard of using @ but I don't know if that is the right use for this sort of problem. -
django gunicorn stuck while sending file
i used django, docker, nginx and gunicorn if I tried on development mode (run on my local) it working fine while my server sending PDF ( still downloading ) I still can call another API but on my docker, it's like a single worker, when the server sending a file, and we call another API, the server stuck waiting to send PDF done first. I already set the worker 9 and thread 2 but still have the same problem. this is my docker-compose version: '3' services: web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn --workers=9 --threads=2 server.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles expose: - 8000 env_file: - ./app/config/.env nginx: build: ./nginx volumes: - static_volume:/home/app/web/staticfiles ports: - 80:80 depends_on: - web volumes: static_volume: my views try: test_file = open(pdf_path, 'rb') response = HttpResponse(content=test_file) response['Content-Type'] = 'application/pdf' response['Content-Disposition'] = 'attachment; filename="flp_{}.pdf"'.format(email_phone) print("send pdf") return response except FileNotFoundError: print("send pdf exception file not found") raise Http404() -
how do I properly build a mass insert data using bulk functions in django?
I am trying to build a upsert function where it handle the mass insert data from my crawling system , but I am having some issues where m2m fields cant be directly inserted such as [data.data1,data2] or via ids [1,2,3] since it causes slicing error on django , how can I properly build a import data based on a multiple models on m2m ? class ThingA(models.Model): [..] class ThingB(models.Model): [...] thing_a = models.ForeignKey(ThingA, on_delete=models.CASCADE) class ThingC(models.Model): [..] class ThingD(models.Model): [..] class ThingE(models.Model): [..] thing_a = models.ManyToManyField(ThingA) thing_b = models.ManyToManyField(ThingC) thing_c = models.ManyToManyField(ThingD) [..] def import_data(self, **data): instances = [ ThingE( thing_a=?? thing_b=?? thing_c=?? ) for datas in data ] print(instances) data = { [..] 'thing_a': thing_a, 'thing_b': thing_b, 'thing_c': thing_c } self.import_data(**data) -
Django user management, filteration for ungroupped users
I'm using Django's default admin page for user management. Each user has a "department" field. On the filtration sidebar, users without a department could be accessed through that dash at the bottom of the list. the filteration list Now what we want is instead of creating a new "Unassigned" department and move those people in, is there any way to change that "-" to something else. We are now lack of keywords to google this case, so any keywords, concepts or solution are appreciated. Thanks. -
Django select2 no results found when I try to implement dependent fields
I am trying to implement dependent select fields as shown here . My models are shown here: class VehicleBrand(BaseModel): """Brands for types of vehicles""" name = models.CharField(_('Name'), max_length=50) def __str__(self): return self.name class VehicleModel(BaseModel): """vehicle model""" brand = models.ForeignKey( 'awesomeinventory.VehicleBrand', verbose_name=_('Brand of the vehicle'), on_delete=models.CASCADE, related_name='models', ) name = models.CharField(_("Vehicle model name"), max_length=50) def __str__(self): return self.name My forms.py looks like: class MarketTrackForm(forms.Form): brand = forms.ModelChoiceField( queryset=VehicleBrand.objects.all(), to_field_name='name', label=u'Brand', widget=ModelSelect2Widget( model=VehicleBrand, search_fields=['name__icontains'], attrs={'style': 'width: 100%', 'data-minimum-input-length': 0}, ), ) model = forms.ModelChoiceField( queryset=VehicleModel.objects.all(), to_field_name='name', label=u'Model', widget=ModelSelect2Widget( model=VehicleModel, search_fields=['name__icontains'], dependent_fields={'brand': 'brand'}, max_results=500, attrs={ 'style': 'width: 100%', 'data-minimum-input-length': 0, }, ), ) my urls.py urlpatterns += i18n_patterns( ... path('select2/', include('django_select2.urls')), ... ) and my settings looks like ... CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, }, 'select2': { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/2", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, }, } # Set the cache backend to select2 SELECT2_CACHE_BACKEND = 'select2' ... When I remove dependent fields everything works. Also I tried to copy exact example shown in documentation (country and city models) and even that didn't work. when I add dependent field, it just starts to say no results found(after selecting dependent field), If I remove … -
Django: listing category in the navigation bar
So, I'm working on this blog website with Django, and I will like to list all the category I have to the dropdown, which I will be able click them and will take me to the category detail page. but I don't have any idea to implement this. because I created navbar.html and included it in the base.html, so I don't know which view to create to handle it base.html {% load static %} <!DOCTYPE html> <html lang="en"> {% include 'head.html' %} <body> {% include 'navbar.html' %} {% block content %} {% endblock content %} {% include 'footer.html' %} {% include 'script.html' %} </body> </html> navbar.html {% load static %} <header class="header"> <!-- Main Navbar--> <nav class="navbar navbar-expand-lg fixed-top"> <div class="search-area"> <div class="search-area-inner d-flex align-items-center justify-content-center"> <div class="close-btn"><i class="icon-close"></i></div> <div class="row d-flex justify-content-center"> <div class="col-md-8"> <form action="{% url 'search' %}"> <div class="form-group"> <input type="search" name="q" id="search" placeholder="What are you looking for?"> <button type="submit" class="submit"><i class="icon-search-1"></i></button> </div> </form> </div> </div> </div> </div> <div class="container"> <!-- Navbar Brand --> <div class="navbar-header d-flex align-items-center justify-content-between"> <!-- Navbar Brand --><a href="{% url 'home' %}" class="navbar-brand lead">korexIT</a> <!-- Toggle Button--> <button type="button" data-toggle="collapse" data-target="#navbarcollapse" aria-controls="navbarcollapse" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler"><span></span><span></span><span></span></button> </div> <!-- Navbar Menu --> <div … -
Django filter __in keep order and duplicates
Let's say I have a list items = [1,2,5,1,2,1] What I'm trying to achieve is to get all Example objects in a list and keep order and duplicates. Like following: def get_all_keep_order_and_duplicates(): return [Example.objects.get(pk=pk) for pk in items] My question is that is there a way to do this more efficiently, having a single query instead of getting each item individually? So far I have tried following which keeps the order but doesn't return duplicates: def get_all_keep_order(): return Example.objects.filter(pk__in=items).order_by( Case(*[When(pk=pk, then=count) for count, pk in enumerate(items)]) ) -
Docker. Docker-Compose. Server does not support SSL, but SSL was required
I'm kind of new to Docker. So, the project worked correctly, then I updated my ubuntu to 18.04. And now docker-compose up gives me this error: django.db.utils.OperationalError: server does not support SSL, but SSL was required Not sure what to try. Any advice will help. -
Django can't find my template directory inside my view?
I'm trying to use an HTML template for django mail module. MY current issue is that I'm getting this error: django.template.exceptions.TemplateDoesNotExist when I try to render HTML inside my app called users: html = render_to_string('email/email_confirm.html', context) Here is my folder layout, my app is called users, my project settings live in /core. My templates are located in BASE_DIR. Here is my templates code in settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(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', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] How can I get Django to properly find the templates folder? I have all my apps hooked up and data is working fine. This is strictly a templates path issue. -
Trying to add a form to a DetailView
I am writing a Detail View - and the form that is displayed is the particular Track that the user is adding/updating to the CD Entry (It's a CD Library application). The trick is I want to see everything else about the CD on the page as well as the form for the particular track. Having trouble figuring out how to get the form to be just the trac I am adding/updating. Basically you can enter a CD Title,Artist, and total time of the CD into the CD model. Then the Tracks are stored in the Track Model, with their Foreign Key being the CD they are on. While looking at a Detail View of the CD, the user can add or update a Particular track via a button. I'm trying to get the update part working. Model Looks like this: from django.db import models from datetime import datetime, timedelta class Cd(models.Model): artist_name = models.CharField(max_length=155) cd_title = models.CharField(max_length=155) cd_total_time = models.TimeField(default="00:00:00") cd_total_time_delta = models.DurationField(default=timedelta) cd_run_time = models.TimeField(default="00:00:00",blank=True) cd_run_time_delta = models.DurationField(default=timedelta) cd_remaining_time = models.TimeField(default="00:00:00",blank=True) cd_remaining_time_delta = models.DurationField(default=timedelta) def save(self, *args, **kwargs): super().save(*args,**kwargs) def __str__(self): return f"{self.artist_name} : {self.cd_title}" class Track(models.Model): cd_id = models.ForeignKey(Cd, on_delete=models.CASCADE, related_name='cd_tracks', ) track_title = models.CharField(max_length=50) track_number = … -
Return all the orderitems in an order of a customer Django
I want to return all the items in all the orders that have made a customer. I don't know if it is possible or how I need to do it, I tried to get the orders with .get and .filter in my views but with get is only possible to return one value My models.py class Customer(models.Model): user = models.OneToOneField(Account, on_delete=models.CASCADE, null=True) first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True, blank=True) phone = models.CharField(max_length=10, null=True, blank=True) email = models.EmailField(null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.user) class Category(models.Model): name = models.CharField(max_length=200, null=True) class Meta: verbose_name='categoria' verbose_name_plural ='categorias' def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True) description = models.TextField(max_length=500, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) ventas = models.IntegerField(null=True, blank=True, default=0) image = models.ImageField(null=True, blank=True, default='Banner_Cubrebocas.png') def __str__(self): return self.name class Order(models.Model): STATUS= ( ('Pending', 'Pending'), ('Delivered', 'Delivered') ) customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) #product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True) date_created =models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS, default='Pending') complete = models.BooleanField(default=False, null=True, blank=True) def __str__(self): return str(self.id) @property def shipping(self): shipping= False orderitems=self.orderitem_set.all() for i in orderitems: if i.product.digital == False: shipping=True return shipping @property def get_cart_total(self): orderitems= … -
Django - Query with multiple bool colums count true
I have a model with 100+ fields and all are bool values (true/false). How do I query this model and count the number of true values? Using django-aggregate-if is probably the closes I've come to an answer but it still requires using the field name. I'd like to avoid using the field name since there are so many fields. Everything I have tried has 1 thing in common...I can't seem to iterate over the query set without using the field name. I have also tried placing a count variable in the form to increase as form values are grabbed from the post request and sending the query set to another function to count. Essentially I am looking for something that will iterate over the query set and count true values regardless of the field name. -
How to perform arithmetic operations on fields of model class in django?
I have two models 'Client' and 'Installment'. my models.py is given below: models.py from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User # Create your models here. class Client(models.Model): name = models.CharField(max_length = 100) dob = models.SlugField(max_length = 100) CNIC = models.SlugField(max_length = 100) property_type = models.CharField(max_length = 100) total_price = models.IntegerField() down_payment = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) consultant = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('client_details',kwargs={ 'pk' : self.pk}) class Installment(models.Model): client = models.ForeignKey(Client, null=True, on_delete=models.CASCADE) installment_month = models.CharField(max_length = 100) installment_amount = models.IntegerField() installment_date = models.DateTimeField(default=timezone.now) balance = models.IntegerField(default='0') # Calcuting balance def calculate_balance(self): balance = (self.client.total_price - self.client.down_payment) - self.installment_amount return balance # Saving balance def save(self,*args, **kwargs): self.balance = self.calculate_balance() super().save(*args, **kwargs) def __str__(self): return self.installment_month def get_absolute_url(self): return reverse('installment_confirmation') As you can see above, there is one field balancein Installment model, that is being calculated using two fields total_price and down_payment of Client model in the function called calculate_balance what I want to do is, calculate the balance every time the new installment is added. for example: when first client is created the total_price is 300000, and the down_paymentis 50000. Now, when new Installment is … -
How can I remove a particular item using a popup?
I have many items and I want to delete one of them but when I delete one item it turns out that it deletes the last item which exists based on ordering so, if I have 10 records of id which start from 1 to 10 record so, it will remove the item number 10 til if I remove item number 5 will remove the number 10. this case occurs because of popup but if I remove popup and delete the items directly it will remove with no mistake so, How can I remove a particular item using popup? profile.html {% if request.user == profile.user %} <div class="col-lg-7 offset-lg-1 col-12"> {% if profile.user.user_history.all.count != 0 %} <form method="post"> {% csrf_token %} <div class="clear_all fl-left"> <input class="global_checkbox" type="checkbox" name="remove_all_history" id="remove_all_history"> <label for="remove_all_history" class="ml">Remove All</label> </div> <div class="fl-right"> <input type="submit" value="Remove" class="clear_button btn btn-danger invisible"/> </div> </form> {% else %} <p class="text-center">you have no history yet!</p> {% endif %} <div class="clearfix"></div> <div class="mt-6"></div> {% for history in history_pages %} {% if history.deleted_history == False %} <div class="history"> <div class="row"> <div class="col-4"> <form method="post"> {% csrf_token %} <input class="global_checkbox" type="checkbox" name="remove_one_history" id="remove_all_history"> <span class="ml-2">{{ history.history_time|time }}</span> <div class="ml ml-4">{{ history.history_time|date:'d M Y' }}</div> … -
Django emptying display value after submitting form
I want my fields to show no value after submitting my django form, but I can't seem to find a way on how to do this. I think I just need to add something to my html, but just can't find out what exactly. Below is my html. <form method="post"> {% csrf_token %} <div>{{ form.ervaring|as_crispy_field }}</div> <div class="form-row"> <div class="form-group col-md">{{ form.startjaar|as_crispy_field }}</div> <div class="form-group col-md">{{ form.eindjaar|as_crispy_field }}</div> </div> <div>{{ form.functie|as_crispy_field }}</div> <div>{{ form.beschrijving|as_crispy_field }}</div> <div> <a class="btn btn-primary" href="{% url 'my_cv' %}">Done</a> <button class="btn btn-primary" type="submit">Add</button> </div> </form> -
How do you count the total number of objects in query set, and display the total number in a CreateView generic view?
I need to know how to print the total number of objects in a query set for my CreateView generic view. I don't know how to connect a variable or something so I can process the information onto my template. CreateView class in views.py: class CreateView(CreateView): model = Blog fields = ['author', 'title', 'category', 'article'] success_url = reverse_lazy('home') template_name = 'blog/create.html' Here is my template: templates/blog/create.html {% extends 'blog/main.html' %} {% block content %} {% include 'blog/navbar.html' %} <div class="row"> <div class="card-body"> <form method="POST"> <a style="margin-bottom: 10px;" class="btn btn-info" href="{% url 'home' %}">&#8592; Go back</a> <br /> {% csrf_token %} <label>{{ form.author.label }}:</label> <br /> {{ form.author}} <br /> <label>{{ form.title.label }}:</label> <br /> {{ form.title }} <br /> <label>{{ form.category.label }}:</label> <br /> {{ form.category }} <br /> <label>{{ form.article.label }}:</label> <br /> {{ form.article }} <br /> <input class="btn btn-info" type="submit" value="Create" /> </form> </div> <div class="info"> <div class="col-sm-6"> <div class="card"> <div class="card-body"> <h5 class="card-title">Current number of blogs</h5> <p class="card-text">{{ ** I want total number of objects in here** }}</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> <div class="col-sm-6"> <div class="card"> <div class="card-body"> <h5 class="card-title">Special title treatment</h5> <p class="card-text">With supporting text below as a natural lead-in to …