Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Pass Input to URL
I want to make a search field in django. I have a database with books and want, that the user can write e.g. "3" in a field and than the URL should look like this: www.url.com/search/3 3 is the id How can I do that? btw. I already have this: www.url.com/book/3 but I want, that the user writes it in a input field :) -
Django Mttp how to access element of Jquery nestable
I've been trying to access Html Element with Jquery. I have nested category in Django and I want to update the parent of the menu with drag and drop. enter image description here HTML <div class="dd" id="nestable3"> {% load mptt_tags %} <ol class="dd-list" > {% recursetree menu %} <li class="dd-item dd3-item" data-id="{{ node.id }}" data-parent="{{node.parent.name}}" id="nestable-item"> <div class="dd-handle dd3-handle" ></div> <div class="dd3-content" id="nestedList">{{ node.name }}</div> {% if not node.is_leaf_node %} <ol class="dd-list" > {{ children }} </ol> {% endif %} </li> {% endrecursetree %} </ol> JQUERY $('.dd').nestable().on('change', function(e) { /* It should be write data-id and parent id */ }); -
How to save a form in a database (django)
I have a quiz. I have 2 pages, I create the questions and their answers on the first page and I put these questions on the second page, but I want these questions to have the Answer model input, i.e. each question has its own input. When I try to set a query with an Id in the view and the unsuitable Answer form to save does not work, it is not stored in the database. How do I save? models.py from django.db import models # Create your models here. class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE, related_name="questions") answer=models.CharField(max_length=100,blank=True) def __str__(self): return str(self.questin) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" class AnswerForm(forms.ModelForm): class Meta: model=Answer fields="__all__" views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question import random def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): form=AnswerForm questions=Question.objects.all() if request.method=="POST": instance=Question.objects.get(id=request.POST['i_id']) print(instance) form=AnswerForm(request.POST, instance=instance) if form.is_valid(): form.save() return render(request, "question/ans.html", {"form":form, … -
gunicorn: error: unrecognized arguments: myproject.wsgi:application
I am trying to deploy my django project. I am trying to use gunicorn and Nginx. While following this tutorial. I reached at setting up the gunicorn.service file at location /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=tk-lpt-0098 Group=www-data WorkingDirectory=/home/tk-lpt-0098/Desktop/myproject/myproject ExecStart=/usr/bin/gunicorn /usr/share/man/man1/gunicorn.1.gz --workers 3 --bind unix:/etc/systemd/system/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target Proceeding further, I then run the following two commands sudo systemctl start gunicorn sudo systemctl enable gunicorn Now by checking the status of the server using command sudo systemctl status gunicorn I am experiencing the following error gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Thu 2021-01-21 19:20:03 PKT; 38s ago Main PID: 967938 (code=exited, status=2) جنوری 21 19:20:03 noc-HP-ProBook-650-G1 systemd[1]: Started gunicorn daemon. جنوری 21 19:20:03 noc-HP-ProBook-650-G1 gunicorn[967938]: usage: gunicorn [OPTIONS] [APP_MODULE] جنوری 21 19:20:03 noc-HP-ProBook-650-G1 gunicorn[967938]: gunicorn: error: unrecognized arguments: myproject.wsgi جنوری 21 19:20:03 noc-HP-ProBook-650-G1 systemd[1]: gunicorn.service: Main process exited, code=exited, status=2/INVALIDARGUMENT جنوری 21 19:20:03 noc-HP-ProBook-650-G1 systemd[1]: gunicorn.service: Failed with result 'exit-code'. I am using ubuntu version Ubuntu 20.04.1 LTS I have tried changing working directory but did not work. I would really appreciate if anyone can help me out with this issue. -
How can I set up an SSL configuration in Namecheap for Angular deployed on GitHub Pages and Django deployed on App Engine
I am deploying my system, Angular frontend using GitHub and the whole backend in the Google Cloud Platform - App Engine, SQL, Elasticsearch etc. Https seems to be working properly between website and the client as I have checked in the GitHub settings Enforce HTTPS. However I am not sure whether I do a correct configuration between Angular app and my Django API which is deployed in the App Engine. Can anyone take a look at the configuration and confirm that everything is done correctly? I would like to do everything as safely as possible. User portal should be accessible from example.com and www.example.com and the Django API on App Engine from api.example.com and www.api.example.com. Besides maybe you have any additional safety tips or advice on what else I could do to increase protection? Namecheap: Google App Engine: -
How can I use an external API to authenticate user's login instead of Django's inbuilt authentication system?
I'm currently working as an intern in a company. I'm helping to create a software using Django for their company to use. This software requires login system. However, their company have an API endpoint which logins a user using user's email and password and returns an access token upon successful login. How can I make use of the API to login the user? I've tried to search online but couldn't find any solution to it. -
Different ordering fields for ViewSets actions
I have a viewset lets say TestingViewSet which has a default ordering field id. class TestingViewSet(viewsets.ReadOnlyViewSet): ordering = ('id',) But there as some custom action views that uses the super(TestingViewSet).list that i want to change the ordering field for them conditionally e.x def distinct_list(self, request): return super(TestingViewSet, self).list(request) Is there a way like to change the ordering field of function distinct_list only? -
Django - Create views and serialisers for table without model
I have a ManytoManyField in one of my model, Django automatically created a table in my database so there is no model for this table. Here is my code: class UserPortfolio(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class ExchangeConnection(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) portfolios = models.ManyToManyField(UserPortfolio, blank=True) Django automatically created a table called exchange_connection_portfolios in my database which is fine. But I don't know how to create DRF Serialisers and ViewSets without any model in my code. Do I need to create a model for the table ? -
How to code python script to run run existing task scheduler in Window
please recommend any python package that is pretty much the closest to do this task. or the previous questions are similar to my question. Please guide me to use library to run window task scheduler? I am going to use it to run the window task scheduler through the Django web application ? Or else , is there any package to do for this scenario? I would like you to guide sample code to do as the following requirement. My job has been created on Window task scheduler already My job is responsible for executing a python file. 2.I would like you to run the job of window task scheduler in view.py on the Django web application -
How to check that an instance detail is being oppened in django admin
Is there a possibility to check that an instance detail is being opened in django admin? An example with orders illustrates it well - imagine that there is a new order instance in a list display of order instances in django admin. (data come from outside django) The order model has the following field which is blank when the instance appears in the list; ProcessingPersonAdminId = models.IntegerField(verbose_name=_('Processing Person Admin Id'), db_column='ProcessingPersonAdminId', blank=True, null=True) What I need to do - first person (imagine from sales dep.) that clicks on this particular order instance to view its detail is assigned to it. Before it even displays so the field is already filled in with corresponding user data. I was thinking about signals but nothing is being saved or updated neither in admin nor in models or anywhere else. I would appreciate any hint on how to approach this task. Thank you in advance. -
Access manyTomany field (Label) from category class via subclass(Products) Category-> Products -> Labels
Here is the code of my models file: from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') name = models.CharField(max_length=255) price = models.DecimalField(decimal_places=2, max_digits=9) def __str__(self): return self.name class Label(models.Model): name = models.CharField(max_length=255) products = models.ManyToManyField(Product, related_name='labels') def __str__(self): return self.name Now I want to access manyTomany field i.e. Label from Category please help me Thanks in advance -
Pass file data from view to view in django
I have two views in django: def upload(request): if request.method == 'POST': form = UploadFileModelForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/') def select(request): return render(request=request, template_name='converter/select.html') And I would like to pass a file from one view to the other. Currently I am just saving the file and then reopening it, but that is not a very elegant solution. I would like to use the session data, but in django the session won't allow the storage of InMemoryUploadedFile. Is there any other solution to this that doesn't include a redirect, since I am using dropzone to upload files and that prevents you from redirecting from python. Combining the two views into one is also not possible. -
How do i put multiple groups in one database?
I'm trying to make a centralized clinic management system of a university that has multiple campuses using django and react. im having trouble making a database that contains all the campuses with each having their own unique collection of inventory and student records. -
How to add page count in the class of views.py without error [Django]
I have created a simple blog app using Django/Python. I have the following views.py code: from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post # Create your views here. #def home(request): # return render(request, 'home.html', {}) class HomeView(ListView): model = Post template_name = 'home.html' ordering = ['-published_date'] paginate_by = 9 class ArticleView(DetailView): model = Post model.post_view = model.post_view + 1 model.save() template_name = 'article.html' My models.py code looks as follows: from django.db import models from django.contrib.auth.models import User from django.utils import timezone from ckeditor_uploader.fields import RichTextUploadingField from ckeditor.fields import RichTextField import math # Create your models here. # https://stackoverflow.com/questions/29536180/django-blog-adding-published-date-field-to-new-posts-and-ability-to-login-as-non class Post(models.Model): title = models.CharField(max_length=300) keywords = models.CharField(max_length=300, default="default keywords") author = models.ForeignKey('UserProfile', on_delete=models.CASCADE) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField(auto_now_add=True, blank=False, null=False) language = models.ForeignKey('LanguageCategory', on_delete=models.CASCADE) image = models.ImageField(upload_to='blog_images/', default='blog_images/image.png') body = RichTextField(blank=False, null=False) post_view = models.IntegerField(default=0, null=False, blank=False) When I try to runserver I get the following error: ine 15, in <module> class ArticleView(DetailView): File "/PATH/views.py", line 17, in ArticleView model.post_view = model.post_view + 1 TypeError: unsupported operand type(s) for +: 'DeferredAttribute' and 'int' I am guessing that I am getting the aforementioned error because I am not updating the post_view of the Post class … -
django REST Framework - How to properly unittest a custom parser
I have been googling around for some time now and I still couldn't come up with a single match! I wrote a quite elaborate custom parser to convert the incoming data to match my serializer structure. I want to unittest this properly to be sure that it remains functional when changing or refactoring my code. But I don't know how! There are literally no example in the internet and just using it naive like this: def test_me(self): parser_class = MyFancyParser() parser_class.parse(stream={'id': 27, 'other_data': 117}) ... is not working because it requires a stream and not a data dictionary. Any ideas on the topic? Thanks in advance! -
Modify pop up iframe google calendar
I have an iframe on my web page to display google calendar. I am using django and it correctly shows me the events that I create. I've been looking for several days, but I can't find a way to modify the pop up that the iframe generates when you select an event. Let's see if someone can give me some ideas on how to do it or where to look. A greeting. -
Django Channel - Nginx cannot connect to websocket
I've been stuck for days just to find a way to fix this problem. Why my Nginx can't connect to WebSocket? and always get these errors on the console: WebSocket connection to '<URL>' failed: WebSocket is closed before the connection is established. or WebSocket connection to 'wss://domain.com/virtualexpo/' failed: Error during WebSocket handshake: Unexpected response code: 404 Here's my Nginx setup looks like: upstream projectname { server localhost:9001; } upstream uvsock { server 127.0.0.1:6379; # server unix://var/run/supervisor.sock; } server { server_name domain.com www.domain.com; sendfile on; charset utf-8; client_max_body_size 20M; client_body_buffer_size 80M; client_body_timeout 50; location /ws/ { proxy_pass http://uvsock; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header Host $host; } location / { proxy_pass http://projectname; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header X-Forwarded-Proto https; proxy_redirect off; ... } location /static { alias /home/username/server/vier/staticfiles; } location /media { alias /home/username/server/vier/media; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.domain.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = domain.com) { return 301 https://$host$request_uri; } # managed by … -
Get N recent objects from multiple models at one place in Django
I'm working on a project using Python(3.7) and Django(3) in Which I have created 4 models, for example, A, B, C, and D. All of these models are strong in any kind of report. Now on the home page, I need to display 10 recent reports from all of these models. how Can I achieve that? These models don't have any foreign Key to each other. -
How to know when all m2m operations are completed in Django
The m2m_changed send me a unique signal when every single action (add or remove related record) is completed with the action "post_add", "post_delete" or "post_clear". May I know when ALL (not just one) the add/remove/clear action are completed with a single signal in django? -
Python function call vs database query (django ORM) overhead
While working in a Django project, when I see that I can reduce a database query for some cases if I use a function call (e.g datetime.today()) I opt for that to get more efficiency cause as far as I know, database query is the most expensive operation in a production environment. Am I right about this? Think of a postgres database with hundred thousands of records, I use the datetime.today() function and check if it is today, if not then don't run the database query (filter exists() query). Doing the database query all the time serves my logical purpose too, but I'm adding the datetime function call only for efficiency purpose as doing the query only for today is enough for this case. This bit of code is inside a loop. Will this approach be more efficient than simply doing the database query all the time? -
How to make Tinder-like swipe cards in django/Ajax?
I am making simple dating app with django, and I am planning to do a simple cards similar to these in tinder app, I am totally new in web dev and here's my question: From my django view I am planning to pass few user objects in dictionary, and how could I show one of them, and if user would like/remove this user's card show the next one from this dict? Should I do this in ajax? And if so, how could I do this? -
How to create a response for a Ajax query to a Django View such that the objects can be iterated in the template
I have the following ajax function in my view def load_parts(request): machinery_group_id = request.GET.get('machinery_group') parts = MachineryPart.objects.filter(machinery_group =machinery_group_id) return HttpResponse(parts) I am trying to iterate to this response in my template using $.ajax({ url: url, data: { 'machinery_group': groupId }, success: function (parts) { alert(typeof parts) {% for part in parts %} //Do Something here {% endfor %} I the View, I have tried Serialising parts using serializer and return a JSON, Return the parts query set as a value()/value_list(), with and without serialising Just return the parts as is. In each case, the typeof is a string, and I am unable to iterate over the parts returned in the template to get the individual part objects. Any help would be appreciated. Thanks a lot!!! -
Link correctly to index.html in Python Django
I have a Python Django project with the following files. proj1/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('website.urls')), ] proj1/website/views.py from django.shortcuts import render def index(request): return render(request, 'index.html', {}) proj1/website/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), ] Under proj1/website/templates I have a few .html files. How do I link to those in my .html files? I have currently the following written in index.html <a href="index.html">Home</a> I get error message when I press the link for the index.html though. Page not found (404) Request Method: GET Request URL: http://localhost:8000/index.html Using the URLconf defined in leam.urls, Django tried these URL patterns, in this order: admin/ [name='index'] The current path, index.html, didn't match any of these. What am I doing wrong? Do I need to specify where the index.html is located with a full path, or what is wrong here? The index.html loads with run manage.py. -
Django admin site login error -"This site can’t be reached127.0.0.1 refused to connect."
I am developing a web app using Django 3.0.1 and python 3.7 for my college's final year project. Whenever I try to login to the admin page in the local host in google chrome, link "127.0.0.1/admin/" I got error saying "This site can’t be reached 127.0.0.1 refused to connect. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED" I know this may not be due to wrong username and password. I have done lots of research on this topic but couldn't find a solution. I have found that updating python version would solve this problem but haven't tried that one cause I have been developing other projects in the same version. I have checked my pcs setting on proxy site that is also fine. But changing anything did not work. So, if anyone can answer this problem it would help me a lot. And thankyou in advance. -
Can't insert Title of Category in HTML with Django
I want to display only the title of my Django Category in HTML, but don't know how to access it properly. My views.py looks like this: def category_products(request,id,slug): products = Product.objects.filter(category_id=id) category = Category.objects.all() context={'products': products, 'category':category, 'slug': slug} return render(request,'sondermuenz/category_products.html',context) The model class Category(MPTTModel): title = models.CharField(max_length=200) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') slug = models.SlugField(unique=True) def __str__(self): return self.title class MPTTMeta: order_insertion_by = ['title'] def __str__(self): full_path = [self.title] k = self.parent while k is not None: full_path.append(k.title) k = k.parent return ' -> '.join(full_path[::-1]) class Product(models.Model): title = models.CharField(max_length=120) description = models.TextField(blank=True,null=True) image = models.ImageField(....) ... The urls: path('products_13/<int:id>/<slug:slug>', views.category_products_13, name='products_13'), When I insert in my html file this <h1>{{ slug }}</h1> I can show the passed in slug, but how can I display the title of the model? If I loop through it will show the same amount of titles as the looped objects, but I want to display it only once. I hope someone can help. Thank you.