Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Request always returns get Django
I can't post my django form. Request always returns get. Can you help me form, model, view, template aşağıda belirtiğim gibi. Post request is not detected when I fill out and submit the form. It doesn't even enter the is valid part anyway. I made the POST post and wrote the url in the action ="". I tried it as a model form. I checked the divs but no result no matter what I did view.py if request.method =="POST": print('send1') form = ContactForm(request.POST) if form.is_valid(): print('send1.1') print('send1') subject = request.POST['subject'] name = request.POST['name'] company_name = request.POST['company_name'] title = request.Post['title'] email_address = request.POST['email_address'] phone = request.POST['phone'] city_country = request.POST['city_country'] message = request.POST['message'] form.save() value = "İsim ve Soyisim : {0}\nŞirket İsmi : {1}\nÜnvanı ve Departmanı : {2}\n" \ "Mail adresi : {3}\nTelefonu : {4}\nŞehir ve Ülkesi : {5}\nMesajı : {6}\n"\ .format(name,company_name,title,email_address,phone,city_country,message) send_mail(subject, message=value, from_email="utku.mutlu@adatech.com.tr", recipient_list=['utku.mutlu@adatech.com.tr']) print('send2') print(form.data) return redirect('offer-request') else: form = ContactForm() print("send3") print(form.data) context = {'contexts':OfferRequest.objects.first(),'form':form} return render(request, "offer.html", context) template.html {% if form %} <form id="form" class="modular-form modular-form--black" method="POST" action=""> {% csrf_token %} <div class="modular-form__pages "> <div class="modular-form__page modular-form__page--active " data-page-number="1 "> <div class="modular-form__field form-text "> {{form}} </div> </div> <div class="form-footer__action "> </div> </div> </form> {% endif %} -
Render pdf locally
I don't have an access to S3 project bucket and I would like to save html file or pdf(will be better) in my local machine, instead of S3 storage. When I'm generating pdf I'm catching ValidationError I have this function for rendering pdf file, any ideas how I can edit this and save it locally? def _render_pdf(storage, context, language_code, filename, template_path): tmp_html_file = tmp_pdf_file = None try: with tempfile.NamedTemporaryFile( delete=False, suffix='.html' ) as tmp_html_file: with translation.override(language_code): tmp_html_file.write( str( render_to_string( template_path, context ) ).encode('utf-8') ) tmp_pdf_file = tempfile.NamedTemporaryFile( delete=False, suffix='.pdf' ) i = 0 while i < settings.WKHTMLTOPDF_BINARY_RETRIES and os.path.getsize(tmp_pdf_file.name) == 0: i += 1 generate_pdf_file(tmp_html_file.name, tmp_pdf_file.name) if os.path.getsize(tmp_pdf_file.name) == 0: raise ValidationError(u'Pdf file is empty: {}'.format(tmp_pdf_file), u'empty_pdf_file') storage.save(filename, tmp_pdf_file) finally: if tmp_html_file is not None: os.unlink(tmp_html_file.name) if tmp_pdf_file is not None: tmp_pdf_file.close() os.unlink(tmp_pdf_file.name) -
Page not found (404) Using the URLconf defined in shop.urls, Django tried these URL patterns, in this order:
Error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:9000/accounts/profile/ Using the URLconf defined in shop.urls, Django tried these URL patterns, in this order: admin/ products/ The current path, accounts/profile/, didn’t match any of these. shop is my project products is my app... After Login my page redirect to another location... i want another page in (products/templates/index.html) to shown after login.. how i do that products/urls.py from django.contrib.auth import views as auth_views path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'), in views.py i have no function called login login.html <h1>login page</h1> <form class="login-form" method="POST"> {% csrf_token %} <div class="row"> <div class="col-lg-12"> <div class="form-group position-relative"> <label>Username <span class="text-danger">*</span></label> {{form.username}} </div> </div> <div class="col-lg-12"> <div class="form-group position-relative"> <label>Password <span class="text-danger">*</span></label> {{form.password}} </div> </div> <div class="col-lg-12 mb-0"> <a href="{% url 'index' %}"><button class="btn btn-primary w-100" type="submit">Login</button></a> </div> <div class="col-12 text-center"> <p class="mb-0 mt-3"><small class="text-dark mr-2">Don't have an account ?</small> <a href="{% url 'register' %}" class="text-dark font-weight-bold">Sign Up</a></p> </div> </div> </form> -
Django: how do you prefetch recursive fields?
class Item(models.Model): # ... required_items = models.ManyToManyField("self", symmetrical=False, blank=True) Since it's a M2M relation, I can't use select_related to optimise my query, so I have to use prefetch_related. But I don't undertstand why I can't chose the depth of recursion, like I would with select_related and the depth parameter. For example, to select 3 levels of recursion, I would expect some syntax like this to work (it doesn't): Item.objects.prefetch_related("required_items", depth=3). But instead, what I'm currently doing and is obviously awful is: Item.objects.prefetch_related("required_items__required_items__required_items") I think I don't get it at some point... -
Signal attached to 3rd party library model not being triggered
I've have got a usecase in which I have a model named "Content" which inherits from a 3rd party library I've installed as a pip package known as "django-mptt" as shown below. content_viewer/models.py class Content(MPTTModel): content_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) content_name = models.CharField(max_length=250) I'm also using redis cache for cacheops and I've added the configurations as follow in my settings.py. dashboard/settings.py CACHEOPS_REDIS = { "host": REDIS_HOST, "port": REDIS_PORT, "db": 1, "socket_timeout": 3, } CACHEOPS = { "content_viewer.*": {"ops": {"fetch", "get"}, "timeout": 60 * 60}, } Note:- content_viewer is the name of the app Requirement: What I want here is a post_save signal on the MPTTModel class which should invalidate/clear the redis cache for the object that has been created/saved I've created a signal in my signals.py file as below. content_viewer/signals.py @receiver(post_save, sender=Content) def clear_redis_cache_for_mptt_instance(sender, instance, **kwargs): invalidate_obj(instance) and I've imported the signals inside the apps.py file as shown below. content_viewer/apps.py class WorkspaceDisplayConfig(AppConfig): name = "content_viewer" def ready(self): import content_viewer.signals But when I run the code in debug mode the signal seems to be never fired whenever I create an instance of the Content object. can anyone tell me what could I be doing wrong here? -
Django - after saving data redirecting to same url and showing json data showing on page django
I am trying to save data but the problem is while saving data it is showing json response which I'm returning from view views.py def Vwallocator_time(request): application_date = FcApplicationParameters.objects.first().todays_date att_data = FcAgentAttendance.objects.filter(user_id__in=User.objects.filter(is_active=1), attendance_status__in=('P', 'H'), attendance_date=application_date) attendance_data = att_data.values_list('user_id', flat=True) role_data = FcUserRoleMst.objects.filter(role_id=6, user_id__in=attendance_data).values_list('user_id', flat=True) profile_data = FcUserProfile.objects.filter(user_id__in=role_data) if request.POST: hours = request.POST.get('hours', 0) user_id = request.POST.get('user_id', None) att_data = FcAgentAttendance.objects.filter(user_id=user_id, attendance_date=application_date) att_data.update(fe_shift_hrs=hours) messages.success(request, "Hours saved Successfully.") return JsonResponse({'data': 'Hours saved Successfully'}) return render(request, 'allocator_agent_time.html', {'profile_data': profile_data, 'att_data': att_data }) allocator_agent_time.html <form action="{% url 'firstcall:allocator_time' %}" method="post"> {% csrf_token %} {% for message in messages %} <span id="msg_element"> <div class="alert alert-{{ message.tags }} alert-dismissible"> {{ message }} </div></span> {% endfor %} <span class="msg"></span> {% if att_data|length == 0 %} <div class="alert alert-warning"> <center> Please fill up the today's attendance muster. </center> </div> {% endif %} <div class="row"> <div class="col-md-12 roleBoxNewD"> <div class="Country-detail detail-style marginTop20"> <div class="box-header with-border p-0 m-0 position-relative"> <div class="row m-0 p-0"> <div class="col-md-7"> <h3 class="box-title position-absolute title_area">Agent Muster FE</h3> </div> <div class="col-md-5 text-right mt-1 mb-1">&nbsp;</div> </div> </div> <div class="output-table pre-allocation-box"> <div class="col-12"> <div id="example1_wrapper" class="dataTables_wrapper dt-bootstrap4 "> <div class="row"> <div class="col-sm-12 table-responsive"> <table id="example1" class="table table-hover table_devider table-striped table-top-design border-right border-left mb-2 dataTable currency-rate-table no-footer" role="grid" aria-describedby="example1_info"> <thead> … -
How to properly unpack a nested dictionary in a django HTML template?
So I was able to figure out how to unpack a dictionary keys and values on to a HTML template, but I am a bit confused as to how to unpack if if a dictionary value is a Querylist. For example I passing in all the timeslots of the given user into the dictonary. How can I unpack the attributes of the TimeSlot Query List for each timeslot such as the start time and end time? This is my HTML Template: <table> {% for key, value in user_info.items %} {% for key2,value2 in value.items %} <tr> <td>{{key2}}</td> <td>{{value2}}<td> </tr> {% endfor %} <br> {% endfor %} </table> My function in views.py def check_food_availibility(request): food = FoodAvail.objects.all() timeslots = TimeSlot.objects.all() users_dict = {} for i in range(len(user_info)): user = { "author": None, "food_available": None, "description": None, "timeslot": None } user["author"] = user_info[i].author.username user["food_available"] = user_info[i].food_available user["description"] = user_info[i].description if TimeSlot.objects.filter(time_slot_owner=user_info[i].author): user["timeslot"] = TimeSlot.objects.filter(time_slot_owner=user_info[i].author) users_dict[user_info[i].author.username] = user return render(request, "food_avail/view_food_avail.html", {"user_info": users_dict}) This is how it shows up currently: -
ctypes.util.find_library() did not manage to locate a library called 'pango-1.0-0' UBUNTU SERVER (EC2)
I am setting up my EC2 instance on AWS with an UBUNTU 18.04 and running into the following error when trying to run this gunicorn command gunicorn --bind 0.0.0.0:8000 zipherJobCards.wsgi:application error: OSError: cannot load library 'pango-1.0-0': pango-1.0-0: cannot open shared object file: No such file or directory. Additionally, ctypes.util.find_library() did not manage to locate a library called 'pango-1.0-0' I ran into this error after installing weasyprint in both my base directory and my web apps directory. Does anyone know the cause of this and also how to fix it? -
Passing Data From View to Model Django
I'm working on how to passing data from View to Model. I want to pass request.user.id from view to model through save method and put it on created_by field. Here is my view.py codes: def dashboardCategoryCreate(request): form = CategoryForm() if request.method == 'POST': form = CategoryForm(request.POST, request.FILES) form.save(request.user.id) # I Wanto To Pass This Value return redirect('dashboard-category') context = {'form': form} return render(request, 'category/category_form.html', context) And I try to catch this data on models.py and modify field created_by with userId value def save(self, userId=None): self.created_by = userId super().save() There is no error but value is not passing. How to do that? Or maybe there is another way to do that? -
Django model order_by based on another model queryset length
I have 2 models: models.py class Post(models.Model): title = models.CharField(max_length=255) desc = models.CharField(max_length=500) content = models.TextField() uploadedBy = models.ForeignKey(User, on_delete=models.CASCADE) LIKE_CATEGORIES = ( ("LIKE", "LIKE"), ("DISLIKE", "DISLIKE") ) class PostLike(models.Model): _type = models.CharField(max_length=200, choices=LIKE_CATEGORIES, blank=True, null=True) content = models.ForeignKey( Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) I want to order Post based on number of likes a post has. Number of likes a post has is the count of PostLike objects having _type="LIKE",content=post_object. How can I order Post specifically based on number of likes? -
I want that my answer field must be equal to the (one)options field. i try but it didn't working?
#forms.py from django.forms import ModelForm from .models import Question class QuestionForm(ModelForm): class Meta: model = Question fields = "__all__" def clean_answer(self): answer = self.cleaned_data['answer'] option1 = self.cleaned_data['option1'] option2 = self.cleaned_data['option2'] option3 = self.cleaned_data['option3'] option4 = self.cleaned_data['option4'] # print(answer,option1,option2, option3,option4) # return answer if answer == option1 or answer == option2 or answer == option3 or answer == option4: return answer #views.py class AddQuestion(View): def post(self, request): forms = QuestionForm(request.POST) if forms.is_valid: forms.save() messages.success(request, 'Successfully Added') else: messages.error(request, 'Answer must be equal to the choices') return redirect(reverse('home')) def get(self, request): forms = QuestionForm() context = {'forms': forms} return render(request,'file/addQuestion.html',context) #AddQuestion.html {% extends 'file/base.html' %} {% block title %} AddQuestion {% endblock %} {% block body %} <div class = 'container mt-5 pt-6'> <div class = 'col-md-5 mx-auto'> <h3>Add Question: </h3> <form method="POST" action="" > {% for msg in messages %} {{ msg }} {% endfor %} {% csrf_token %} {{forms.as_p}} <input type = 'submit' value = 'Submit'> </form> </div> </div> {% endblock %} -
how can I convert the normal post method submission from an html from into an ajax call in django without losing the same logic?
How can I convert the normal post method submission from an html from into an ajax call in django without losing the same logic.My django files are given below.I don't want to lose the logic. The logic should be same. views.py @csrf_exempt @require_http_methods(['POST', 'GET']) # only get and post def crawl(request): if request.method == 'POST': url = request.POST.get("id_url",None) print(url) if not url: return JsonResponse({'error': 'Missing args'}) if not is_valid_url(url): return JsonResponse({'error': 'URL is invalid'}) domain = urlparse(url).netloc # parse the url and extract the domain unique_id = str(uuid4()) # create a unique ID. settings = { 'unique_id': unique_id, # unique ID for each record for DB 'url':url, #'USER_AGENT': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' } This is my index.html <form method="POST" class="post-form" id='userinfoform' action="{% url 'crawl' %}" onsubmit="return spinner();"> <div class="container " > <br> <div class="form-group"> <label class=" col-form-label"></label> <div class="col-lg"> <h3><strong>Please Fill The Details</strong></h3> </div> </div> <br> <fieldset class="w-100 border border-rounded p-4"><legend class="w-25 text-center">Domain Form</legend> <div class="form-group row"> <label class="col-sm-4 col-form-label"><strong>Enter domain name:</strong></label> <div class="col-sm-8"> <input type="text" name="id_url" id="id_url" required="" value=""> </div> </div> <br> {% if d %} <p style="color: red;">{{d}}</p> {% endif %} </fieldset> <div class="form-group row mt-3"> <label class="col-sm-4 col-form-label"></label> <div class="col-sm-8 text-right"> <button type="submit" class="btn btn-primary w-25" name='submit' … -
How i can make Analytics dhasboard with models data in django without using google Analytics
I am working on my website but I am confused does I make Analytics function with myself or do I use Google Analytics? I don't have experience in both. In the dashboard, I have to show views with graph and retention on-page and other things -
Multiple forms with one single create view in Django
I have 5 forms: MyForm, EducationForm, ExperienceForm, RecommendationForm, OtherDocumentsForm I want to disply them in one form template. I can not do it with CreateView because it only accepts one form class. How can I create single view for multiple forms? class MyForm(forms.ModelForm): class Meta: model = UserForm_uz fields = 'all' class EducationForm(forms.ModelForm): class Meta: model = Education_uz fields = 'all' class ExperienceForm(forms.ModelForm): class Meta: model = Experience_uz fields = 'all' class RecommendationForm(forms.ModelForm): class Meta: model = Recommendation_uz fields = 'all' class OtherDocumentsForm(forms.ModelForm): class Meta: model = OtherDocuments fields = 'all' -
How to connect Google big query between Django project and postgresql database?
I am new to bigquery and Django, I want to optimize the performance for analysis of past data for that I want data to come out from postgresql to bigquery for process and then I want to show it in frontend of Django project. Since analysis of past data effect the performance of transaction workloads in postgresql so bigquery is best technology for that. -
How to add nested field after creating the ModelSerializer? Not in the class
Basically i want to have fk_inventory as a nested field in StorageRackSerializer but as you guys can see I also need to use StorageRackSerializer in InventorySerializer. How can i set the field after creating the serializer class? I have tried creating a fk_inventory field and set it to None and tried to set to InventorySerializer afterwards but didn't work. class Inventory(models.Model): inventory_id = models.AutoField(primary_key=True) fk_building = models.OneToOneField(Store, on_delete=models.CASCADE, unique=True, related_name='inventory') def __str__(self): return f"{self.inventory_id}" class StorageRack(models.Model): storage_rack_id = models.AutoField(primary_key=True) quantity = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(50)]) fk_inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE, related_name="storage_racks") fk_product_id = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, related_name="storage_racks") def __str__(self): return f"{self.storage_rack_id}" class StorageRackSerializer(serializers.ModelSerializer): fk_product_id = ProductSerializer(read_only=True) fk_inventory = None class Meta: model = StorageRack fields = ('storage_rack_id', 'quantity', 'fk_inventory', 'fk_product_id') class InventorySerializer(serializers.ModelSerializer): fk_building = StoreSerializer() storage_racks = StorageRackSerializer(many=True) class Meta: model = Inventory fields = ('inventory_id', 'fk_building', 'storage_racks') StorageRackSerializer.fk_inventory = InventorySerializer() -
rm: refused to remove '.' or '..' directory: skipping '..' on running docker-compose
Here is my docker file FROM python:3.8-slim-buster ENV PYTHONUNBUFFERED 1 WORKDIR /app ADD . /app COPY requirements.txt requirements.txt RUN pip install --upgrade pip setuptools wheel RUN apt-get update && apt-get install -y --no-install-recommends \ tzdata \ libopencv-dev \ build-essential \ libssl-dev \ libpq-dev \ libcurl4-gnutls-dev \ libexpat1-dev \ gettext \ unzip \ python3-setuptools \ python3-pip \ python3-dev \ python3-venv \ git \ && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* \ \ pip3 install -r /app/requirements.txt COPY . /app I used to get a "couldn't import Django" error so I updated my docker file by changing the line pip install -r requirements.txt to run . venv/bin/activate && pip install -r requirements.txt: FROM python:3.8-slim-buster ENV PYTHONUNBUFFERED 1 WORKDIR /app ADD . /app COPY requirements.txt requirements.txt RUN pip install --upgrade pip setuptools wheel RUN apt-get update && apt-get install -y --no-install-recommends \ tzdata \ libopencv-dev \ build-essential \ libssl-dev \ libpq-dev \ libcurl4-gnutls-dev \ libexpat1-dev \ gettext \ unzip \ python3-setuptools \ python3-pip \ python3-dev \ python3-venv \ git \ && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* \ \ RUN . venv/bin/activate && pip3 install -r /app/requirements.txt COPY . /app Now I am getting the error refused to remove … -
django invite users with to a specific project with a specific role
I have a django app built for music producers. I am trying to build a system for a producer to invite other users (potentially users that don't even have an account) to a project with a specific role. So basically as I producer I would get the email of someone I want to invite to my project, I would choose a role for him and I would then send an invitato to him. What i am not sure is how can I create an invite url where the user that clicks on it, after sign-ing up automatically has the role and access to the project they got invited for. Thoughts? -
Django models not accessible in python script
Directory structure my_project/ ├ ├ dashboard/ ├ __init__.py │ ├ models.py │ └ module2.py scripts/ ├ __init__.py │ ├ data_transfer.py │ └ data_transfer.py import sys import os import django import ast from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings") from dashboard.models import ReceivedData # dictionary = ast.literal_eval(str_dict) meter_data = ReceivedData.objects.all().first() print(meter_data.retrieved_data) print(meter_data) I am trying to execute a python script inside Django project but somehow i am not able to access the models which are in other directory error: "data_transfer.py", line 10, in <module> from dashboard.models import ReceivedData ModuleNotFoundError: No module named 'dashboard' -
how to group equal data and show it in the template
I have an app that shows the history of products ordered in a restaurant, and to get the data of the restaurant, i have the following view: def restaurant_orders(request): restaurant = get_restaurant(request.user.restaurant.user_id) products = list(restaurant.restaurante.values_list("id")) items = Item.objects.filter(product_id__in=products).order_by('order_id') context = {'items': items} return render(request, 'pages/orders_restaurant.html', context) In template i'm displaying as follows: <div class="col-lg-7"> <h2>Histórico de Pedidos</h2> {% for value in items %} <ul class="list-group list-group-flush"></ul> <li class="list-group-item bg-light"> <h4>Order {{ value.order_id }}</h4> {{ value.quantity }} X {{ value.product }} <span class="float-right">R$ {{ value.price }}</span> <li class="font-weight-bold list-group-item bg-light">Client Name <span class="float-right">{{ value.order.name }}</span> </li> </li> <br> {% endfor %} </div> but doing it this way I get each data separate, and I would like to know if there is any way to group the data that has a field with the same value. The result I getting now is this, and I would like something like this. model.py class Item(models.Model): order = models.ForeignKey(Order, related_name="items", on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name="order_items", on_delete=models.CASCADE) price = models.DecimalField(max_digits=5, decimal_places=2) quantity = models.PositiveIntegerField( validators= [ MinValueValidator(1), MaxValueValidator(20), ] ) -
How to style form in django?
I'm trying to style this upload form in django site, so far is not working. I usually lose some part in process or at the end form is not working. I was wondering what would be simplest way to keep all elements, but to look like modern style. This is how it looks now in my django site. This is html. {% extends "base.html" %} {% load static %} {% block content %} <form action="{% url "rca" %}" method="post" enctype="multipart/form-data" class="dropzone"> {% csrf_token %} {{ message }} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p> <p> {{ form.docfile.errors }} {{ form.docfile }} </p> <p><input type="submit" value="Upload and Download!"/></p> </form> {% endblock content %} Please give me some simple solution suggestions. Thanks in advance! -
Django and HTML- How to apply style to only one survey
I have created a Django project where I have two surveys. One of the surveys asks the user to select one image as their answer. So far, the survey is working in that I am able to display the images and record the user's answer (which by the way is the name of the image, not the image itself). However, I want to arrange all the images in a circle container. I want to apply this styling only to the one survey with images, not the other survey. This has been difficult because my HTML syntax uses "for" loops to go over the surveys, and also I created both surveys using the same Django ModelForm (I think this shouldn't be a problem). Please I need recommendations on how this can be done. So far I have been trying some "if-then" statements but they have been wrong. See below the HTML file that I have with the code for the circle container at the end: <form method="post" action="{{ request.url }}"> {% csrf_token %} <legend><h2>{{ questionnaire.text }}</h2></legend> {% for question in questions %} <h1>{{question.text}}</h1> <label hidden="" for="id_form-{{ forloop.counter0 }}-question">Question:</label> <select hidden="" name="form-{{ forloop.counter0 }}-question" id="id_form-{{ forloop.counter0 }}-question"> <option value="{{question.id}}" selected="">{{question.text}}</option> </select> <label … -
How can i combine these two Django annotated queries into one?
i have two queries: bb1 = Users.objects.filter(comments__likedislike__gt=0).annotate(likes=Sum('comments__likedislike')) bb2 = Users.objects.filter(comments__likedislike__lt=0).annotate(dislikes=Sum('comments__likedislike')) how to combine them? -
Django: How to update one field at a time on a form?
I've been trying to find a solution online but I haven't found any that works, I was hoping you guys could help me out with this as I've been in this situation for a two days now. My problem is whenever I tried to update one of the fields of my User an error pops up saying that it is required to update the other fields too. I've tried putting blank=True on one of the fields of my User model so that the required thing will turn to False, but when I click update on the front end those fields that I haven't changed turn to blank. All I want is to let the user be able to update one field if he or she wants too without the need to update the other fields.. just like on the admin site, you can freely update one field of a user and it would not throw you an error. Could someone help me out with this? this is my view class ProfileUpdateView(LoginRequiredMixin,UpdateView): model = User form_class = UserUpdateForm template_name = 'accounts/profile_update.html' def get_object(self, *args, **kwargs): return User.objects.get(username=self.kwargs.get('username')) def get_success_url(self): self.object = self.get_object() return reverse_lazy('accounts:profile_update', self.request.user.username) this is my form class UserUpdateForm(forms.ModelForm): … -
How can I make pagination to work with filtering django?
I have a webpage with pagination, but when I click on the second button, all the data from my database will appear, I only want to paginate according to the the filter I set, like technical investigation will only appear the status as technical investigation. The sort by in ascending order is working, but the moment i click on the part number or the other 3, it will show all the data from the database also, how to prevent that and only show the data base on the filtering of the next status? This is my current page, but when I click on the number 2, all the data will appear and my filtering of the next status technical investigation wont work anymore. views.py @login_required() def investigation(request): search_post = request.GET.get('q') # Code for the users to search for reception, partno, serialno, mconum, customername if (search_post is not None) and search_post: allusername = Photo.objects.filter(Q(reception__icontains=search_post) | Q(partno__icontains=search_post) | Q( Customername__icontains=search_post) | Q(mcoNum__icontains=search_post) | Q( serialno__icontains=search_post)) if not allusername: allusername = Photo.objects.all().order_by("-Datetime") else: allusername = Photo.objects.all().filter(Q(nextstatus='Technical Investigation')).order_by("-Datetime") # Sort BY: part = request.GET.get('sortType') valid_sort = ["partno", "serialno", "Customername", "mcoNum"] # Sort the workshop data in ascending order acording to the part number, serial …