Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Store list of tuples django model in easy to access way
I'm creating django application for online Barber Shop booking. I came out with an algorithm that store avaliable hours. Here is exaple how it works. Let's say that barber_1 works form 8am to 4pm. We store this date in list with tuple {(8, 16)} if someone book an 1 hour apointment for 1pm it checks if it is between tuple and if it is, it creates 2 different tuples with updated hours {(8, 13), (14, 16)}, if another apointment is booked for let's say 10am, than it deletes first tuple and creates two new on it's place {(8, 10), (11, 13), (14, 16)} and so on and so on. I have a problem with "translating" my python code to the Django model. Can't find a way to store list of tuples in accesable way to be able to edit it. I read on different post that list of tuples can be stored in many to many relation but I dont think that it will be good in my case. -
Deploying Django DRF and Nuxt.js to Heroku (managing ports)
So I have deployed my Nuxt and Django to Heroku using the following buildpack. So I am running two servers in one app. So my frontend deployed successfully, however I can't setup the ports and hosts for my backend server. My frontends XHR requests are failing with 404, obviously my backend server should proxy to my frontend's "host" as /api/ route. I suppose it should be done using nginx - heroku module or somehow changing the procfiles with specifying the ports and hosts correctly. I would be more than glad if you could help me to clarify the setup structure. my Procfile.web django: gunicorn mydjango.wsgi:application --bind $HOST:$DJANGO_PORT node: cd frontend && yarn start -
The field admin.LogEntry.user was declared with a lazy reference to 'app2.user', but app 'app2' doesn't provide model 'user'
I am trying to build a custom-made User model in Django. My app name is app2. My models.py: from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_Employee = models.BooleanField(default=False) is_Inspector = models.BooleanField(default=False) is_IndustryOwner = models.BooleanField(default=False) is_Admin = models.BooleanField(default=False) class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) extraField = models.TextField(blank=True) I have already put AUTH_USER_MODEL = 'app2.User' in my settings.py and in admin.py: admin.site.register(User) admin.site.register(Employee) Now when I try to migrate I get the following error: Operations to perform: Apply all migrations: admin, app2, auth, contenttypes, sessions Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "G:\Python\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "G:\Python\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "G:\Python\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "G:\Python\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "G:\Python\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "G:\Python\lib\site-packages\django\core\management\commands\migrate.py", line 190, in handle pre_migrate_apps = pre_migrate_state.apps File "G:\Python\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "G:\Python\lib\site-packages\django\db\migrations\state.py", line 209, in apps return StateApps(self.real_apps, self.models) File "G:\Python\lib\site-packages\django\db\migrations\state.py", line 279, in __init__ raise ValueError("\n".join(error.msg for error in errors)) ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'app2.user', but app 'app2' … -
django common context for views but for app only
app1/templates/test.html: {% load my_tags %} APP1: {% test_tag %} app2/templates/test.html: {% load my_tags %} APP2: {% test_tag %} app1/templatetags/my_tags.py: from django import template register = template.Library() @register.simple_tag def test_tag(): return 'Lord of the Rings' app2/templatetags/my_tags.py: from django import template register = template.Library() @register.simple_tag def test_tag(): return '3.14152925' And the result is of course wrong... it depends, which app is first in settings... APP1: 3.14152925 APP2: 3.14152925 how to rebuild this to get: APP1: Lord of the Rings APP2: 3.14152925 No changing names of tag, no changing name of templatetags file.... The best solution would be: {% load {% app_name %}/my_tags %} or {% load {% app_name %},my_tags %} - but of course it doesn't work.... (i have app_name template tag registered by processor if you want to use it) from django.urls import reverse def appname(request): return {'app_name': request.host.name, 'app_base' : '{}/base.html'.format(request.host.name) } -
How to return nested data according to user role in django rest framefork?
I have model which is connected to another model with foreign key, I have ApiView in django. Also, I have users with admin,moderator , and some roles. What I want is when Admin sends get request bring all nested data, when moderator sends get request return only one model's data. What can I do to implement it? I think to create several serializers classes to implement it. -
How can I find the Page Count of a Word Document with Python?
I have tried the approach of finding the page count in the docProps/app.xml file but this isn't very robust as the values can be easily manipulated. As I require this functionality for a website, I can't use win32com.client because it only works on Windows with Word installed. Is there a reliable way of finding the page count using Python? -
Display field (create with sql query) in fields= [ ] in Django admin?
I try create function create field dynamic. And i tried create function adding field with raw SQL query for django Ex : query_raw = "ALTER TABLE myapp ADD myField float(2);" and I had field with name "myField" in my database. But have i a trouble with edit it on Django admin. Because it's not showing on. Ex : First i have field in my db : MyName, MyYearOld, MySchool After i use query_raw i will have : MyName, MyYearOld, MySchool, myField in my database But in Django admin windowns, i just have field MyName, MyYearOld, MySchool. The "myField" cant display. -
Form validation in function views
Is there any difference between the 2 parts of code? def test(request): if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): form.save() title = form.cleaned_data.get('title') #<<-- print(title) return redirect('blog-home') else: form = TestForm() return render(request, 'blog/test.html', {'form': form}) def test(request): if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): form.save() title = request.POST.get('title') # <<-- print(title) return redirect('blog-home') else: form = TestForm() return render(request, 'blog/test.html', {'form': form}) Since both cases is part of form.is_valid() condition I believe it should be same right? -
django database won't show real time changes
my Django website connected to SQL server, when I make changes to the database on phpmyadmin page, for example, delete a field on a table, the data will remove, but my site shows it, if I rerun my app from pycharm, the changes show up, can you help me to have a real time database? Thanks -
UnboundLocalError at /: local variable 'query' referenced before assignment
This code worked yesterday but today when i open this i get unbounced local error!! I am trying to make a search using country name in an API and it should show me the context that i set up. Code: def index(request): url = 'https://api.covid19api.com/summary' result = requests.get(url).json() info = result['Countries'] if request.method == 'POST': query = request.POST['search'] for i in range(0,192): if query.lower() == info[i]['Country'].lower(): context = { 'country': info[i]['Country'], 'confirm': info[i]['NewConfirmed'], 'recover': info[i]['NewRecovered'], 'death': info[i]['NewDeaths'] } return render(request, 'corona/home.html', context) -
WIN10: Python env. variables suddenly changed themselves or sometihng?
This is the usual topic about with a twist , I think: For months I used Python+Django fine in a Win10 PC, running the bussines from the app folder like: python manage.py runserver Then one day sudenly with no change to the env vars that I recall, this happens: python manage.py runserver C:\Users\Admin\Desktop\Python\tjr>python manage.py runserver Can not find Python; etc etc... Also if I try jist py manage.py runserver BUT, typing only "py" starts the interpeter, so, yes, the python.exe is found by Windows, right? C:\Users\Admin\Desktop\Python\tjr>py Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> My env.vars.: enter image description here NOTE: I did not change the envvars or reinstalled Python or anyhing at all. This happened suddenly and I would like to know why. We do have thousands of posts about Python+Win+env.vars but this is more like, what happened? everything was fine and set up and now suddenly it errors our, same computer, same steps. Other posts advise to set the vars in the SysPath, not UserPath, ok, but, I had thse set in the user path all the time and worked fine, then … -
Add group to Proxy User
I'm using Django with Wagtail CMS and i created two proxy models from class User. I ant to add a group on user creation from the proxy classes. I tried to add signals but that apparently dose not work on proxy models. So on save i would like to add teachers to Teachers group and students to Students #models.py class User(AbstractUser): class Types(models.TextChoices): STUDENT = "STUDENT", "Student" TEACHER = "TEACHER", "Teacher" type = models.CharField(_('Type'), max_length=50, choices=Types.choices, default=Types.STUDENT) class Student(User): class Meta: proxy: True def save(self, *args, **kwargs): if not self.pk: self.type = User.Types.STUDENT return super().save(*args, **kwargs) class TeacherMore(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) models = models.CharField(max_length=255) class Teacher(User): class Meta: proxy: True def save(self, *args, **kwargs): if not self.pk: self.type = User.Types.TEACHER return super().save(*args, **kwargs) -
Django staticfiles not loading
I am using s3 to serve my static files. The files are present on the s3 bucket but when i run my website those files do not load up. I have installed django-storages and boto3 for this. This is what is see [Click Here to see the image] when i inspect the image i can see that the image url is pointing towards the s3 aws bucket but for some reason the css and images are not being shown on the website itself. here is my setting.py # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', 'accounts', 'blog', 'tinymce', 'storages', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] ROOT_URLCONF = 'vedicmiracles.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 = 'vedicmiracles.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': … -
Django Heroku Deployment No Module Found
I am trying to deploy a django project at https://testing-mike.herokuapp.com/ The deployment succeeded but it throws a no module found error. The same module with wsgi works on the local shell using this command : gunicorn --bind 0.0.0.0:8000 solvesto.wsgi:application but fails on heroku. -
Dictionaries in specific format
I need the below code in one specific formate ROOM_CATEGORIES={ ('Elt','Elite'), ('Lux','Luxury'), ('Sig','Signature') } Above code I want {'Sig':'Signature','Lux':'Luxury','Elt':'Elite'}<---Like This -
How to set up gunicorn
My django project in /root/code/mysite, django apps: main, homepage. What should I write in gunicorn.service? (Debian 9, user root) -
Can't Run Django Local Server due to Dash
I am trying to migrate my Django database after installing django_plotly_dash and am receiving this error even though I have dash installed and working fine. Any ideas why this will not work when I try it with Django? Command: C:\Users\xxx\Python\Price Tracking\Django\mysite>python manage.py migrate Installing dash: C:\Users\xxx>pip install --trusted-host=pypi.org --trusted-host=files.pythonhosted.org dash Requirement already satisfied: dash in c:\python38\lib\site-packages (1.12.0) Requirement already satisfied: Flask>=1.0.2 in c:\python38\lib\site-packages (from dash) (1.1.2) Requirement already satisfied: flask-compress in c:\python38\lib\site-packages (from dash) (1.5.0) Requirement already satisfied: plotly in c:\python38\lib\site-packages (from dash) (4.7.1) Requirement already satisfied: dash_renderer==1.4.1 in c:\python38\lib\site-packages (from dash) (1.4.1) Requirement already satisfied: dash-core-components==1.10.0 in c:\python38\lib\site-packages (from dash) (1.10.0) Requirement already satisfied: dash-html-components==1.0.3 in c:\python38\lib\site-packages (from dash) (1.0.3) Requirement already satisfied: dash-table==4.7.0 in c:\python38\lib\site-packages (from dash) (4.7.0) Requirement already satisfied: future in c:\python38\lib\site-packages (from dash) (0.18.2) Requirement already satisfied: itsdangerous>=0.24 in c:\python38\lib\site-packages (from Flask>=1.0.2->dash) (1.1.0) Requirement already satisfied: Werkzeug>=0.15 in c:\python38\lib\site-packages (from Flask>=1.0.2->dash) (1.0.1) Requirement already satisfied: Jinja2>=2.10.1 in c:\python38\lib\site-packages (from Flask>=1.0.2->dash) (2.11.2) Requirement already satisfied: click>=5.1 in c:\python38\lib\site-packages (from Flask>=1.0.2->dash) (7.1.2) Requirement already satisfied: MarkupSafe>=0.23 in c:\python38\lib\site-packages (from Jinja2>=2.10.1->Flask>=1.0.2->dash) (1.1.1) Requirement already satisfied: brotli in c:\python38\lib\site-packages (from flask-compress->dash) (1.0.7) Requirement already satisfied: six in c:\python38\lib\site-packages (from plotly->dash) (1.14.0) Requirement already satisfied: retrying>=1.3.3 in c:\python38\lib\site-packages (from plotly->dash) … -
How to implement RBAC(role-based-access-control ) in distributed microservices architecture?
I created authentication server and resource server. I used django oauth toolkit library for the implementation. The authorization works fine. https://django-oauth-toolkit.readthedocs.io/en/latest/ I would like to implement RBAC(role-based-access-control) in the resource server. I don't find any reference for that. Can someone guide me to implement the RBAC(role-based-access-control) in distributed microservices architecture? -
Unable to get output in server localhost by returing using loop in django python?
for k in range(len(data[0])): fi = data[0][k] return render(request, "a.html", {'result': fi}) i return by sing render function in a loop but get no output. when i return same thing outside the for loop than it gives me correct output. is it any possilbe way to get my output using loop? -
Django: Prevent form from resetting when a form is not valid
I am trying to prevent the form from resetting when there is an invalid input, but when there is an invalid input my whole form is resetting and I don't understand why. This is basically a registration form and the point is to not have the form reset when form.is_valid() is false. Also, if you could help with displaying messages. How do I incorporate a strength password bar under the password field. <center><div class= 'form-container'> <h1 style="font-weight:normal;font-family: 'Google Sans','Noto Sans Myanmar UI',arial,sans-serif;position: relative;top: 20px;">Sign-up</h1> <form method="post" id = "register-inputs" action = {% url 'register' %}> {% csrf_token %} <div> <div class="user-register"> <input type = 'text' name = 'first_name' required> <span class="highlight"></span> <span class="bar"></span> <label>First name</label> </div> <div class="user-register"> <input type = 'text' name = 'last_name' required> <span class="highlight"></span> <span class="bar"></span> <label>Last name</label> </div> <div class="user-register"> <input type = 'text' name = 'email' required> <span class="highlight"></span> <span class="bar"></span> <label>Email</label> </div> <div class="user-register"> <input type = 'text' name = 'username' required> <span class="highlight"></span> <span class="bar"></span> <label>Username</label> </div> <div class="user-register"> <input type = 'password' name="password1" required> <span class="highlight"></span> <span class="bar"></span> <label>Password</label> </div> <div class="user-register"> <input type = 'password' name="password2" required> <span class="highlight"></span> <span class="bar"></span> <label>Confirm Password</label> </div> <input class="btn btn-primary" type="submit" value="Sign up!"> … -
How to implement file upload in django with TinyMCE?
I'm quite new to django and I wanted to make my text editor to my Django admin page accept file upload and file browsing. I currently have the editor set up, however I'm not able to browse for files. image of my current file upload pop up (notice there's no browse button) I understand that there are documents on the official TinyMCE website (https://www.tiny.cloud/docs-4x/configure/file-image-upload/) regarding implementing file and image upload and file_picker and what not, but they're all provided in JavaScript instead of Python. How would I go about doing this using Python? If that process is too complicated, how would I implement the file upload to my django project if I'm using the default admin page that django provides? -
Problem in the button not working in django
I created articles blog but user can not create article with create button , my code in git hub: https://github.com/MohammadGhanbari1/firstBlog -
permission to users with few model instances
models.py How can i setup custom permission for users(who are my employees) to only view those dealer pages that admin assigns to them and can change those permission anytime. class Dealer(models.Model): name = models.CharField(max_length=200) mob_num = models.IntegerField(blank=True, null=True) address = models.TextField(blank=True) def __str__(self): return self.name class Ledger(models.Model): date = models.DateTimeField(auto_now_add=True) particulars = models.CharField(max_length=100,blank=True) debit = models.IntegerField(blank=True, default=0) credit = models.IntegerField(blank=True, default=0) paymode = models.CharField(max_length=10, choices=(('Cash','Cash'), ('Cheque','Cheque'),)) dr_cr = models.CharField(max_length=10, default='', choices=(('Dr','Dr'), ('Cr','Cr'),)) invoice = models.ImageField(upload_to=None, blank=True) dealer = models.ForeignKey(Dealer, null=True, on_delete=models.SET_NULL) balance = models.IntegerField(default=0) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name = 'home'), path('ledger/<int:pk>/', views.ledger, name = 'ledger'), path('dealer/<int:pk>/', views.dealer, name = 'dealer'), This picture shows that each dealer has his own ledger instances i want to restrict my users to only few of those dealer pages, and can customize that anytime, some help would really be appreciated. -
Handling Multiple Forms on the Same Page in Django without Django's default model form
I am trying to develop a webpage with two forms on the same page with Django. Anyone will able to fillup any single form and submit it, then that data will be saved in the database. Here I try to avoid Django's default model form and any type of js stuff also. My HTML: <!DOCTYPE html> <html> <head> <title></title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Popper JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> <!-- animated css link --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.0.0/animate.min.css"/> <!-- font awsome css link --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <!-- custom css link --> <link rel="stylesheet" type="text/css" href="#"> </head> <body> <div class="row m-0 bg-info"> <h2 class="mx-auto my-4">Multiple form in one page</h2> </div> <div style="height: 40px;"></div> <div class="container-fluid my-5"> <div class="row m-0 d-flex justify-content-center"> <div class="col-md-3"> <h2>Employee Profile</h2> <form class="#" method="POST" id="EmployeeProfile"> <div class="form-group"> <label>Ranks</label> <input type="text" class="form-control" name="ranks" placeholder="Enter ranks"> </div> <div class="form-group"> <label>salary</label> <input type="text" class="form-control" name="salary" placeholder="Enter salary"> </div> <div class="row d-flex justify-content-center"> <button type="submit" class="btn btn-primary m-2">Submit</button> </div> </form> </div> <div class="col-md-2"></div> <div class="col-md-3"> <h2>Inspector Profile</h2> <form class="#" method="POST" id="InspectorProfile"> <div class="form-group"> <label>Ranks</label> <input type="text" class="form-control" name="ranks" placeholder="Enter ranks"> </div> <div … -
WSGI Daemon doesn't recognize python 3.8 env path Django 3.1.4
WSGI Daemon doesn't recognize python 3.8 env path. This results in him not being able to load 'django' module which. The mod_wsgi was intialy installed with python3.6 so this might be the case. Inside the /usr/lib/apache2/modules/ there are two files concerning mod_wsgi: mod_wsgi.so mod_wsgi.so-3.6 From this I can assume that in order to run WSGIDaemon with python 3.8 I will have to create a mod_wsgi.so-3.8 How can i achieve this ?