Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - How can I prevent a tenant from accessing an app in my django project
I'm using Django-tenant-schemas for a multi-tenancy application. I'm trying to limit the access of some tenants to some apps based on subscription options. Is there a way to prevent a specific tenant from accessing a specific app in the project. -
How to run a external python script that is run infinitely in Django and print all the outputs in html?
I have a python script that in an infinite loop get some data from a URL and saves it in a database. it prints some logs and sometimes it throws some errors. my script is as follow: dbclient = MongoClient('127.0.0.1') db = dbclient.shell while True: url = "http://example.com/api" print("request has been sent====================") response = requests.get(url).json() print("data has been downloaded====================") db.api_backup.insert_many(response) print("data has been saved in MongoDB====================") Now, I have created a Django project for monitoring. So, I want to able to start and stop it by a button on an Html page and see its status and outputs(like what is seen in the terminal). It should be noted that this script is independent of Django and is running in the background when Django is not running, and when I go to the Monitoring page, its status will be displayed on the page. I have no idea how to do it. thanks in advance. -
Django zappa application's modular path to app's function? Don't know which one it is
I'm new to django and aws and I'm trying to get my project deployed. I have a similar filestructure as in the project here: https://github.com/divanov11/crash-course-CRM/tree/Part-8---data-to-templates-and-template-tags/crm1_v7_database_queries Now when I'm initializing zappa and they ask "What's the modular path to your app's function?" I have no idea which path I should put. Could anyone help me with this? -
add utf-8 encoding to postgresql - postgis extension for django (UnicodeDecodeError)
i've created a database in postgresql with the following command create database "gisdb" with owner 'geo_user' encoding 'UTF8' LC_COLLATE='C.UTF-8' LC_CTYPE = 'C.UTF-8' TEMPLATE template0; my locale-a are just found C, C.UTF-8 and POSIX , after locale-gen en_US.UTF-8 this is my seetings.py file in django-python DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'db_name', 'PASSWORD': 'pass', 'USER': 'user', 'PORT': '5432', 'HOST': 'localhost', } } postgresql version : 10 makemigrations and migrate worked fine and created the tables , but when i try to run runserver the output is A server error occurred. Please contact the administrator. and in the terminal ubuntu subsystem it raise this error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb1 in position 233732: invalid start byte -
How do I integrate oscar's product render template tags with my own template?
I am developing an ecommerce website with the help of django-oscar. I decided to use the template tags and dashboard of oscar while trying to only change the templates with my own. I am sorry that the description of the question is so long but I assume you would need to understand my work process to understand the problem. In the description below, I start with my basic settings and template integration and work my way to the catalogue.html which is where I am facing the problem. My main problem statement is in bold I have forked the oscar's catalogue app with my own. Right now my settings.py looks like this: # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates/local') OSCAR_TEMP_DIR = os.path.join(BASE_DIR, 'templates/oscar') TEMP_DIR = os.path.join(BASE_DIR, 'templates') STATIC_ROOT = os.path.join(BASE_DIR,'allstatic') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env'),] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', #Custom Made Apps 'appdir.catalogue.apps.CatalogueConfig', #Oscar Apps 'oscar', 'oscar.apps.analytics', 'oscar.apps.checkout', 'oscar.apps.address', 'oscar.apps.shipping', # 'oscar.apps.catalogue', 'oscar.apps.catalogue.reviews', 'oscar.apps.partner', 'oscar.apps.basket', 'oscar.apps.payment', ... ] SITE_ID = 1 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR, OSCAR_TEMP_DIR, TEMP_DIR], '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', 'oscar.apps.search.context_processors.search_form', … -
Problem loading static content to Web App using Django
I have difficulty displaying static content in my web, I can't figure out where's the issue Here's my browser enter image description here this is my settings.py file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,"templates") STATIC_DIR = os.path.join(BASE_DIR,"static") ..... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'first_app', ] .... STATIC_URL = '/static/' STATICFILES_DIR = [ STATIC_DIR, ] views.py file: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index (request): my_dict={'insert_me':"Hello I am from views.py!"} return render(request,'first_app/index.html', context=my_dict) url.py file: from django.conf.urls import url from first_app import views urlpatterns=[ url(r'^$', views.index, name='index') ] and my templates file: <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Django Page</title> </head> <body> <h1>Hi this is a picture from Zakopane</h1> <img src= "{% static "images/picture1.jpg" %}" alt="Picture not found"> </body> </html> I get an error saying ""GET /static/images/picture1.jpg HTTP/1.1" 404 1683" on the terminal. Would appriciate any help Thank you in advance! -
I have set all settings for CORS but it blockes APIs when I'm using VPN, it allows when VPN is off
I have a website with django, nginx and gunicorn. settings.py: INSTALLED_APPS = [ 'corsheaders', ... ] ... MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] ... CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = ['DELETE','GET','OPTIONS','PATCH','POST','PUT'] and for nginx: location / { add_header 'Access-Control-Allow-Origin' '*' always; } when I use the website without VPN, it will be loaded. when I activate VPN it raises this error: Access to XMLHttpRequest at '' from origin 'front\url' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. how can I solve this issue and see my website with and without VPN? -
$ is not defined error in jquery and javascript
For many days I am making a big django project.For the project I needed jquery. linked many jquery recources.I even kept the jquery file near my templates folder. But an error is coming: Uncaught ReferenceError: $ is not defined I looked for it on google,youtube,on this site and many other sites.But I can't find the solution. <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <!--<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>--> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src='templates\jquery-3.5.0.min.js' -
Django annotate with related_name from A->C where A->B and B->C where '->' is reverse relationship
I searched a lot on internet but could not find a similar question. I have 3 models : Domain, Topic, Post Each Domain can have many Topics and each Topic can have many Posts. Topic has a foreign key to Domain and Post has a foreign key to Topic. So I can include count of Posts in Topic by annotate(Count('posts')) and I can include count of Topics in Board by annotate(Count('topics')) Is there any way to include count of Posts in Board by annotate ? -
Error with setting DJANGO_SETTINGS_MODULE variable while running debug in PyCharm
I am trying to run my project in PyCharm to debug it but i get this error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I know there have been lot of discussion in stackoverflow and on internet about this topic a lot and i have carefully read through django docs many times now https://docs.djangoproject.com/en/dev/topics/settings/. I have tried next. Also my project is called 'fitex', so i use it as 'mysite': 1)Setting environment variables in my shell as so: set DJANGO_SETTINGS_MODULE = fitex.settings 2). Tried also in shell: export DJANGO_SETTINGS_MODULE=fitex.settings 3). Tried in shell something like this: from django.conf import settings, from fitex import settings, settings.configure(default_settings=settings, DEBUG=True) unfortunately, didn't work. Error: AttributeError: module 'fitex.settings' has no attribute 'configure' 4)Tried adding in my settings.py file: os.environ['DJANGO_SETTINGS_MODULE'] = 'fitex.settings' Also my debug configurations: screenshot Maybe someone is able to help out, thanks! -
login_required and logout is not working in django
here's my views.py from django.shortcuts import render, get_object_or_404,redirect from .models import Post,Author from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate,get_user_model,login,logout from .forms import UserLoginForm,UserRegisterForm def login_view(request): next = request.GET.get('next') form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request,user) if next: return redirect(next) return redirect('/') context = { 'form': form, } return render(request, "login.html", context) def register_view(request): next = request.GET.get('next') form = UserRegisterForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get('password') user.set_password(password) user.save() new_user = authenticate(username = user.username, password = password) login(request,user) if next: return redirect(next) return redirect('/') context = { 'form': form, } return render(request, "signup.html", context) def logout_view(request): logout(request) return redirect('/') @login_required def home(request): return render(request,"home.html", {}) def posts_list(request): all_posts = Post.objects.all() context = { 'all_posts': all_posts } return render(request,"post_list.html",context) def posts_detail(request, slug): unique_post = get_object_or_404(Post, slug=slug) context = { 'post': unique_post, } return render(request,"posts_detail.html",context) and my url.py is from django.contrib import admin from django.urls import path from posts import views urlpatterns = [ path('admin/', admin.site.urls), path('login/', views.login_view), path('signup/', views.register_view), path('logout/', views.logout), path('', views.home), path('post/',views.posts_list), path('post/<slug:slug>/', views.posts_detail,name='post'), ] so,the problem the home.html directly redirected without going form login route and the logout function is not workig i am … -
How to add a 'new' button for a ForeignKey in a modelForm
I want to add a 'NEW' button for a ForeignKey in ModelForm just like in admin area, here is my medical_report model class Medical_report(models.Model): Immunisation = models.ForeignKey(Immunisation, on_delete=models.DO_NOTHING) Name_of_examining_health_officer = models.CharField(max_length=50) Name_of_the_Health_facility = models.CharField(max_length=50) Date_of_medical_examination_of_child = models.DateField() def __str__(self): return self.Name_of_the_Health_facility Here is my Immunisation model class Immunisation(models.Model): Date_of_immunisation = models.DateField() def __str__(self): return str(self.Immunisation_type) And here is my form.py file class MedicalReportForm(forms.ModelForm): class Meta: model = Medical_report fields = 'Name_of_examining_health_officer','Name_of_the_Health_facility','Date_of_medical_examination_of_child','Immunisation' -
ModelForm is creating a new record inspite of providing an instance
I am creating a ToDo list where I can create a ToDo item and provide a button against each item to update it. I am using ModelForm to save my data to DB. The update button takes me to 'update.html' with the instance of selected task. But when I update the task information and click on 'Submit', it creates a new task with the updated information and does not update the same task. Please helo me, I am stuck. views.py from django.shortcuts import render, redirect from .models import Task from .forms import * def index(request): tasks = Task.objects.all() form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: context = {'tasks':tasks,'form':form} return render(request,'TaskList/list.html',context) def update(request, pk): task = Task.objects.get(id = pk) if request.method == 'POST': form = TaskForm(request.POST, instance=task) if form.is_valid(): form.save() return redirect('/') else: form = TaskForm(instance = task) context = {'task':task, 'form':form} return render(request,'TaskList/update.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name = 'list'), path('update/<str:pk>/', views.update, name = 'update') ] update.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form method = 'POST' action = ''> {% csrf_token … -
Python Django views .home dividing into sub classes
I'm trying to do a platform which is querying some data from different social media channels. My "Home" Class is now full of these queries and it takes up to 10 seconds to load the page. My question would be how I can divide the Home class into sub classes like this. Currently my code looks like this: def Home(Request): function1() function2() function3() function4() context{ query1: "query1", query2: "query2", query3: "query3", } return render(request, 'base.html', context) But I want to do like this: def Home(Request): function1() context{ query: "query" } return render(request, 'base.html', context) def Home-query2(Request): function2() context{ query2: "query2", } return render(request, 'base.html', context) def Home-query3(Request): function3() context{ query3: "query3", } return render(request, 'base.html', context) Other question would be, how can I first load the home class and then load each query all at the same time. So that I that load time totally is decreased. -
django.db.utils.OperationalError: no such table: Homepage_generalsettings
I am setting up git project to my local server. when I try to makemigrations, migrate, run. i get the following error: django.db.utils.OperationalError: no such table: Homepage_generalsettings i have installed sqlite as well. I am using django version 3. please help me to solve this problemscreenshot of error message -
How can i set my position at the first page in fiverr market place to get more orders?
I want to rank my fiver gig so that it appear in the first page and I get more orders. How can I rank this gig Python Programmer and Developer? -
Django:How to prevent non authorize users to access reset url to reset password?
reset url pattern url(r'^reset/$', auth_views.PasswordResetView.as_view( template_name='password_reset.html', email_template_name='password_reset_email.html', subject_template_name='password_reset_subject.txt', ) this url is basically if user want to reset his password but i want that only login users can access this page.I know i can prevent non-authorize user to access this url with @login_required decorator but i'm using PasswordResetView which is written by django and i'm unable to use this decorator on it. Can anyone tell me how i can added this functionality that only login user can access this page and how i can Modify PasswordResetView class-view according to me. -
ModuleNotFoundError: No module named 'django' while running server in virtual environment
i am new in python learning.after learning python basics i have moved to learn python web framework Django. for this i followed these steps for installing django on my windows after installing python 3.7 first i opens cmd command prompt (C:\users\mypcname) then i created virtual environment wrapper with command pip install virtualenvironmentwrapper-win then i created virtual environment with command mkvirtualenv test then i entered command workon test to enable virtual environment then tried to install django with command pip install django and its successfully installed then i created projects directory with command mkdir djangoprojects then i created app directory in djangoprojects(which i created in last step) with command django-admin startproject firstproject then i moved to firstproject with command cd.. there i tried to run server with command python manage.py runserver and got error Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did … -
django clean data if create but not clean when update
Im new in django so this is very confusing I have this clean method to raise error when the input data has the same year with existing data def clean_date_year(self): clean_year = self.cleaned_data.get('effective_date') year = clean_year.strftime("%Y") check = model.objects.filter(effective_date__year=tahun).exists() if check: raise forms.ValidationError("The Year Input already here") return clean_year but i also use the same page and the same form to make update, how can i not clean it when i update it ? im using date field so it was a date picker <fieldset> <div class="row"> <div class="col-lg-3"> <label >Effective Date</label> </div> <div class="col-lg-9"> {{ form.effective_date.errors}} {{ form.effective_date }} </div> </div> </fieldset> -
How can i get current status or http code in django via request
I check status code in request.META but there is not available Like request.status or request.status_code -
Django Ajax form
I want to use Ajax in Django to handle the view of my checkout form after it has been submitted. After the form is submitted, I want it to go to : return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") , i.e http://127.0.0.1:8000/checkout/?address_added=True But for some reason, it is not going there. Rather it's being going to http://127.0.0.1:8000/checkout/?csrfmiddlewaretoken=W4iXFaxwpdtbZLyVI0ov8Uw7KWOM8Ix5GcOQ4k3Ve65KPkJwPUKyBVcE1IjL3GHa&address=123+Main+Street&address2=&state=MA&country=USA&zipcode=55525&phone=%28877%29+314-0742&billing=on As a result, the form data is also not getting saved. I was thinking if it were because of the new version of Django. What I want to do is that after they submit the place order button, the form is going to be None, i.e disapper and then I would add a credit card form there for payment. But it is not happening. What is wrong here? Can anyone please help me out of this or is there a better way to do this? My forms.py: class UserAddressForm(forms.ModelForm): class Meta: model = UserAddress fields = ["address", "address", "address2", "state", "country", "zipcode", "phone", "billing"] My accounts.views.py: def add_user_address(request): try: next_page = request.GET.get("next") except: next_page = None if request.method == "POST": form = UserAddressForm(request.POST) if form.is_valid(): new_address = form.save(commit=False) new_address.user = request.user new_address.save() if next_page is not None: return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") else: raise Http404 My orders.views.py: try: address_added = request.GET.get("address_added") … -
How to implement ownership roles for specific models through DRF
Have two types of models, User and Object. Each User can have different ownership level of Object which will come attached with different permissions when accessing DRF endpoints (ownership=ManyToManyField(Object, through='UserObject')). e.g. A User with ownership.permission='Owner' for Object would have CRUD permissions while a User with ownership.permission='Manager' would only have RU permissions while a User with no ownership would have only C permissions. I'm currently storing the relationship with two tables OwnershipLevel with M2M to Permissions which states which of the CRUD permissions the role has but every API transaction is DB heavy as I have to retrieve the user permissions at the beginning. Looking for a way to lessen the load on the DB if possible, by caching role permissions on load or something. Thank you! -
Django render a DynamoDB JSON into a HTML table
I'm try to use a Django page as front-end using some AWS DynamoDB tables as back-end. To do so, I use boto3 library and it gets the data from the table correctly but I'm not able to parse the data into a HTML table. I have the following in views.py def history(request): itemsid = list() agents = list() dates = list() source = list() dynamodb_resource('dynamodb') history_table = dynamodb_resource.Table('name_of_the_table') all_items = history_table.scan() for p in all_items['Items']: itemsid.append((p['id'])), agents.append((p['agent'])), dates.append((p['date'])), source.append((p['source'])) return render(request, 'history.html', {'itemsid':itemsid, 'agents':agents, 'dates':dates, 'source':source} The issue is that I don't know how to write the html code to show a table with the rows: id, agent, date and source. I have the following in history.html <table> {% for i in itemsid %} <tr> <td>{{ i }}</td> ... but I don't know how to code it (how to loop it) to show the table with the lists as source. Any idea please about how to parse a Json with the following format into a HTML with Django and Python please?. JSON from DynamoDB: { 'Items: [ {'id' : '94f' 'agent' : 'aws' 'date' : '04/05 'source' 'case1' }, { 'id' :'lk42' ..... Thank you so much. I'm new in … -
How do I lowercase the first letter of part of my urls address?
I created a for-loop in the template.html to have several buttons direct to different URLs with the product names specified: <a href=http://127.0.0.1:8000/products/{{product.name}} class="btn btn-primary">Click Here</a> For example, if you click the button for pizza, you will be directed to http://127.0.0.1:8000/products/Pizza However, the product names I assigned are all capitalized; how I can address the URLs to be http://127.0.0.1:8000/products/pizza instead of http://127.0.0.1:8000/products/Pizza? -
Django - How to Insert Multiple Form Data using JQuery Ajax
I want to perform a similar task like what described in the following video, https://youtu.be/NoAdMtqtrTA?t=2156 To add multiple rows in the table and then insert it all in a batch to the database. Any reference or any sample code will be really appreciable. Thank you.