Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting the homepage data refresh every time user refresh or login in django
How can I change the data of my homepage while refreshing every time or login into Django using machine learning? I have made the model that can recommend using movie_datasets which recommend the movie but I don't know how can I implement it in Django how and to make it dynamic every time while a refreshing or new user is logged in and showing the title of the movie using bootstrap. -
CSRF_Token in POST method using Vue.js and Django Rest Framework
I'm trying to send a POST request from a Vue.js template to my API created with Django. When sending I get a 403 CSRF token missing or incorrect error. Since I separated the front and the back, I don't have a view with {csrf_token} on the Django side. How do I send my form? I tried some exemples on the web using cookies but i'm beginners and need more explaination about the POST subject and CSRF -
Django:What is best way to import my Custom-User in views.py?
Actually i have created my own custom-user (MyUser) in models.py from django.db import models from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): country=models.CharField(max_length=20) settings.py AUTH_USER_MODEL = 'new_user.MyUser' I created a simple function in views.py to create new users. from django.shortcuts import render,redirect from django.http import HttpResponse from django.contrib.auth import get_user_model from django.conf import settings def save_account(request): MyUser=get_user_model() if request.method == "POST": name=request.POST.get("name") email=request.POST.get("email") password1=request.POST.get("password1") password2=request.POST.get("confirm-password") country=request.POST.get("country") new_user=MyUser.objects.create_user(username=name,email=email,password=password1,country=country) new_user.save() return redirect('/') else: return HttpResponse("404 Not Found") 1. Here i use get_user_model() function to get my currently custom-user. 2. I have second option to get my custom user just by importing MyUser model from models.py and then use it. from .models import MyUser 3. I have third option to get custom-user just by importing AUTH_USER_MODEL directly from settings.py and use it like in this way. from django.conf import settings MyUser=settings.AUTH_USER_MODEL but third option returning a string instead of returning my custom-user.but why? I just want to know that which option is best to import custom-user in views.py and why? -
How to change title for the tab of change list page of django admin
I'm working on Django and wanted to change the default title for the tab of change list page of Django admin as marked in the pic : my admin.py file is : from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): change_list_template='change_list_form.html' change_form_template = 'change_form.html' add_form_template='add_form.html' list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So is there any way so that it can be changed?? Thanks in advance!! -
one to many or many to many relationship in DJANGO
I wanna try to build a relationship between an employee and an area. Each employee has to visit more than one area and the area depends on the city. I built a relationship between city and area with a foreignkey(many-to-one). I have to add more than one areas to single employee however, I used manytomany relationship between employee and area. At the time of employee registration when I select city from "City" dropdown the list of the area is not altered. All the areas are shown. This is my Employee form class EmployeeForm(forms.ModelForm): class Meta(): model =Employee fields = ('code','first_name','last_name','designation','report_to','join_date','leave_date','city','area','username','password','status','address') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['area'].queryset = Area.objects.none() if 'city' in self.data: try: city_id = int(self.data.get('city')) self.fields['area'].queryset = Area.objects.filter(city_id=city_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['area'].queryset = self.instance.city.area_set.order_by('name') and models are class Employee(models.Model): code = models.CharField(max_length = 256) # name = models.CharField(max_length = 256) designation =models.ForeignKey(Designation,on_delete=models.CASCADE) report_to = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) area = models.ManyToManyField(Area, through ='EmployeeArea',) city = models.ForeignKey(City, on_delete=models.CASCADE, null=True, blank=True,) status = models.BooleanField(default = True) join_date = models.DateField(default=datetime.datetime.now) leave_date = models.DateField(blank = True, null=True) username = models.CharField(max_length = 256) password = models.CharField(max_length = … -
Ngnix redirect for Mouseflow to remove Django staticfiles MD5 hash
Mouseflow recordings issue I have an issue with Mouseflow and the way that it displays "recordings". Mouseflow recordings capture and store the mouse movement of users at a particular time, and also the HTML of the page that they were interacting with. However, Mouseflow does not store the associated static assets that the site uses, such as CSS, JavaScript, or image files such as logos, icons etc. - these are loaded again at the time the recording is played back via the Mouseflow admin panel. Django static assets Apart from CMS-generated media (such as uploaded images and documents), Django's static file assets are collected each time there is a new code deployment, and processed to add MD5 hashes to the end of the filename, preceding the file extension. Example static file URL before processing: https://example.com/assets/css/screen.min.css Example static file URL after processing: https://example.com/assets/css/screen.min.87f74c1e97de.css When Mouseflow generates a recording, the HTML refers to the static asset filenames at the time of the interaction. If a recording is viewed at a later date and the static assets have been changed and re-deployed, the filenames will no longer exist. This issue is documented here on the Mouseflow support site. As suggested in the support … -
How filter queryset by multiple ID
My objective is to get the id and make a queryset filtered by id, as in the following code: view.py class CustomViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = product.objects.all() def list(self, request, *args, **kwargs): products = self.queryset orders = order.objects.all() order_serializer = OrderSerializer(orders, many=True) product_serializer = self.get_serializer(products, many=True) custom_response = [order_serializer.data, product_serializer.data] return Response(custom_response, status=status.HTTP_200_OK) urls.py from django.urls import path, include from list import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'all', views.CustomViewSet, basename='product') urlpatterns = [ path('', include(router.urls)) ] in this code there are two mode and two serializer class in one one viewset my task is how to get all data by id using one api hit -
Automatic publication of a post
In my blog I've a filter that put online only the posts that aren't draft and that aren't published in the future. models.py class BlogPost(models.Model): title =.... .... publishing_date = models.DateTimeField( default=timezone.now, ) draft = models.BooleanField( default=False, ) views.py @api_view(["GET"]) def blogPost_apiview(request): if request.method == "GET": objects = BlogPost.objects.filter(Q(draft=False) & Q(publishing_date__lte=datetime.now())) serializer = BlogPostSerializer(objects, many=True) return Response(serializer.data) I've seen that when the post goes from future to past it is not put online. I can see the post online only if I change manually the publishing date and time and save it. How can I make it happen automatically? -
RESTful API filter data by list of filters
I am creating a RESTful API to return a lot of data. Now I want to filter this data by the selected filters from a list. There are more than 150 options. The user can select the filters link this: My question is, how can I apply those filters without having 150+ if statements. The downside of the database is that those filters are not stored directly in the database but are defined by a set of numbers. I hope anyone can help me by finding the best practice. I am creating the API with Django with Rest framework -
resizing images to load faster in django
Hi everyone i'm working in a blog project in django framework where you can upload images and text. I have 30 images uploaded and the page takes 2234kb for most of its images when loading and all the images are loading at the same time. So when my users hit the page (the post list page) load all the images and its make the page slower. If anyhow i could load, not all the images, but a typically 20 images at a time when they are loading and rest images will be loading when the user scroll the page. is there anything how to do it i'm using html template in django. please help me. -
how to fullfil this requirement with wordpress and python
I have a running blog build with wordpress and I can add a new page with a button which I hope to upload an image. After receive this image, I hope it can be proceed by AI programe(Python) running in the background. how to fullfil this requirement, anybody can help me to achieve that? Or we can use Django/Flask to act as the front end web, and AI(python) work in the back end? -
Using docker secrets without swarm
I recently went trough a nextcloud deployment and I saw at the nextcloud docs that I could use docker secrets without a docker-swarm setup it seems: https://hub.docker.com/_/nextcloud/ -> Docker Secrets Now I have Integrated secrets into my docker-compose file like so: secrets: mariadb_password: file: secrets/mariadb_password.txt services: app: build: .... environment: MYSQL_PWD: /run/secrets/mariadb_password But currently it seems that my application does not use the content of /run/secrets/mariadb_password instead it uses the path to the file and not the content of it. This is how I currently load my mariadb config at my Django application: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", }, 'NAME': env.str('MYSQL_DB'), 'USER': env.str('MYSQL_USER'), 'PASSWORD': env.str('MYSQL_PWD'), 'HOST': env.str('MYSQL_HOST'), 'PORT': env.str('MYSQL_PORT'), } } I also have read at the nextcloud docs that: As an alternative to passing sensitive information via environment variables, _FILE may be appended to the previously listed environment variables, causing the initialization script to load the values for those variables from files present in the container. Do I need to write a initialization script myself? If so, is there a pratical example to do this? thanks in advance -
How to retrieve a GenericRelation data using single query in Django
My aim is to retrieve a GenericRelation data using single query & without use of for loop. Example: I have Customer model & Address model from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models class Customer(models.Model): name = models.CharField(null=False, blank=False, max_length=255) email = models.EmailField(null=False, blank=False, unique=True) address = GenericRelation(Address) class Address(models.Model): address1 = models.CharField(max_length=255) address2 = models.CharField(max_length=255) content_type = models.ForeignKey(ContentType, null=True, blank=True, on_delete=models.DO_NOTHING) object_id = models.PositiveIntegerField(null=True, blank=True) content_object = GenericForeignKey('content_type', 'object_id') Bellow is the traditional way i archive GenericRelation data result = [] customer1 = Customer.objects.filter(pk=1) customer1_obj = Customer.objects.get(pk=1) address_of_customer1 = customer1_obj.address.all() result.append({'customer_data': customer1.values(), 'address_data': address_of_customer1.values()}) print('---result---', result) ---result--- [{'customer_data': <QuerySet [{'id': 1, 'name': 'Aakash', 'email': 'aakash@g.com'}]>, 'address_data': <QuerySet [{'id': 2, 'address1': 'Flat 1-2', 'address2': 'Road 1-2', 'content_type_id': 18, 'object_id': 1}, {'id': 1, 'address1': 'Flat 1-1', 'address2': 'Road 1-1', 'content_type_id': 18, 'object_id': 1}]>}] But this is not Good solution. Take too much time when ids is in thousands of range. If is there any other way to archive those data. Then please give your solution in comments.. Note: Make sure your query result get customer & address data in one result. without use of for loop. -
django.core.exceptions.ImproperlyConfigured and TypeError: 'module' object is not iterable
I have a very annoying problem. There was an errors in the project I am creating: django.core.exceptions.ImproperlyConfigured: The included URLconf 'My_Site.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. and TypeError: 'module' object is not iterable views.py: class UserRegisterView(View): def get(self, request): form = UserCreationFormv2() return render(request, "registrationReg.html", {'form': form})` def post(self, request): form = UserCreationFormv2(request.POST) if form.is_valid(): user = form.save() login(request, user, backend='django.contrib.auth.backends.ModelBackend') UpdateUser.objects.create(user=user) else: return render(request, "main.html") urls.py: from django.contrib import admin from django.urls import path from MySite.views import OrganizationRegisterView, UserRegisterView urlpatterns = [ path('', OrganizationRegisterView.as_view(), name='Organizators Registration'), path('/user', UserRegisterView.as_view(), name='Regular User Registration') ] probably, there is some mistake in my code, but i cant see it -
Trouble installing django-heroku
I am trying to deploy my django application to heroku When I try and; '''pip install django-heroku''' It gives me this error; ''' ERROR: Command errored out with exit status 1: command: /Users/huntermackenzie/Dev/personal/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/15/k9lcjv5129v661mkkrsdt09w0000gn/T/pip-install-v2fvrgwp/psycopg2/setup.py'"'"'; file='"'"'/private/var/folders/15/k9lcjv5129v661mkkrsdt09w0000gn/T/pip-install-v2fvrgwp/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/15/k9lcjv5129v661mkkrsdt09w0000gn/T/pip-install-v2fvrgwp/psycopg2/pip-egg-info cwd: /private/var/folders/15/k9lcjv5129v661mkkrsdt09w0000gn/T/pip-install-v2fvrgwp/psycopg2/ Complete output (23 lines): running egg_info creating /private/var/folders/15/k9lcjv5129v661mkkrsdt09w0000gn/T/pip-install-v2fvrgwp/psycopg2/pip-egg-info/psycopg2.egg-info writing /private/var/folders/15/k9lcjv5129v661mkkrsdt09w0000gn/T/pip-install-v2fvrgwp/psycopg2/pip-egg-info/psycopg2.egg-info/PKG-INFO writing dependency_links to /private/var/folders/15/k9lcjv5129v661mkkrsdt09w0000gn/T/pip-install-v2fvrgwp/psycopg2/pip-egg-info/psycopg2.egg-info/dependency_links.txt writing top-level names to /private/var/folders/15/k9lcjv5129v661mkkrsdt09w0000gn/T/pip-install-v2fvrgwp/psycopg2/pip-egg-info/psycopg2.egg-info/top_level.txt writing manifest file '/private/var/folders/15/k9lcjv5129v661mkkrsdt09w0000gn/T/pip-install-v2fvrgwp/psycopg2/pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.''' Then I try and; '''pip install psycopg2''' And I get the same error. Can someone please help me. Thank you. -
how to make edit functionality by using django form
I have two models parent and child models and they have relationship to each other it means that a child can have a parent,and then i have this template which i pass a child id on it that will display edit fields for parent, the problem that i face is that,i can see the form fields into the template but there is no value on it that will help me to edit here is my child model from django.db import models class Child_detail(models.Model): Firstname = models.CharField(max_length = 50) Lastname = models.CharField(max_length = 50) def __str__(self): return self.Firstnam here is my parent model class Parent(models.Model): child = models.ForeignKey(Child_detail,on_delete=models.CASCADE) Parent_firstname = models.CharField(max_length = 100) Parent_lastname = models.CharField(max_length = 100) Current_address = models.CharField(max_length = 100) def __str__(self): return str(self.Parent_firstname) here is my views.py file for editing parent details def edit_parent(request,pk): child=get_object_or_404(Child_detail,pk=pk) form=ParentForm(request.POST) if form.is_valid(): form.instance.child=child form.save() return redirect('more_details',pk=pk) else: form=ParentForm() context={ 'form':form, 'child':child } return render(request,'functionality/parents/edit.html',context) here is form.py file class ParentForm(forms.ModelForm): class Meta: model=Parent fields=['Parent_firstname','Parent_lastname','Current_address','Phone_number','Parent_job', 'Life_status','Other_parent_name','Other_parrent_phone_number'] labels={ 'Parent_firstname':'Parent Firstname','Parent_lastname':'Parent Lastname', 'Other_parent_name':'Other Parent Name', 'Current_address':'Current Address','Phone_number':'Phone Number', 'Other_parrent_phone_number':'Other Parent Phone Number', } and here is my template {% extends 'base.html' %} {% block content %} <form action="" method="post" autocomplete="on"> {% csrf_token %} <div … -
Dynamic Allowed Host in Django
I'm developing multitenant application using django. Every things works fine. But in the case of ALLOWED_HOST , I've little bit confusion, that how to manage dynamic domain name. I know i can use * for any numbers for domain, But i didn't wan't to use * in allowed host. Here is my question is there any way to manage allowed host dynamically. -
Author of the post is not set to current logged in user
I created this simple model: class FormModel(models.Model): fullname = models.CharField(max_length=150) slug = models.SlugField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) I passed blank=True and null=True so that it can pass form_valid condition. and then set the author of the current post to current logged in user, but sounds I am making a mistake here. Can anyone help. Here is how the views looks like: def FormsView(request): if request.method == 'POST': form = FormsProject(request.POST, request.FILES) if form.is_valid(): form.save(commit=False) form.author = request.user.username print(form.author) form.save() return HttpResponse("Success") else: form = FormsProject() context = { 'form': form, 'user': request.user.username } return render(request, 'forms_project/forms.html', context) Thank You -
How to display Data from two model without creating new model in Django?
I have two models with one common field (email). I using viewset.ModelViewset to list and create data in both the models. My models.py: class Schema(models.Model): """Database model for Schema """ name= models.TextField() version = models.TextField() email = models.EmailField(unique = True ) def __str__(self): return self.email class Status(models.Model): """ Model For status """ email = models.EmailField(unique = True ) status = models.TextField() def __str__(self): return self.email my view.py: class StatusViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): queryset = models.Status.objects.all() serializer_class = serializers.StatusSerializer class SchemaViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): queryset = models.Schema.objects.all() serializer_class = serializers.SchemaSerializer I want to overide List function of Status Viewset to display entire detail of that user. For ex: from schema viewset i have created : { "id": 1, "name": "Yatharth", "version": "1.1", "email": "yatharth@test.com" } and From Staus viewset i have POST the status of Email: yatharth@test.com to Active. From GET of Status VIewset I want to display data like this: { "name": "Yatharth", "version": "1.1", "email": "yatharth@test.com" "status": "Active" } How to do this? -
I need to run Shell Script using django in side a Docker container
my shell file #!/bin/bash echo "Success" exit 1 I called the above file using following command. python file subprocess.call(["bash", "scripts/test.sh"], shell=True) This works fine when running without the Docker container. But it shows an error when running inside the container. Can anyone help me? -
blog_index() missing 1 required positional argument: 'body'
Hi I'm a newbie in django framework and I got an error like this blog_index() missing 1 required positional argument: 'body' this is my code: views.py def blog_index(request,body): body = Post.objects.get(body) posts = Post.objects.filter(body=body) form = ProfileForm(instance=posts) context = {"posts": posts, 'form': form} return render(request, "blog_index.html", context) I want to get data body from post , how to make it possible? Thanks. -
Django Deploy to heroku: Application Error
I deployed my Django project to heroku. It deployed successfully but the page shown Application error. In logs on heroku error be like this. 2020-04-24T05:34:09.500250+00:00 app[web.1]: [2020-04-24 05:34:09 +0000] [4] [INFO] Using worker: sync 2020-04-24T05:34:09.506988+00:00 app[web.1]: [2020-04-24 05:34:09 +0000] [10] [INFO] Booting worker with pid: 10 2020-04-24T05:34:09.532649+00:00 app[web.1]: [2020-04-24 05:34:09 +0000] [11] [INFO] Booting worker with pid: 11 2020-04-24T05:34:10.051702+00:00 heroku[web.1]: State changed from starting to up 2020-04-24T05:34:20.000000+00:00 app[api]: Build succeeded 2020-04-24T05:34:26.126726+00:00 app[web.1]: [2020-04-24 05:34:26 +0000] [4] [INFO] Shutting down: Master 2020-04-24T05:34:41.808971+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=GET path="/favicon.ico" host=dashboard-retail.herokuapp.com request_id=f5feaeba-075f-4dc7-a637-fe6b271f0d67 fwd="125.24.11.115" dyno=web.1 connect=1ms service=30003ms status=503 bytes=0 protocol=https 2020-04-24T05:34:42.096139+00:00 app[web.1]: [2020-04-24 05:34:42 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:10) In Procfile,I set like this web: gunicorn myWeb.wsgi --log-file - -
How to add dynamic URLs for different cities of a country Django-leaflet
I have a shapefile of a country on districts level. I want every district to be clickable on shapefile on Leaflet (Django) and get to another URL where it shows stats of that city or district on another page. How can I set dynamic URLs like each district have a unique id so URL will be based on id? I don't know how to get this process done. -
Count forengkey django rest framework?
When I count the likes i got all the count from database. I would like to count only the likes related with an article class ArticleSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) comments = CommentSerializer(read_only=True, many=True) likes = serializers.SerializerMethodField(read_only=True) class Meta: model = Article fields = "__all__" def get_likes(self, value): return Vote.objects.select_related('article').filter(value=True).count() -
Getting the selenium scraping script output in web browser using django?
I had wrote a script for scrapping the data of all the matches that are being shown in this url https://web.bet9ja.com/Sport/OddsToday.aspx?IDSport=590 the script which I wrote is scrape.py import selenium.webdriver from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import mysql.connector import pymysql from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # the relevant url url = 'https://web.bet9ja.com/Sport/OddsToday.aspx?IDSport=590' # the driver path driver = webdriver.Chrome(r"c:/Users/SATYA/mysite/chromedriver") driver.get(url) driver.implicitly_wait(10) # seconds buttons = WebDriverWait(driver,15).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.Event.ng-binding"))) for btn in range(len(buttons)): #elements re-assigned again to avoid stale. buttons = WebDriverWait(driver, 15).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.Event.ng-binding"))) buttons[btn].click() headings= [item.text for item in driver.find_elements_by_css_selector("div.SECQ.ng-binding")] keys = [item.text for item in driver.find_elements_by_css_selector("div.SEOdd.g1")] values = [item.text for item in driver.find_elements_by_css_selector("div.SEOddLnk.ng-binding")] driver.execute_script("window.history.go(-1)") print(headings,keys,values) when I run this script in console using python scrape.py then I am getting output i.e scraping all the matches values dynamically now I actually I tried this script in django views.py and want to show the output in web page for that I wrote code like this views.py from django.shortcuts import render from django.http import HttpResponse import selenium.webdriver from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as …