Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Page not found error in Django
After a lot of hustle and bustle, i am asking this question. I'm a noobs into it and trying to make a small website using django. I'm not able to figure out where I m commiting the mistake. Here is my models.py file from django.db import models class A(models.Model): author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) title = models.CharField(max_length=200) text = models.TextField() def __str__(self): return self.title Project name is website and here goes its urls.py file:- from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url('admin/', admin.site.urls), url('artitem/', include('artitem.urls')) ] App name is artitem and here its urls.py file:- from django.conf.urls import url, include from . import views urlpatterns = [ url('artitem/', views.A.as_view(), name = 'artitem') ] Views.py file:- from django.shortcuts import render from django.views.generic import ListView from .models import A class A(ListView): model = A template_name = 'B.html' Here is the admin.py:- from django.contrib import admin # Register your models here. from .models import A admin.site.register(A) Settings.py file, I have changed the static path in order to make way for static file:- INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'artitem' ] STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] Any help is appreciable. -
Django asking to define `model` while its already defined
I have already defined model = Post in my views.but still its asking for defining a model or queryset! where am i doing wrong then? views.py from .models import Post from django.views.generic import ListView # Create your views here. class PostList(ListView): model = Post template_name = 'home.html' urls.py from django.urls import path from . import views urlpatterns = [ path('',views.ListView.as_view(),name ='list') ] traceback error File "D:\django\blog_env\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "D:\django\blog_env\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "D:\django\blog_env\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\django\blog_env\lib\site-packages\django\views\generic\base.py" in view 69. return self.dispatch(request, *args, **kwargs) File "D:\django\blog_env\lib\site-packages\django\views\generic\base.py" in dispatch 89. return handler(request, *args, **kwargs) File "D:\django\blog_env\lib\site-packages\django\views\generic\list.py" in get 142. self.object_list = self.get_queryset() File "D:\django\blog_env\lib\site-packages\django\views\generic\list.py" in get_queryset 39. 'cls': self.__class__.__name__ Exception Type: ImproperlyConfigured at / Exception Value: ListView is missing a QuerySet. Define ListView.model, ListView.queryset, or override ListView.get_queryset(). -
Django default isolation level with MariaDB and the BINLOG_FORMAT = STATEMENT error
I'm running a set of tests on my django webserver using pytest-django. I'm trying to switch from a MySQL database server to MariaDB in my testing/CI on travis, and for that I also switched from the mysqldb python package to pymysql. When using MariaDB, I suddenly get a strange exception for all my database related tests: pymysql.err.InternalError: (1665, 'Cannot execute statement: impossible to write to binary log since BINLOG_FORMAT = STATEMENT and at least one table uses a storage engine limited to row-based logging. InnoDB is limited to row-logging when transaction isolation level is READ COMMITTED or READ UNCOMMITTED.') This exception is below in a stack of several exceptions in all tests for that job, but I've identified it as the root cause for the issue. It's important to note that out of the two jobs that run the test-suite directly on travis, and another that runs it on docker (inside travis), only one fails, the one running on python 3.6. Although I roughly understand the cause of the problem I could not find a lot of information about the specifics or any reason for it to trigger/manifest all of a sudden. Except this Django documentation issue. Given it's only … -
Save form with user id Django
To make my question simple I have A Form That user can upload their cv's into databse. My forms.py class resume_upload(forms.ModelForm): cv = forms.FileField(required = True) job_title = forms.CharField(required = True) def save(self, commit=False): cvs = super(resume_upload, self).save(commit=False) cvs.cv = self.cleaned_data['cv'] cvs.job_title = self.cleaned_data['job_title'] if commit: cvs.save() class Meta: model = Cv fields = ('cv', 'job_title',) My models.py class Cv(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) cv = models.FileField(upload_to='cvs', default='', validators=[validate_file_extension]) job_title = models.CharField(max_length=100, default='') def __str__(self): return self.job_title and my views.py def upload_resume(request): if request.method == 'POST': form = resume_upload(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/') else: messages.error(request,"Oops! That didn't work. Please try again") else: form = resume_upload() return render(request, 'upload_resume.html',{'form':form,}) And the problem is it redirect to home page but i cant find object in admin panel -
call a request api function in views.py with ajax
Forgive me for stupid questions, but I do not really understand how such relationships work in the Web-development. I have views.py: As you can see there is a connection to the api and the information I need is parsed. Then in my template I have a listener that shows when the user reached the bottom of the page: As you can see at the bottom of the template i have ajax block where I again connect to api But now the most important question is this the right way? Do I need to connect json and fill my arrays and elements in the ajax block one time more? BUT It's all done in views.py.In general, is it realistic to call def main(request) from ajax all the time and append all my arrays and elements automatically? I need like smth this : $(window).scroll(function () { if ($(window).scrollTop() + $(window).height() == $(document).height()) { $.ajax({ url: "{% url 'main' %}",//my request which appends all my arrays automatically type: "GET", success: function () { }, error: function () { }); Sorry for such questions but I do not understand how such bundles work As for the counter of connected pages, I'll deal with this … -
In a django model, I want to do a table lookup for a list of column values to use as choices in one of my fields. Is it possible?
The model I'm trying to pull values has a different primary key than the column I'm trying to get the list from. This is what I was thinking but it doesn't work: class Server(models.Model): """ Model representing list of servers per contract """ os_license = models.CharField(max_length=95, blank=True, choices=product_list) @staticmethod def product_list(): return CustomerCatalog.objects.filter(account=Server.account).values_list('ccname', flat=True) -
No command 'pyhton' found, did you mean
a django store front, and for that I have created a virtual env. I ran the project for the first time and everything worked well and project was running, but now when i am trying to run pyhton manage.py runserverit is giving me the error: No command 'pyhton' found, did you mean: Command 'python' from package 'python-minimal' (main) Command 'python' from package 'python3' (main) pyhton: command not found I did everything the same way I did first time. So any idea what might be causing this issue. Also I have pyhton 3.5.2 -
Avoiding circular imports in Django Models (Config class)
I've created a Configuration model in django so that the site admin can change some settings on the fly, however some of the models are reliant on these configurations. I'm using Django 2.0.2 and Python 3.6.4. I created a config.py file in the same directory as models.py. Let me paracode (paraphase the code? Real Enum has many more options): #models.py from .config import * class Configuration(models.Model): starting_money = models.IntegerField(default=1000) class Person(models.Model): funds = models.IntegarField(default=getConfig(ConfigData.STARTING_MONEY)) #config.py from .models import Configuration class ConfigData(Enum): STARTING_MONEY = 1 def getConfig(data): if not isinstance(data, ConfigData): raise TypeError(f"{data} is not a valid configuration type") try: config = Configuration.objects.get_or_create() except Configuration.MultipleObjectsReturned: # Cleans database in case multiple configurations exist. Configuration.objects.exclude(Configuration.objects.first()).delete() return getConfig(data) if data is ConfigData.MAXIMUM_STAKE: return config.max_stake How can I do this without an import error? I've tried absolute imports -
Click a link to delete targeted content using ajax
I write a glypicon as a link to delete comment <a class="delCommentLink" href="{% url 'article:comment_delete' comment.id %}"> <span id="{{ comment.id }}" class="glyphicon glyphicon-trash" aria-hidden="true">delete</span> </a> I send the request using ajax, 1, retrieve the comment_url 2, get the grand-grand-parent element to hide, 3, send request to views.py and delete the target comment, $(document).ready(function () { $("body").on("click",".delCommentLink",function (e) { e.preventDefault(); var comment_url = $(e.target).parent().attr("href"); var $commentEle = $(e.target).closest(".comment"); if (window.confirm("Delete this comment?")) { $.ajax({ type: "get", url: comment_url, success: function (data) { var ret = JSON.parse(data); if (ret['status'] == 1) { $commentEle.hide(); } else { alert(ret['msg']); }; },//success });//ajax } else { e.preventDefault() } });//click event }) Click a link to delete it, my codes seems too many lines for such a routine task, How to complete it elegantly? -
TemplateDoesNotExist base.html
Getting issue while calling base.html in to other html pages Getting issue as, Exception Type: TemplateDoesNotExist Exception Value: base.html Below is my settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_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', ], }, }, ] index.html {% extends "base.html" %} <h1>Django</h1> {% block content %} <h1>Django</h1> {% endblock %} Any suggestions -
Column closingevent.id doesn't exist LINE 1: SELECT "closingevent"."id", "closingevent"."owner", "closing
I've a problem with my templates. I try to render the following template {% if liste_column %} <table> <tr><th>Owner</th> <th>RegimeID</th> <th>ClosingeventID</th> <th>Category</th> <th>Transaction or Closing</th> <th>**** Accounting Field</th> <th>Data Source</th> </tr> {% for item in liste_column %} <tr><td>{{item.owner}}</td> <td>{{item.regimeid}}</td> <td>{{item.closingeventid}}</td> <td>{{item.category}}</td> <td>{{item.transactionorclosing}}</td> <td>{{item.****accountingfield}}</td> <td>{{item.datasource}}</td> </tr> {% endfor %} </table> {% else %} <p>No Data are available.</p> {% endif %} And get the error: Column closingevent.id doesn't exist LINE 1: SELECT "closingevent"."id", "closingevent"."owner", "closing... My table has no column which is called "closingevent"."id" and I even didn't try to get this. I get it for other templates too. Can you help me? I think it could be the problem that my model doesn't have a primary key and just a foreign key. class Closingevent(models.Model): owner = models.CharField(max_length=800, blank=True, null=True) regimeid = models.ForeignKey('Regime', models.DO_NOTHING, db_column='regimeid') closingeventid = models.FloatField() category = models.CharField(max_length=800, blank=True, null=True) closingevent = models.CharField(max_length=800, blank=True, null=True) transactionorclosing = models.CharField(max_length=1, blank=True, null=True) ****accountingfield = models.CharField(max_length=1, blank=True, null=True) datasource = models.CharField(max_length=800, blank=True, null=True) debitacoountnumber = models.CharField(max_length=800, blank=True, null=True) debitsubitem = models.CharField(max_length=1, blank=True, null=True) debitaccountname = models.ForeignKey('Lineitemaccounting', models.DO_NOTHING,db_column='debitaccountname', blank=True,null=True,related_name='daccountname2') debitbalancesheet = models.CharField(max_length=1, blank=True, null=True) debitprofitandlose = models.CharField(max_length=1, blank=True, null=True) debitreconciliation = models.CharField(max_length=1, blank=True, null=True) creditaccountnumber = models.CharField(max_length=1, blank=True, null=True) creditsubitem = models.CharField(max_length=1, blank=True, … -
HTTP DELETE trigger 'def retrieve' method in Django Viewset insetad of 'def destroy'
I have a Django Viewset defined like: class TokenViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin): queryset = AccessToken.objects.all() serializer_class = TokenSerializer def list(self, request, *args, **kwargs): ## some logic def retrieve(self, request, *args, **kwargs): ## some logic @list_route(methods=["get"]) def count(self, request, *args, **kwargs): ## some logic def destroy(self, request, *args, **kwargs): ## some logic I send DELETE HTTP request for the Viewset to handle but somehow it always triggers the def retrieve(self, request, *args, **kwargs) method. How do I enforce the my viewset to call the def destroy(self, request, *args, **kwargs) instead ? -
mac django error Did you install mysqlclient or MySQL-python?
I am trying to set up a django rest project on my mac. Whenever I run python manage.py makemigrations it shows: Did you install mysqlclient or MySQL-python? error. However both of them are already installed. Full stack trace: (VB_env) staff-207-213:VB_Backend_SCG nitishpatkar$ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/nitishpatkar/Development/Vision Backlog rewrite/VB_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/nitishpatkar/Development/Vision Backlog rewrite/VB_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/Users/nitishpatkar/Development/Vision Backlog rewrite/VB_env/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/nitishpatkar/Development/Vision Backlog rewrite/VB_env/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Users/nitishpatkar/Development/Vision Backlog rewrite/VB_env/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/nitishpatkar/Development/Vision Backlog rewrite/VB_env/lib/python2.7/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/nitishpatkar/Development/Vision Backlog rewrite/VB_env/lib/python2.7/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "/Users/nitishpatkar/Development/Vision Backlog rewrite/VB_env/lib/python2.7/site-packages/django/db/models/base.py", line 124, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Users/nitishpatkar/Development/Vision Backlog rewrite/VB_env/lib/python2.7/site-packages/django/db/models/base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "/Users/nitishpatkar/Development/Vision Backlog rewrite/VB_env/lib/python2.7/site-packages/django/db/models/options.py", line 214, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/Users/nitishpatkar/Development/Vision Backlog rewrite/VB_env/lib/python2.7/site-packages/django/db/__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/Users/nitishpatkar/Development/Vision Backlog rewrite/VB_env/lib/python2.7/site-packages/django/db/utils.py", line 211, in __getitem__ backend = load_backend(db['ENGINE']) File "/Users/nitishpatkar/Development/Vision Backlog rewrite/VB_env/lib/python2.7/site-packages/django/db/utils.py", line 115, in load_backend return import_module('%s.base' % backend_name) … -
How to implement a 'global cache' in a Django application using memcache?
I am interested in learning memcached for Django. Let's say I want to do the following: If an alert box has already been raised for a given user and time of day, do nothing. If the alert has not yet been raised for this user at this time of day: Save the key (e.g., cache_key=alert_triggered~user1~2018-01-01_13:00) in memcached with a value of 1 and a timeout of 1 day (86400 seconds). Raise the alert I am trying to implement this to only pop up one alert box per user regardless of how many tabs they have the application open in. This is just an example problem to learn memcached in Django. My views below does not work on a tab-by-tab basis, nor application-wide on a per-user basis. Each time the function is called data returns None. views.py def get_context_data(self, *args, **kwargs): # e.g., cache_key = alert_triggered~user1~2018-01-01_13:00" cache_key = build_cache_key(username, time) cache_time = 86400 data = cache.get(cache_key) print(data) # printing 'None' every time with identical keys # if data is None, key does not exist in cache, add it. if data is None: cache_value = 1 cache.set(cache_key, cache_value, cache_time) alert_needed = True # raise alert in Django template if True context['alert_needed'] = … -
Django: forms & initial data
In order to display the ticket_reference with {{ form.initial.ticket_reference }}, include the field ticket_reference in forms.py. While I can hide this field through forms.HiddenInput(), I now wonder if this is 'save'? The user shouldn't be able to change this hidden field, but currently, I think with some knowledgeable people would be able to change this hidden field data, and therefore it's ticket_id. Did you face a similar question before? .html-file <form method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="card mt-5"> <div class="card-header"> Ticket ref: {{ form.initial.ticket_reference }} </div> <div class="card-body"> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputAddress">{% trans "First name" %}</label> {{ form.first_name }} [...] forms.py class AssignAttendeeForm(forms.ModelForm): class Meta: model = Attendee fields = ( 'ticket_reference', 'first_name', 'last_name', 'company_name', 'email', ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['ticket_reference'].widget = forms.HiddenInput() -
Migration error in django
when I tried to migrate Django using Mysql server, I got the error: django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'value' used in key specification without a key length") When I searched this error, I found -->MySQL error: key specification without a key length. but I occur error while migration. django version - 1.11.5, mysql version - 5.7.20 please help me to find the problem. thanks in advance -
Runing two webapps from one server?
I have a server that contains the first webapp I evermade, the server capacity is half used (cpu nor hdd) but it still earns some money. I don't want to remove the app but I would like to host a new project there, however the setup is very ... let's say "my-first-app-style" bad. For exemple there is no virtual enviroment there. This is the folder structure I am thinking about: /public_html/ /apps /core_app /3rd_apps #old-app django is here /static /media /new_app #this would be my new app /new app folders #with different django The new_app would have it's own django and everything else. Currently my enviroment variables point to apps, 3rd_apps and core_app. I am not sure what would happen if I introduce a new app and point more enviroment variables towards the new_app folders. Also, currently I am using nginx, gunicorn, postgres server and supervisor there. I think using the same database server (and create a new database) for the new app should not be a problem. Supervisor should also be no problem. I think I can setup nginx to handle two domains in different locations. My biggest fear is that the two djangos are going to fight each … -
chat app using websocket python+django+angular
I want to make one real-time chat application using websockets and the frontend is angular5. So, I create websocket in purepython and backend is Django and frontend is angular5. Myquestion is when i create websocket service in python. So, do i have to make websockets services in angular too? -
Django/jQuery Datatables access to datatable parameters
I've been using jQuery dataTables a little bit, and I used to access to dataTable informations. This time, I decided to add pagination at the beginning and at the end, and python raise this error. How can I access to the first element of the dict ? Maybe by using an other method ? django.utils.datastructures.MultiValueDictKeyError: 'iDisplayStart' My view @csrf_exempt def lexeme_to_json(request): query = request.session.get('queryset') search = request.GET.get('sSearch', '') sort_by = int(request.GET.get('iSortCol_0', '0')) asc = request.GET.get('sSortDir_0', 'asc') == 'asc' display_all = request.GET.get('iDisplayLength') == '-1' start = int(request.GET['iDisplayStart']) # crashes right here end = start + int(request.GET['iDisplayLength']) JS/jQuery datatable configuration $('#dataTable').dataTable({ "bJQueryUI": true, "dom": "<'#datatableFirstLine'<'row'<'col-lg-3'i><'col-lg-3 offset-lg-6'p>>>" + "<'#datatableSecondLine'<'row'<'col-lg-3'l><'col-lg-5 offset-lg-4'f>>>" + "<'#datatableThirdLine'<'row'<'col-lg-12'tr>>>" + "<'#datatableFourthLine'<'row'<'col-lg-3'i><'col-lg-3 offset-lg-6'p>>>", "aoColumns": [ {"bSortable": true, "sWidth": "1%"}, {"bSortable": true, "sWidth": "12%"}, {"bSortable": true, "sWidth": "12%"}, {"bSortable": true, "sWidth": "1%"}, {"bSortable": true, "sWidth": "1%"}, {"bSortable": true, "bSearchable": false, "sWidth": "3%"}, {"bSortable": false, "sWidth": "7%"}, ], "iDisplayLength": 100, "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]], "bProcessing": true, "bServerSide": true, "ajax": { "url": "lexeme_to_json/", "type": "POST" } }); -
user authenticate is not working Django
user is not getting authenticated when i try to login. this my register code def register(request): if request.method == "POST": username = request.POST["name"] email = request.POST["email"] password = request.POST["password"] password2 = request.POST["password2"] try: if password2 != password: messages.error(request, "password did'nt match") elif User.objects.get(email=email): messages.error(request, "user already exists") except: if email and username: user = User.objects.create_user(username=username, email=email) user.set_password(password) user.save() messages.success(request, "user created") else: messages.error(request, "Looks like user already exists") return render(request, 'register.html', {}) this if my login code if i am using user.object.get for email and check_password for password it,s working but when i am using authenticate it,s not working . printing authenticate is returning None def login(request): if request.method == "POST": email = request.POST["email"] password = request.POST["password"] print email print password try: user = authenticate(email=email , password=password) if user is not None: login(request, user) return redirect('dashbord') else: messages.error(request, "password yesn't match") except: messages.error(request, "login fail plz check ur password or email again") return render(request, 'login.html', {}) -
Migration error in django using MySql db
I have downloaded Mayan EDMS-Electronic Document Management System from GitHub and I configured project using Django server. I had added the required libraries based on requirement. when I tried to migrate Django using Mysql server, I get error: django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'value' used in key specification without a key length") When I searched this error, I found -->MySQL error: key specification without a key length. but I occur error while migration. django version - 1.11.5, mysql version - 5.7.20 please help me to find the problem. thanks in advance -
Django can't find static files on server
So I have this problem with deploying static files on server with Django. I am running nginx, and successfully tested my website locally, but now, when I'm deploying my site on the web, I can't load the local files, despite I have done everything according to the instructions. So I got this error all the time "GET /staticold/botadd/anyfile HTTP/1.0" 404 99 My settings.py static settings looks like this STATIC_URL = '/staticold/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'botadd/static'), ) I've also tried it like this STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') python manage.py collectfiles command is successfull, all of my files are transfered to STATIC_ROOT folder, but then I got that 404 error. What can it be, I am stuck -
Url rerouting after making an entry Django admin add page
After making an entry in django admin, django routes directly to entries page. What I want is to go to main admin page. Do I need to overwrite the admin views file or is there a way to extend it and change the url routing? -
Static file was not found after Django server was run
I am new in programming and in Django and trying to understood core concepts instead of just copy/paste some simple solutions)) there is a huge bunch of cases and answers for my problem but they all are different and make mess in my head instead of help) I have followed book recommendations but it does not works for me.Please, help me understand my core mistace Result: System check identified no issues (0 silenced). July 16, 2018 - 20:37:29 Django version 2.0.5, using settings 'locallibrary.settings' Starting development server at http://127.0.0.4:8000/ Quit the server with CONTROL-C. [16/Jul/2018 20:56:46] "GET / HTTP/1.1" 200 1457 [16/Jul/2018 20:56:46] "GET /static/catalog/css/catalog.css HTTP/1.1" 404 1794 # structure Development manage.py <Project> ( _init_.py, settings.py, urls.py, wsgi.py, rootstatic(to collect information) ) <Catalog> (_init_.py, models.py, tests.py, views.py, static [catalog/css/catalog.css/] #settings DEBUG = True import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_URL = '/static/' STATIC_ROOT = '%s/rootstatic/' % (BASE_DIR) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['%s/templates/'% (PROJECT_DIR),], 'APP_DIRS': True, }, ] # urls from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) # template <link href="{% static 'catalog/css/catalog.css' %}" rel="stylesheet"> -
Django. access database through model on shutdown hook
Here is my problem, i'm trying to update database through django-model on shutdown signal which is declared on init.py file but database on model object is None import logging import os import signal import sys from django.db import transaction logger = logging.getLogger("logger") def my_signal_handler(*args): if os.environ.get("RUN_MAIN") is not "true": return from mymodels import MyModel logger.info("update models") with transaction.atomic(): for model in MyModel.objects.all(): if model.my_flag: model.my_flag = False model.save() sys.exit(0) signal.signal(signal.SIGINT, my_signal_handler) Also when i'm trying to import model outside my_signal_handler function application throws exception "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet." The question is: what's the better way to append shutdown hook that can access application context