Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My django app breaks when installing geo django: libpoppler not found
I developing an app but it doesn't compile after installing django-leaflet and django.contrib.gis. Everythin works perfectly if I don't use django.gis nor django-leaflet, and it appeared after I struggled a lot installing the gdal library. I thought it could be compatibility with Python, because I'm using latest version, but downgrading didn't work form me (should I downgrade more?) Any suggestion? The error I see: > File "/home/horacio/anaconda3/envs/epec/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/home/horacio/anaconda3/envs/epec/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home/horacio/anaconda3/envs/epec/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module> from … -
Django How to Fix Multiple Server Issues
I have this model, and it has been causing me a lot of trouble here are the models: class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=20) text = models.TextField(default='') created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) class Videos(models.Model): title = models.CharField(max_length=100) video = models.FileField(upload_to='videos/') def __str__(self): return self.title First, when I try to migrate anything I get: django.db.utils.OperationalError: table "blog_videos" already exists This is for model Videos. This error happened after I deleted a few migration files. Then when I try to add to the model "Comment", I get this: django.db.utils.IntegrityError: NOT NULL constraint failed: blog_comment.author_id_id This happened after I added this to comment model: author_id = models.ForeignKey(User, on_delete=models.CASCADE, default='') I then deleted this model and have this problem now. I am unable to fix this because I can't migrate anything becuase of the issue above. Please help me. I am using python 3.8 and django 3.1.5. I am fine deleting all data (It's all worthless at the moment, its just dummy data. Cheers. -
Override vs extend Django's models.Manager to handle deleted objects (best practice)
There is a requirement, that nothing should be deleted from database So, obviously, all models should be inherited from something like this: class BaseModel(models.Model): is_deleted = models.BooleanField(default=False) But, it is not obvious how to make QuerySets handle is_deleted the best way I can imagine two options: 1) Override BaseModel's Manage's ._get_query_set() method So, both will return only active objects (marked as is_deleted=False): Article.objects.all() Article.objects.filter(id__in=[1, 2]) Even .get(...) will raise 404 if is_deleted=True: Article.objects.get(id=1) Also, extend with additional method, to actually access is_deleted=True: Article.objects.deleted(id=1) 2) Second option is to extend BaseModel with additional second Manager, let's say - actual So, all three will exclude objects with is_deleted=True: Article.actual.all() Article.actual.filter(id__in=[1, 2]) Article.actual.get(id=1) Regular .objects stands with native behaviour: Article.objects.all() Article.objects.filter(id__in=[1, 2]) Article.objects.get(id=1) --- Maybe there are another good options? Is there a best practice? Big thx for advices! -
Working with one-to=many relationships (Django)
Okay....previously I wrote up a simple HTML-CSS-Javascript site. I then created an empty Django project and tried to put everything in that project. I created a real mess! So I am now writing everything up from scratch, working on the Django project first. I still am having problems with the database I set up. Here is my models.py: from django.db import models # Create your models here. class Book(models.Model): title = models.CharField(max_length=200) description = models.TextField() source = models.CharField(max_length=200) source_site = models.CharField(max_length=200) def __str__(self): return self.title class Chapter(models.Model): book = models.ForeignKey( Book, on_delete=models.CASCADE, related_name='chapters') chtitle = models.CharField(max_length=100) chtitletext = models.CharField(max_length=200) chtext = models.TextField() def __str__(self): return self.chtitle And here is my views.py: from django.shortcuts import render, get_object_or_404 # Create your views here. from django.http import HttpResponse from .models import Book, Chapter def index(request): book_list = Book.objects.order_by('-id') output = ', '.join([b.title for b in book_list]) context = { 'book_list': book_list, } return render(request, 'sophia/index.html', context) def readBook(request, book_id): book = get_object_or_404(Book, pk=book_id) chapter_list = Chapter.objects.order_by('-id') context = {'book':book, 'chapter_list':chapter_list} return render(request, 'sophia/readbook.html', context) and here is my urls.py: from django.urls import path from . import views app_name = 'sophia' urlpatterns = [ path('', views.index, name='index'), path('<int:book_id>/', views.readBook, name='readbook'), ] and finally, my … -
How to call distinct() on django-pivot results
I've been using the django-pivot package to pivot complaint data, and it's an amazing package that generally works like a dream, but I noticed yesterday that when rows or columns are referring to ManyToMany fields, the results include some duplicates. When I'm constructing my own queries I just throw a distinct() on the end of it, is there a way to do something similar in django-pivot? -
Fetch failed loading: GET (with same path)
Got an issue with fetch in js + Django document.addEventListener("DOMContentLoaded", function () { // loading inbox as default load_mailbox("inbox"); console.log("again loaded INBOX____________") // when form is submitted, send email to other user document.querySelector("#compose-form").onsubmit = function () { fetch("/emails", { method: "POST", body: JSON.stringify({ recipients: document.querySelector("#compose-recipients").value, subject: document.querySelector("#compose-subject").value, body: document.querySelector("#compose-body").value, }), }) .then((response) => response.json()) .then((result) => { // Print result console.log(result); // after sending email, loading page with sent emails load_mailbox("sent"); }); }; }); Load mailbox will call other function, which will fetch the data for the page if (mailbox === "sent") { fetch_mail_by_folder("sent") } function fetch_mail_by_folder(folder) { fetch(`/emails/${folder}`) .then((response) => response.json()) .then((emails) => { emails.forEach(email => { // we fetching data for this page, and paste it into new div const element = document.createElement("div"); element.innerHTML = `some data`; element.addEventListener("click", function () { get_email(email.id, folder); }); const div = document.querySelector('#emails-view') // after that we add elements into existing html div div.append(element); }) }); } There is an error when mail was sent, (after concole.log with "email sent successfully") Fetch (fetch_mail_by_folder("sent")) was failed, (see screenshot). After, I tried to fetch the "sent" page with other function (just a simple button): document .querySelector("#sent") .addEventListener("click", () => load_mailbox("sent")); And it works well (see … -
How can I resolve an" ImportError: attempted relative import with no known parent package" issue in a Django project?
I'm working on Chapter 18 of Python Crash Course, and have started over from scratch twice already, all 53 steps. (A very educational process) The program was working fine until I tried to add the code for individual pages. Now, it won't run at all. It keeps saying that views aren't defined. I've tried every suggestion I've found for similar issues without success and double checked all the elements. Here is the code for my urls.py and views.py. Any information/suggestions on how to resolve this would be greatly appreciated. """Defines URL patterns for learning_logs""" from django.urls import path from . import views app_name = 'learning_logs' urlpatterns = [ path('topics/<int:topic_id>>/',views.topic,name = 'topic'), path('', views.index,name='index'), path('topics/',views.topics, name='topics'), ] from .models import Topic from django.shortcuts import render def topics(request): topics = Topic.objects.order_by('date_added') context = {'topics':topics} return render(request,'learning_logs/topics.html',context) def index(request): return render(request,'learning_logs/index.html') def topic(request, topic_id): topic = Topic.objects.get(id= topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic,'entries':entries} return render(request, 'learning_logs/topic.html',context) -
Custom User Model in Django (email as username) - removing username safely if overriding AbstractUser
In my Django project, I would like users to register/login with their email address rather than a username, so I am planning to use a custom User model. Alongside this, I would like to define a couple of extra fields, and avoid extra database queries that would come with having a separate Profile model (with One-to-one relationship) for those. Other than these things, the default User functionality is exactly what I need, so rather than overriding AbstractBaseUser and having to rewrite code without confidence, I think overriding AbstractUser is the way to go. But I'm not sure, so that's where you come in! I have read many blog posts and threads on StackOverflow about the subject and there seems to be a common approach when using AbstractUser for this purpose (setting username = None) as follows: class CustomUserA(AbstractUser): username = None email = models.EmailField(unique=True) #necessary as it must now be unique extra_field = models.CharField(max_length=20) #for example USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] #necessary to empty this as 'email' is now USERNAME_FIELD objects = CustomUserManager() If this approach is used, a custom user manager (a subclass of BaseUserManager) needs to be set up, as it states here in the docs: You … -
Restrict access to a url unless user is coming from a certain page
For example the user won't be able to access page 'b' unless they are coming from page 'a' (they can't just paste the link and go to the page) -
Django Custom Use with Array of Another Model (Acting like a shopping cart)
Newbie to Django, Django rest_framework, and Djoser here. I am building the backend to what you can think of as a simple shopping app (think coffeeshop on this one). At the moment, I have a custom User model in one app called authapp and a Coffee model that lives in another app called apiapp. My goal is to allow User objects to have 0-infinity number of Coffee objects to act as their shopping cart and to have that data displayed in the users endpoint. Currently, I the User model looks like the following in models.py: from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): email = models.EmailField(verbose_name='email', max_length=255, unique=True) phone = models.CharField(null=True, max_length=255) coffees = models.ManyToManyField("apiapp.Coffee", verbose_name="coffee") REQUIRED_FIELDS = ['username', 'phone', 'first_name', 'last_name'] USERNAME_FIELD = 'email' def get_username(self): return self.email In serializers.py, I have: from djoser.serializers import UserCreateSerializer, UserSerializer from rest_framework import serializers from .models import * # Create your serializers here class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User field = ['id', 'email', 'username', 'password', 'first_name', 'last_name', 'phone', 'coffee'] In the admin dashboard, I currently see this when editing a User object (looks like you can select and deselect any / all of the … -
How to caught exception when django query is not performed due to no internet connection
I need to handle the scenario when django query can't reach the database due to no internet connection I tried with try-except block like this, but there's no exception caugth: try: return self.filter(my_model_id=<some int number>) except Exception as e: logger.error(e) How can i handle this? -
Django's set_exprity() in JsonResponse
I want to implement the "Remember me" functionality in my app. According to the docs and other questions the snippet request.session.set_expiry(0) is supposed to destroy the user session when the user closes the browser. My problem is that I can't find a way to add this to the JsonResponse in my login view. (the logic is not implemented yet) @require_POST def login_view(request): data = json.loads(request.body) email = data.get('email') password = data.get('password') if email is None or password is None: return JsonResponse({'detail': 'Please provide email and password.'}, status=400) user = authenticate(email=email, password=password) if user is None: return JsonResponse({'detail': 'Invalid credentials.'}, status=400) login(request, user) request.session.set_expiry(0) # does not work return JsonResponse({'detail': 'Successfully logged in.'}) -
Fastest way of performing multiple different calculations to every object in a queryset
I have these two models in my db: class Product(models.Model): name = models.CharField(max_length = 64) retailer = models.ForeignKey(Retailer, related_name = 'products', on_delete = models.CASCADE) brand = models.ForeignKey(Brand, related_name = 'products', on_delete = models.CASCADE, null = True, blank = True) enabled = models.BooleanField(default = True) def __str__(self): return self.name class Item(models.Model): product = models.ForeignKey(Product, related_name = 'p_items', on_delete = models.CASCADE) date = models.DateField(null = True, blank = True) user = models.ForeignKey(User, related_name = 'p_items', on_delete = models.CASCADE) net_price = models.PositiveIntegerField(blank = True) class Meta(): ordering = ['-date'] These models are in fact an alias to protect my employer. Keep this in mind if something doesn't really make sense - The db structure can't change. An Item represents one sale made by one of our users. The user needs to fill which type of product and when they did sell it, also by how much. However, the net_price chosen by the user isn't whats being charged at the client. There are two types of "added costs" later added to the net_price. One of them is deliberately chosen by the management, and it can be done days after the item has been added to the db. With this new model: (...) class GradeInflation(models.Model): … -
How to show linked objects in Django Admin View?
I have two models that are linked by a foreign key relationship: class A(models.Model): q1 = models.CharField(max_length=60) q2 = models.CharField(max_length=60) ... class B(models.Model): b = models.CharField(max_length=60) a = models.ForeignKey("A", on_delete=models.CASCADE) In my admin site I have the A model showing, and ideally would like to keep it that way. Is there a way for me to within the individual A instances show the B instances? I have only been able to find solutions for the reverse (showing a dropdown of A instances in the individual B instances). -
Ajax function not showing values in django
Bit of a problem. What i am trying to do is determine what date the user has selected from an option picker and print the value from a main.py function. So let me show my set up. first thing i have done is calculate the date and in my views.py: def index(request): #GOING TO PUT THE DATE DIFFERENCE CALCULATION HERE the_uploaded_excel_file = excel_upload.objects.order_by('-id').first() excel_file_path_from_db = the_uploaded_excel_file.my_excel_file.path print(excel_file_path_from_db) wb = load_workbook(excel_file_path_from_db) ws = wb["Sheet1"] df = pd.read_excel(excel_file_path_from_db, engine='openpyxl', sheet_name='Sheet1', skiprows=1) max_date_column = ws.max_column last_date_entered = ws.cell(row=1, column=max_date_column).value todays_date = datetime.datetime.now().date() Date_difference = pd.date_range(start= last_date_entered, end=todays_date, freq='D') print("last date entered was ") print(last_date_entered) print("todays date is ") print(todays_date) print("the days not done are") print(Date_difference) for date in Date_difference: print(date) return render(request, "index.html", { 'Date_difference': Date_difference }) Then I show the dates in my html: <h2> {% for daterange in Date_difference %} <h5>{{ daterange|date:"d M Y" }}</h5> {% endfor %} </h2> <select style="background-color: #ceedd0;" id="date_selector" onchange="what_date_has_been_picked()" name="filter_for"> {% for daterange in Date_difference %} <option value={{ daterange }}>{{ daterange|date:"d M Y" }}</option> {% endfor %} </select> this produces the following: now what I want to do is to be able to print this result in my main.py. so i set up an ajax function. … -
Django rest framework bulk post object
I want insert bulk json via django rest_framework however, I get a error message ; typed following line ; "detail": "JSON parse error - Expecting property name enclosed in double quotes: line 2 column 6 (char 7)" my serializer.py file include following code block; class DrfSerializerV2(serializers.ModelSerializer): def __init__(self,*args,**kwargs): many=kwargs.pop('many',True) super(DrfSerializerV2,self).__init__(many=True,*args,**kwargs) class Meta: model = DrfData fields=['id','name','duration','rating','typ'] and my views.py file ; class ActionViewSet(viewsets.ModelViewSet): queryset = DrfData.objects.filter(typ="action") serializer_class = serializers.DrfSerializerV2 finally send json file via post; [ {'name':'m1','duration':120,'rating':4.7}, {'name':'m2','duration':120,'rating':4.5} ] however, I can't handle this error message. if I send sperataly, there is no problem. but, I can't resolve this error for bulk insert -
Can't run the server on Django TCP/IP conection?
I've already download all packages from django, whitenoise, etc, and the error continues. The cmd is running with the env and triyng to push i'm still on the same error I'm trying to run with a local host my server and that happend : Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Domestico\anaconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check_migrations() File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, … -
How to pass variable from JavaScript to Django as part of url?
I'm building video player in Django. I use JavaScript to change prev/next video without refreshing the page by passing queryset from Django to JS. I need to add Like button to like currently played video. I can bring variable (ID) of current video but don't know how to include it in URL. This is how I'm bringing variable from JS to HTML. JavaScript: document.getElementById("video_controler").innerHTML=video_controler; Displaying it in HTML: Video controler: <a id="video_controler"></a> And in this form I want to replace hardcoded 'videos.0.pk' with 'video_controler' varibable: <form action="{% url 'like_post' videos.0.pk %}" method="POST"> {% csrf_token %} <button type="submit" name="post_id" value = '{{ videos.0.pk }}'>LIKE</button> </form> -
Passing values from Jquery with Ajax to Django views
I'm building an django app where user can organize notes in three columns "To Do", "Progress" and "Done" with drag and drop made with Jquery sortable. On screen load, notes are imported from database and put inside column matching their status values. After user changes, "save" button can be clicked. That's where i want to make an update to note's status in database. Here's HTML with Javascript {% load staticfiles %} {% load static %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static '/css/bootstrap-5.0.0-beta1-dist/css/bootstrap.css' %}"> <script src="{% static 'css/bootstrap-5.0.0-beta1-dist/js/bootstrap.js' %}"></script> <script src="{% static 'js/jquery.js' %}"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script src="{% static 'js/jquery.bootstrap.modal.forms.js' %}"></script> </head> <body> <div id="con_p" class="col-sm-10 "> <div id="2"> <div class="row "> <div class="col text-center"><h3 class="display-5">TICKETS</h3></div> </div> </br></br> <div class="d-flex flex-row-reverse"> <button id="add-ticket" class="btn btn-primary btn-sm mx-2 " type="button" name="button">Add Ticket</button> <button id="save_tickets" class="btn btn-primary btn-sm " type="button" name="button">Save</button> </div> <div class="row border"> <div class ="col text-center"> <h4>To Do</h4> </div> <div class ="col text-center"> <h4>In Progress</h4> </div> <div class ="col text-center"> <h4>Done</h4> </div> </div> <div class="row"> <div class ="col border text-center" > <fieldset class="sortable"> <ol id="to_do" class="min-vh-100"> {% for i in ticket %} {% if i.status == "To Do" %} <li class="ticket" > … -
Django MSSQL: Override Foreign Key Constraint Name Generation
I am attempting to create a database model in Django 3.0 using django-mssql-backend as by db backend for SQL Server 2019. The database uses multiple schemas for the tables included in it with some of the tables being non-managed (already exist), and others being created from scratch through migrations. To get multiple schemas working, I used a hack I found on another answer on here that suggested formatting the tablename as follows: class MyModel(models.Model): ... class Meta: db_table = 'schema].[table' This is so that the SQL compiles to have the wrapped square brackets that automatically form on the outside complete the schema/table definition. The problem with this is that ForeignKey objects have their constraint names generate using this table name which causes invalid constraint names arise, causing the migration to fail once the tables are done being created and it comes time for the constraints to be created.\ They generate like this: [schema1].[table1_colname_id_bc165567_fk2_schema2].[table_colname] Is there a way to override this behaviour? If this can be overridden by forking the backend and adding manual compilation code how would I even go about doing that? Otherwise, how can I have foreign keys in my models while using multiple schemas and fully utilizing … -
Cookies are blocked during development DRF and Vue app
I have Django Rest Framework API and Vue SPA frontend app. I deploy both of them in the DigitalOcean App platform. I use Session Authentication. My problem is that Session and CSRF Token cookies do not work during development when Django and Vue are served by their default servers. I guess it is because of the Same Origin Policy and other security stuff. In the production, everything is working fine when they are on the same domain. I do not have this issue earlier because I was using Token Authentication which I found out is not suitable for web Apps. I need some way of using session and csrftoken cookies during development on my computer. Is this possible with Dockerazing both apps (they are in separete repositories currently) and starting them with some reverse-proxy like Nginx so they will have the same domain? Or mayby some other way so i could develop and deploy such app easier? I cant find any information about this problem in the internet, so maybe I am missing something, or should do something differently? -
Django: how to redirect to page with list of newly created objects after form post bulk_create
I have a simple form that allows user to paste csv data with the goal to create multiple model objects at one go. The form method is 'post'. Action url is a method that calls the django `bulk_create` to create the model objects returning the pks. Goal: After submission, I want to redirect to page showing a list of the objects corresponding to the pks. Is that possible? I have tried: return render(request, "list_template.html", context={'object_list': objects_with_pks}), passing the model objects as context data to another template (but there would be danger of duplicate submission upon refresh) Redirect user to a model DetailView which contains the pk in the url (but I have more than one pks created) return HttpResponseRedirect to a new page with a success message (but I won't be able to pass the pks to the new page) Other ways that I've thought but could not find an answer Can I pass multiple pks in a url? Is there a way to transform a POST request to a GET? Can querysets in a model ListView instance be passed as parameters? I am fairly new to web development and posting questions on stackoverflow. Please comment if its unclear and … -
Django: TypeError: Object of type ModelBase is not JSON serializable
I get Error 'TypeError: Object of type ModelBase is not JSON serializable'. But i don't use JSON. And i don't put any 'ModelBase' object to templates. It's started when i began to use request.session for global variables store. When i used global variables like in pure Python - this project worked ok. (On local developer server, but was a problem with works on deploy for multiuser load.) I can't understand where it problem is appears: I use Debug mode - my views.py function is runned proprly, it return exit_ for temlate: def page_Category_Main(request, cat_): #... exit_ = { 'category_name': category['category_name'], #str 'categories_list': categories_list, #list 'action': cat_, #str 'tbl_ttx_col': [x for x in tab_marketability.keys() if x not in ['id', 'brand', 'name', 'price_avg', 'appear_month']], #list 'tbl_data': tab_marketability, #dict 'tbl_data_nov': tab_novelty, #dict 'new_form': new_form, #dict 'enabled': enabled_return, #list 'checked_items': post_return, #list 'period': request.session['period_mth_rus'], #list 'tab_active': tab_active, #str 'tab_list': list(dict_tabs.keys()), #list 'tab_data': dict_tabs #dict } return render(request, template_name="al_category.html", context=exit_) And server begin to handles template al_category.html (I see it in Python Debuger, becouse template use some @register.filter function from views.py). And in unknown point raise this TypeError: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/Nb/ Django Version: 3.1.2 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', … -
Dynamic Model Creation, Migration, and Registration in Django 3.1
I'm working on a project where I've to dynamically create models. So far I've been able to create a model and store its instance in a variable. But when I'm trying to migrate and register it to admin panel, Django is throwing an error. This is the error that pops up when I try to load the admin panel. NoReverseMatch at /admin/ Reverse for 'app_list' with keyword arguments '{'app_label': 'System'}' not found. 1 pattern(s) tried: ['admin\\/(?P<app_label>auth)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 3.1.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'app_list' with keyword arguments '{'app_label': 'System'}' not found. 1 pattern(s) tried: ['admin\\/(?P<app_label>auth)/$'] Exception Location: D:\DynamicModelCreation\environment\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix Python Executable: D:\DynamicModelCreation\environment\Scripts\python.exe Python Version: 3.6.6 Python Path: ['D:\\DynamicModelCreation', 'D:\\DynamicModelCreation\\environment\\Scripts\\python36.zip', 'c:\\users\\vaibhav\\appdata\\local\\programs\\python\\python36\\DLLs', 'c:\\users\\vaibhav\\appdata\\local\\programs\\python\\python36\\lib', 'c:\\users\\vaibhav\\appdata\\local\\programs\\python\\python36', 'D:\\DynamicModelCreation\\environment', 'D:\\DynamicModelCreation\\environment\\lib\\site-packages'] Server time: Thu, 11 Feb 2021 01:30:23 +0530 This is the function where I'm trying to migrate and register the model. def createModel(tableName, fields): class Meta: pass setattr(Meta, "app_label", "System") fields['__module__'] = "System.models" fields['Meta'] = Meta model = type(tableName, (models.Model, ), fields) class Admin(admin.ModelAdmin): pass admin.site.register(model, Admin) print(model._meta.fields) return model My aim is to create and migrate the models and register them successfully during the runtime. App name - System Project name - DynamicModelCreation -
Problem with accessing static files when deploying Django API using Google App Engine
I have schema.yml in the static folder in my project and during development everything seems to be working properly however after deployment to the App Engine I get the error Not Found /static/schema.yml. My configuration looks in the way shown below. Do you have any ideas what can be the cause of the problem? settings.py: PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'templates'), ) STATIC_URL = '/static/' app.yaml: runtime: custom env: flex entrypoint: gunicorn -b :$PORT mysite.wsgi service: mysite-service handlers: - url: /static/ static_dir: static