Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I submit multiple django forms with one button at once with jquery?
I have a single page application consisting of multiple forms (It's not possible for me to use only one form, as I need to validate ). At a button press, I need to submit each form, somehow catch the response and only redirect the page if one of those forms is invalid. In my view, I return HttpResponse(status=204) if a single form is valid or render(request, 'home.html', context) if a form is invalid. I tried this, but it's obviously not working. Is there a way to submit multiple forms and do nothing, if a response is 204? $('#download-btn').click(function () { $("form").each(function () { $(this).submit(); // Seems to only submit one form // Don't redirect page here, so that all forms get submitted }); }); -
CKEditor plugins not working with django-ckeditor
I wanted to install easyimage plugin. I unpacked zip file to plugins folder so it's in static/ckeditor/ckeditor/plugins/easyimage settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'toolbar_Custom': [ ['Bold', 'Italic', 'Underline'], ['NumberedList', 'BulletedList'], ['Link', 'Unlink'], ['EasyImageUpload'] ], 'width': '100%', 'height': 100, 'extraPlugins': ','.join( [ 'easyimage', ] ), }, and i still get error GET http://192.168.0.3:8000/static/ckeditor/ckeditor/plugins/easyimage/plugin.js?t=K5H9 net::ERR_ABORTED 404 (Not Found) ckeditor.js:270 Uncaught Error: [CKEDITOR.resourceManager.load] Resource name "easyimage" was not found at "http://192.168.0.3:8000/static/ckeditor/ckeditor/plugins/easyimage/plugin.js?t=K5H9". -
How to make a form redirect to an URL given by the user in Django?
There are similar questions in stackoverflow, but not similar enough to help me solve my problem. I'm making a wikipedia-like website with Django, and would like to add a feature to enable the user to post their pages, just like in wikipedia. But the thing is, I want that when the user clicks the 'Add' button, he gets redirected to the page he just created. The URL to that page is the same as the title he gives in the form. This is the form definition: class PageCreationForm(forms.Form): title = forms.CharField(max_length=100) description = forms.CharField(widget=forms.Textarea) def get_title(): return title def createPage(request): return render(request, "encyclopedia/create.html", {"form":PageCreationForm()}) And the form usage in the HTML: <h1>Create A New Wiki Page</h1> <form action="{% url 'wikipedia:renderWikiPage' {{form.getTitle()}} %}" method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Add" /> </form> The URL 'renderWikiPage' needs the title of the page I want to render, and I tried to provide the title with {{form.getTitle()}}. Of course it did not work. How can I do that? -
Django: Parse HTML (containing form) to dictionary
I once saw a parse_form(response.content) method which did this (for unittesting django applications) response = client.get('/foo/') # response contains <form> ...</form> data = parse_form(response.content) data['set_value_of_existing_input']='foo' # this should raise an exception data['set_value_of_non_existing_input']='bar' response = client.post('/foo/', data) How to implement (or find) parse_form()? I read the testing responses docs but could not find something like this. -
Hosting a Django REST framework + Vue App on VPS Server
I have been trying to deploy an app I created using Django REST framework with Vue frontend on a VPS server. My server currently runs Webmin with a couple WordPress sites. I have been trying to follow the tutorial from https://www.shellvoide.com/hacks/installing-django-application-with-nginx-mysql-and-gunicorn-on-ubuntu-vps/ and not able to make this work. I should point out I am using Postgresql, not MySQL, like in this tutorial. When I run the guinicorn or startapp scripts from SSH, everything starts up successfully. The issue I am running into is creating the startup service with NGINX. Whenever I try to do this, it immediately makes all my other sites inaccessible. Forgive my ignorance, this is my first time ever trying anything like this, but is there any way to create startup commands to run the app without NGINX? If you have any tips or ideas for the best way to run this app, I am interested in finding out if there are better solutions or any knowledge you can share. Cheers! -
Integrating User profile system with comment system with Python Django
I have created a Comment system with django, previously anyone could comment regardless of account status, however i have started to integrate my user system to ensure that people commenting have an account. I have thought of many ways to carry this out however I am not sure how to replace the user-inputted 'name' field with the already set 'username'. I have tried using this code so far: models.py (The comment model) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_comments') email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f"Comment views.py (How the comment is saved to the post) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status="published", publish__year=year, publish__month=month, publish__day=day) comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = CommentForm() post_tag_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tag_ids).exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:3] return render(request, 'blog/post/detail.html', {"post": post, "comments":comments, "new_comment":new_comment, "comment_form": comment_form, 'similar_posts': similar_posts}) forms.py (The form for actually commenting) class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) details.html (Displaying the comment form, … -
Adding django to system path - some commands working and some not
I'm trying to set up Django. It's only partially working. I added Django to the system path as advised by other questions here. My PATH variable is 'C:\Users\Me\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\Scripts" and my PYTHONPATH variable is almost identical except it goes "Python39\site-packages" instead of Scripts. If I type "py" into the command line ("python" worked before I changed PATH, but now it has to be "py") and then type "import django," it doesn't throw an error. So it seems that my installation of Django is visible to Python. But if I exit "py" and then type "django startproject testsite," "django-admin startproject testsite," or "django-admin.py startproject testsite" into the command line, it says that django/django-admin/django-admin.py isn't recognized as a command. I'm using Django version 3.1.4 and Python version 3.9.0. These problems only started after I fiddled with the system path variables, so I guess I set them wrong? Please help. -
Creating a Django model ForeignKey field from a specific queryset?
Ok, this is a hard one to explain. I Have these models: class Supplier(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) class Product(models.Model): description = models.CharField(max_length=30) costprice = models.FloatField(null=True, max_length=99, blank=True) retailprice = models.FloatField(null=True, max_length=99, blank=True) barcode = models.CharField(null=True, max_length=99, unique=True, blank=True) image = DefaultStaticImageField(null=True, blank=True,default='images/item_gC0XXrx.png') supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, null=True, blank=True) class Order(models.Model): item = models.ForeignKey(Product, on_delete=models.CASCADE, default='') supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) item_qty = models.IntegerField(null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) My ultimate goal is to be able to create an 'Order' pulling items from a specific supplier. Now, I have no idea as to make that happen - how do I create an instance of an 'Order',in a form of some sort, that will fetch items from the selected supplier and not all items from everybody else? -
AWS ElasticBeanstalk Multi-Docker Deployment Failure
I'm attempting to deploy a multi-docker environment on EB and running into a strange error. I can't figure out what's causing it. This is the Dockerrun file: { "AWSEBDockerrunVersion": 2, "containerDefinitions": [ { "command": [ "celery", "-A", "grmrptcore", "worker", "-l", "INFO", "-B" ], "environment": [ { "name": "PYTHONPATH", "value": "/usr/local/bin:/bin/" }, { "name": "CELERY_BROKER", "value": "redis://redis:6379/0" }, { "name": "CELERY_BACKEND", "value": "redis://redis:6379/0" } ], "essential": true, "image": "alexphi981/grmrptcore", "memory": 1024, "mountPoints": [ { "containerPath": "/opt/python/log/", "sourceVolume": "celery_log" } ], "name": "celery" }, { "command": [ "python3", "manage.py", "runserver", "0.0.0.0:8000" ], "environment": [ { "name": "PYTHONPATH", "value": "/usr/local/bin:/bin/" }, { "name": "CELERY_BROKER", "value": "redis://redis:6379/0" }, { "name": "CELERY_BACKEND", "value": "redis://redis:6379/0" } ], "essential": true, "image": "alexphi981/grmrptcore", "memory": 1024, "mountPoints": [ { "containerPath": "/opt/python/log/", "sourceVolume": "django_log" }, { "containerPath": "/src/static", "sourceVolume": "Static_Volume" } ], "name": "django", "healthCheck": { "command": [ "CMD-SHELL", "curl", "-f", "http://0.0.0.0:8000/", "||", "exit", "1" ] } }, { "command": [ "python3", "manage.py", "migrate" ], "environment": [ { "name": "PYTHONPATH", "value": "/usr/local/bin:/bin/" } ], "essential": false, "image": "alexphi981/grmrptcore", "memory": 200, "mountPoints": [ { "containerPath": "/opt/python/log/", "sourceVolume": "migrate_log" } ], "name": "migrate" }, { "essential": true, "image": "alexphi981/nginx", "memory": 200, "mountPoints": [ { "containerPath": "/src/static", "sourceVolume": "Static_Volume" }, { "containerPath": "/var/log/nginx/", … -
How to convert post_save to pre_save signals?
I have setup a OtoO relationship between Property and a ListingDetail Model: class Property(models.Model): . . . def __str__(self): return "Property " + str(self.pk) ListingDetail Model: class ListingDetial(models.Model): property = models.OneToOneField("properties.Property", on_delete=models.CASCADE) . . . Now I donot want to manually select the property field in LocationDetail Model and instead want to save it automatically. Currently I have used the post_save signal to achieve the funtionality: @receiver(post_save, sender=Property) def ensure_sub_section_model_exists(sender, **kwargs): if kwargs.get('created', False): ListingDetial.objects.get_or_create(property=kwargs.get('instance')) But the issue with this approach is that every time a Property instance is created it creates a ListingDetail, the only trouble with this approach is that I need to keep all the field nullable. What I want is that after I create the ListingModel, the property stores the value same as PK of ListingModel. -
Django: Explicitly ignore missing variable in template?
I use the pytest-django setting FAIL_INVALID_TEMPLATE_VARS Now invalid vars get checked if pytest executes the code. [pytest] DJANGO_SETTINGS_MODULE = mysite.settings FAIL_INVALID_TEMPLATE_VARS = True I have a simple template: <form action="."> <input type="search" name="query" value="{{request.GET.query}}"> <input type="submit"> </form> If request.GET is empty I get: Failed: Undefined template variable 'request.GET.query' How can I ignore this missing variable in my template? -
Is it possible to create a for loop inside a main for loop inside django templates?
I'm just learning django part time and I'm stuck on a problem that I just can't seem to find a solution to. I feel it is probably pretty simple, but I just can't seem to see it right now. In django I have the following table class category(models.Model): category = models.CharField(max_length=100) def __str__(self): return f"{self.id} is {self.category}" class knowledge(models.Model): name = models.CharField(max_length=16) location = models.URLField(max_length=1024) title = models.TextField(blank=True, max_length=512) description = models.TextField(max_length=1024) category = models.ForeignKey(category, on_delete=models.CASCADE, related_name="content") def __str__(self): return f"{self.id}{self.name} {self.location} {self.description}" class notes(models.Model): note = models.TextField(blank=True, max_length=1024, default='none') date_added = models.DateTimeField(blank=True, default=timezone.now) knowledge = models.ForeignKey(knowledge, on_delete=models.CASCADE, related_name="mynotes") def __str__(self): return f"Added on {self.date_added}" For my views I have def kbs(request, category_id): # get all the objects in the category table with the id specified cate = category.objects.get(id=category_id) # once you have the category id get all the objects from the knowledge table using the related name content know = cate.content.all() # for each id in know create a list of notes? return render(request, "knowledge/category.html", { "cate": cate, "know": know, I can loop over all the items in the knowledge table and display them in my template. I wanted to add some notes to each knowledge article from another … -
How to reuse Django's SQL compiler?
I needed to perform an UPDATE JOIN query but django has no builtin support for that, so I wrote a raw SQL query. But now I need to build the where clause of that query dynamically, so I would like to know how to reuse Django's SQL compiler. I could take the Query object from Model.objects.filter(...).query, then generate the raw SQL of the where clause with query.where.as_sql(query.get_compiler(using='default'), None) but the tables from my current raw SQL are aliased, so the lookup fields will be wrong. -
Django - form_valid() takes 2 positional arguments but 5 were given - Multiple forms
I am new using Django and I want to save 4 different forms using CreateView. I am able to save 3 of them: Product Form Product Cost Form Product Prices Form But with Product inventory Form, I am getting this error: form_valid() takes 2 positional arguments but 5 were given. Product inventory Form: class ProdInvForm2(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Row( Column('invmax', css_class='form-group col-md-6 mb-0'), Column('invmin', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), ) class Meta: model = ProdInv # fields = ('invmin', 'invmax') widgets = { 'invmax': NumberInput( attrs={ 'placeholder': 'Inventario Maximo', } ), 'invmin': NumberInput( attrs={ 'placeholder': 'Inventario Minimo', } ), } # esto es para excluir campos que no quieres que aparezcan #, 'invact', 'invord', 'invres' exclude = ['user_updated', 'user_creation', 'prod', 'invact', 'invord', 'invres'] Product Inventory Models: class ProdInv(BaseModel): prod = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='Producto') invact = models.IntegerField(default=0, null=True, blank=True, verbose_name='Inventario Actual') invres = models.IntegerField(default=0, null=True, blank=True, verbose_name='Inventario Reservado') invord = models.IntegerField(default=0, null=True, blank=True, verbose_name='Inventario Ordenado') invmax = models.IntegerField(default=0, blank=True, verbose_name='Inventario Maximo') invmin = models.IntegerField(default=0, blank=True, verbose_name='Inventario Minimo') def toJSON(self): item = model_to_dict(self, exclude=['user_creation', 'user_updated']) item['prod'] = self.prod.toJSON() return item def __str__(self): return self.prod.name class Meta: verbose_name = 'Inventario de … -
Can you debug to find the source code of a function in Django/Python?
def _construct_form(self, i, **kwargs): """Instantiate and return the i-th form instance in a formset.""" defaults = { 'auto_id': self.auto_id, 'prefix': self.add_prefix(i), 'error_class': self.error_class, # Don't render the HTML 'required' attribute as it may cause # incorrect validation for extra, optional, and deleted # forms in the formset. 'use_required_attribute': False, } if self.is_bound: defaults['data'] = self.data defaults['files'] = self.files if self.initial and 'initial' not in kwargs: try: defaults['initial'] = self.initial[i] except IndexError: pass # Allow extra forms to be empty, unless they're part of # the minimum forms. if i >= self.initial_form_count() and i >= self.min_num: defaults['empty_permitted'] = True defaults.update(kwargs) form = self.form(**defaults) self.add_fields(form, i) return form With regards the line: form = self.form(**defaults), I have no idea where it comes from. The method self.form() is not defined anywhere else or imported it seems and I am struggling to deal with it. Is there anyway of finding out its source code to tackle it better? Thank you. -
Django - How to update a list of models on a page instantly without refreshing?
In my html I use a bootstrap list group and I use a for loop to loop through all instances of a model and display a list item with the name of the instance. On the same page, I have buttons to create, edit, and delete instances. All those buttons do their actions using ajax post requests, so no page loading is required there, but after clicking a button, I have to refresh the page to see the changes in the list. Do I need to do another ajax request to make it refresh automatically? html file <ul class="list-group" id="instance_list"> {% for instance in instance_names %} <li class="list-group-item"> <input class="form-check-input" name="instance_name" type="checkbox" value="{{instance}}" aria-label="...">{{instance}} </li> {% endfor %} </ul> <button class="btn btn-primary" type="button" id="create">Create</button> <button type="button" class="btn btn-primary" id="edit">Edit</button> <button type="button" class="btn btn-danger" id="delete">Delete</button> -
query database datetime field for all rows with full hour in django
I have a table with sensor data, resistor values, captured every minute; My app is django-2, python3, mysql; Is it possibel somehow with django queries to select only the rows where my datetime field has i.e. the minute==0, so I get data entries with regular intervals?? Similar to this (object_list has no results) object_list = SensorData_01.objects.filter(dtime__minute=0) I just read all the awesome filter functions in django docs, and saw the dates() and datetimes() comparison functions; But my issue was not explained there. -
I can't display data from database on web page using Python and Django
I have a big problem. I want to display data from my database( SQLite) on a webpage( the data should be present in an HTML table). I have checked my request with Postman and there everything looks fine, but with all of these, I can't see the data on my page.( I'm using Python and Django) **HTML from my template - ** <div id="patientsPanel"> <button class="addButton outline-text" style="top:5px;background-color:#FED558;" onclick="addNewPatient()"><i class="fas fa-plus outline-text" style="color:white;"></i> Add patient</button> <button class="addButton outline-text" style="top:33px;background-color:#691188;text-align:center;" onclick="displayPatientsList()"><i class="fas fa-align-justify" style="color:white"></i> Patients</button> <span class="closebtn outline-text" onclick="this.parentElement.style.display='none';">&times;</span> <h1 class="outline-text" style=text-align:center>{{user.username}}</h1> <div id="patientsList"> <table class="table"> <tr> <th>FirstName</th> <th>LastName</th> <th>Phone</th> <th>Actions</th> </tr> <tbody> {% for patient in patientsForm %} <tr> <td>{{patient.firstName}}</td> <td>{{patient.lastName}}</td> <td>{{patient.phone}}</td> <td>More</td> </tr> {% endfor %} <tr> <td>Dummy</td> <td>Dummy</td> <td>Dummy</td> <td>More</td> </tr> </tbody> </table> </div> </div> There are two panels. When I click a button on the first one, the second panel( this is the panel with data from the database) should appear. The function displayPatientsList() is just for making the panel visible, nothing special. Here is my views.py def viewPatients(request): print("Aici in viewPatients!!") patients = Patient.objects.all() return render(request, 'medRelations/account.html', {'patientsForm': patients}) urls.py from django.contrib import admin from django.urls import include, path from medRelations.views import ( registrationView, loginPageView, accountView, … -
Why code works in one computer and not in second?
I dont know whether it is right question to ask it here, but i have the code from my friend that reads excel file(so you upload it to the page and code redirects you to admin page with uploaded excel file(on sql db) with filter possibilities, and when i run it runs, but admin page does not show anything(in my Mac), while in my friends laptop(windows if it helps) it is shown, he also checked it and could not find the problem. What can be the problem? I downloaded packages from requirements file that he had, i run it on virtual environment(Pycharm), i dont know what else to check? -
Error 111 connecting to 127.0.0.1:6379 Connection refused using docker
I am trying to connect my celery with redis serve and getting this error in django. beat: Connection error: Error 111 connecting to 127.0.0.1:6379. Connection refused.. Trying again in 2.0 seconds... consumer: Cannot connect to redis://127.0.0.1:6379//: Error 111 connecting to 127.0.0.1:6379. Connection refused.. while my docker-compose file is like version: '3' volumes: postgresql_data: services: database: container_name: postgres hostname: sampleproject_database image: postgres:12-alpine environment: - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_DB=${POSTGRES_DB} - POSTGRES_HOST=${POSTGRES_HOST} - POSTGRES_PORT=${POSTGRES_PORT} volumes: - postgresql_data:/var/lib/postgresql/data healthcheck: test: [ "CMD-SHELL", "pg_isready -U postgres" ] interval: 5s timeout: 5s retries: 5 ports: - "5432" app: container_name: sampleproject_app hostname: sampleproject_app build: context: . dockerfile: Dockerfile image: sampleproject command: > bash -c " python manage.py migrate && python manage.py runserver 0.0.0.0:8000 " environment: - SECRET_KEY=${SECRET_KEY} - DEBUG=${DEBUG} - SENDGRID_API_KEY=${SENDGRID_API_KEY} - ALLOWED_HOSTS=${ALLOWED_HOSTS} - SITE_URL=${SITE_URL} - EMAIL_SENDER=${EMAIL_SENDER} - ASENTRY_DSN=${ASENTRY_DSN} - ENCRYPTION_KEY=${ENCRYPTION_KEY} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_DB=${POSTGRES_DB} - POSTGRES_HOST=${POSTGRES_HOST} - POSTGRES_PORT=${POSTGRES_PORT} env_file: .env ports: - "8000:8000" volumes: - .:/usr/src/app/ depends_on: - database - redis redis: image: redis:latest ports: - "6379:6379" celery: build: context: ./ dockerfile: Dockerfile command: celery -A sampleproject worker -l info volumes: - .:/usr/src/app/ environment: - DEBUG=${DEBUG} - SECRET_KEY=${SECRET_KEY} - ALLOWED_HOSTS=${ALLOWED_HOSTS} depends_on: - database - redis celery-beat: build: . command: celery -A sampleproject beat … -
Feeding image to a Django template
I've been working on a simple Django project for myself and I came into a little problem. When first developing the blog, I didn't make templates, I just made sure things were working properly, but now, I dived into making the templates and everything is working besides my header background-image. Before the templates, I was doing it like this: <header class="masthead" style="background-image: url({% static 'img/home-tech-bg.jpg' %})"> This was working just fine, but now that I'm trying to do the same as a template it doesn't work. It doesn't return me any errors, but the image doesn't display. What I did was the following: template base.html <header class="masthead" style="background-image: url({% block headerimage %} {% endblock %})"> blog.html {% load static %} {% block headerimage %} {% static 'image/image.jpg' %} {% endblock %} What is a better way to do this? -
Get the name of the submit button that was clicked in django
I have this form where I create submit buttons which each correspond to a Product object: <form action="/costcorrect/product_choice" method="post"> {% csrf_token %} {% for product in product_list %} <div class="product"> <img src="{{product.image_url}}" alt="{{product.name}}"> <h2>{{product.name}}</h2> <input type="submit" name="{{product.id}}" value="Choose Product"> </div> {% endfor %} </form> I want to get the name of the button the user clicks on, so I know which product was selected. Other questions (like this one) that are related to this had buttons with fixed names, so it was easy to refer to them. My issue is that I'm not sure what the names of the buttons will be, so I can't refer to them directly in views. -
Django Migrations not detecting is_active column
I created a custom user model using the AbstractBaseUser class (see source code below). However, after realising that the column I needed in the table should be called "is_active" not "active", I renamed the column in the models file, however, the migrations only removed the "active" column but didn't create an "is_active" column. Any ideas? class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(max_length=50, null=True) last_name = models.CharField(max_length=100, null=True) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user date_joined = models.DateTimeField(auto_now_add=True) manager_access = models.BooleanField(default=False) USERNAME_FIELD = 'email' # Email & Password are required by default. REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager() def get_full_name(self): return self.first_name + self.last_name def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" return self.staff @property def is_admin(self): "Is the user a admin member?" return self.is_superuser @property def is_active(self): "Is the user active?" return self.is_active -
Django - How to filter products by price?
I am trying to build an E-Commerce application using Django. I am trying to add a price filter using select tag in HTML. So, every time select option changes I want to change to filter product by low-to-high or vice-versa. HTML Code <div class="d-flex flex-row-reverse" style="margin-right: 20px; margin-bottom: 20px;"> <label> <select class="bg-dark" name="price" id="priceFilter" onchange="getValue()"> <option value="normal">Sort by Price</option> <option value="low">Low to High</option> <option value="high">High to Low</option> </select> </label> </div> javascript function getValue() { let option = document.getElementById('priceFilter'); let value = option.value; let url = '/price_filter/'; fetch(url, { method: 'POST', headers: { 'Content-type': 'application/json', 'X-CSRFToken': csrftoken }, body: JSON.stringify({'value': value}) }) .then((response) => { return response.json() }) .then((data) => { console.log('data:', data) location.reload() }) } views.py def filterByPrice(request): data = json.loads(request.body) value = data['value'] print(value) if value == 'low': products = Product.objects.all().order_by('productDiscountedPrice') context = { 'products': products } return render(request, "Amazon/filteredResult.html", context) elif value == 'high': products = Product.objects.all().order_by('-productDiscountedPrice') context = { 'products': products } return render(request, "Amazon/filteredResult.html", context) else: products = Product.objects.all() context = { 'products': products } return render(request, "Amazon/filteredResult.html", context) So, the problem is, It is not getting redirected to filteredResult page, but value in getting printed in terminal. Any Idea why it is not getting redirected? -
How to add Django Template code in JavaScript innerHTML
I am trying to add a search feature for my Django project, but I have a problem knowing how to write Django Template in the Javascript Innerbox. I have an Item model as following: class Item(models.Model): title = models.CharField(max_length=100) image = models.ImageField(blank=False, upload_to=upload_design_to) price = models.DecimalField(decimal_places=2, max_digits=100) discount_price = models.DecimalField(decimal_places=2, max_digits=100, blank=True, null=True) timestamp = models.DateTimeField(default=timezone.now) Item list view as following: class ItemListView(ListView): model = Item paginate_by = 12 template_name = "store/product_list.html" ordering = ['-timestamp'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["qs_json"] = json.dumps(list(Item.objects.values()),cls=DjangoJSONEncoder) return context I have the following Script: <script> const data = '{{qs_json}}' const rdata = JSON.parse(data.replace(/&quot;/g, '"')) console.log(rdata) const input = document.getElementById('search_here') console.log(input) let filteredArr = [] input.addEventListener('keyup', (e)=>{ box.innerHTML = "" filteredArr = rdata.filter(store=> store['title'].includes(e.target.value)) console.log(filteredArr) if (filteredArr.length > 0){ filteredArr.map(store=>{ box.innerHTML += `<b>${store['title']}</b><br>` <------------------------------- Replace }) } else { box.innerHTML = "<b>No results found...</b>" } }) </script> I am trying to replace the innerHTML <b>${store['title']}</b><br> with <div class="col-4 mb-3"> <div class="card h-100"> <a href="{{item.get_absolute_url}}"> <embed src="{{ item.image.url }}" class="card-img-top" alt="..."/> </a> <div class="card-body"> <h5 class="card-title">{{ item.title }}</h5> <p class="card-text"> {% if item.description %} {{ item.description }} {% endif %} </p> </div> <div class="card-footer"> <small class="text-muted">{{ item.timestamp }}</small> </div> </div> </div> But the result is …