Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
segmentation fault while deploying django app using cpanel
I am having issues in deploying the Django app using cPanel. I am using Python 3.6 and Django 3.1, created my virtualenv, ran pip install -r requirements.txt inside my directory, configured my settings.py for production. After running python manage.py makemigrations, I am getting the following error OpenBLAS blas_thread_init: pthread_create failed for thread 32 of 56: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 33 of 56: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 34 of 56: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 35 of 56: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 36 of 56: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 37 of 56: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 38 of 56: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 39 of 56: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: … -
Safely move model from one app to another in django
How to move django models from one app to another without affecting any data? If possible, provide a step-by-step approach to it. -
datetime picker in django without using forms.py
I want to add a datetime picker input field in my django project. I found this tutorial that offers a few ways but all of them are using forms.py as following: from django import forms class DateForm(forms.Form): date = forms.DateTimeField( input_formats=['%d/%m/%Y %H:%M'], widget=forms.DateTimeInput(attrs={ 'class': 'form-control datetimepicker-input', 'data-target': '#datetimepicker1' }) ) But I am not using forms in my project. I am using the function views. I can't find an example of how to implement a DateTime picker in this way?! any help is appreciated. -
Check if Django model exists in an array
So, i have a set off models in my database. Now i have made a script to webscrape certan items form a website. Now i wanted to delete all items from my database which are deleted inn the website. So what i mean is if an item that i have webscraped is deleted inn the website i want to do the same in my database. How do i check for this using a loop? I was thinking of doing this: items = ItemModel.objects.all() for item in items: if item.tite not in webscrape_item[0]: item.delete Im checking based on the title and deleting if the title does not exist inn the webscrape array. -
django Login page does not load
I am trying to make a login page using built-in Django login features. I created a button on the main page, which should redirect the page to login.html where I can log in. Once I click on the button, the URL changes accordingly(http://127.0.0.1:8000/account/login/), but the page itself(login.html) would not load. Please regard the codes below. Codes for urls.py in the created app ''' from django.conf.urls import include, url from django.contrib import admin from mainApp import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^test/', views.test), url(r'^book/', include(('book.urls', 'book'), namespace="PB")), url('', views.mainIndex, name='mainIndex'), url('account/', include("django.contrib.auth.urls")), ] ''' Codes for settings.py ''' import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'mainApp', 'book', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) MIDDLEWARE = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'mainApp.urls' 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', ], }, }, ] WSGI_APPLICATION = 'mainApp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' LOGIN_URL = '/account/login/' LOGOUT_URL = '/account/logout/' LOGIN_REDIRECT_URL = '/' ''' Finally, this … -
How to deploy Django repository from Github to cpanel for automatic changes
I want to deploy my django website from github to cpanel for automatic update,I have managed to clone the repository in cpanel,The issue is that how do I deal with static files? as I know the static files settings are different from local development to a live server since in cpanel we have to keep them on the folder public_html.So how do I deal with this. -
error when saving data in admin user interface in django
when I enter data into the admin interface to an app in Django using sqlite3 database I got this error OperationalError at /admin/products/product/add/ no such table: main.auth_user__old -
django database is not saving data of contact from details which i have entered
I'm new to dajngo projects and I have created a blog which has app named as "blog".Everything went all right and I stuck at conatct from.when I sumbmit details in contact from and go to djando admin database the contact details are not saved here. This is my contact.html code <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <title>contact us</title> </head> {% load static %} <body style="background-image: url('{% static " img/contact.jpg" %}');background-size: cover;"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script> <div class="container my-3" style="padding:70px 0"> <h3>Contact Us</h3> <form method="post" action="{% url "contact" %}" > {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name='name' placeholder="Enter Your Name"> </div> <div class="form-group"> <label for="name">Email</label> <input type="email" class="form-control" id="email" name='email' placeholder="Enter Your Email"> </div> <div class="form-group" > <label for="name">Phone</label> <input type="tel" class="form-control" id="phone" name='phone' placeholder="Enter Your Phone Number"> </div> <div class="form-group" > <label for="desc">How May We Help You?</label> <textarea class="form-control" id="desc" name='desc' rows="3"></textarea> </div> <button style=" margin-top: 25px;" type="submit" class="btn btn-success">Submit</button> </form> </div> </body> </html> This is post_detail.html {% extends 'base.html' %} {% block content %} {% load crispy_forms_tags %} <div class="container"> <div class="row"> <div class="col-md-8 card mb-4 mt-3 left top"> <div …