Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Creating new User object via the Admin gives unexpected errors even if form is filled
Hey there I am trying to add a new user from Django's admin panel. From the screenshot below, you can see that even though I have correctly filled in each form input, errors are still raised by Django. I am wondering what the causes for this may be? If anyone could suggest how I'd find the solution to this problem then that'd be amazing... Quick side question is how to get the password as a password input? Code below: admin.py... from .models import UserModel, UserProfileModel from django import forms from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField class UserCreationForm(forms.ModelForm): password = forms.CharField(label='Password',widget=forms.PasswordInput) passwordrepeat = forms.CharField(label='Confirm Password',widget=forms.PasswordInput) class Meta: model = UserModel fields = ('email',) def clean_password(self): # Check that the two password entries match password = self.cleaned_data.get('password') passwordrepeat = self.cleaned_data.get('passwordrepeat') if password and passwordrepeat and password != passwordrepeat: raise forms.ValidationError("Passwords do not match") return passwordrepeat def save(self, commit=True): # Save the provided password in hashed format user = super(UserCreationForm, self).save(commit=False) user.set_password(self.clean_password['password']) if commit: user.save() return user class UserUpdateForm(forms.ModelForm): password = ReadOnlyPasswordHashField() class Meta: model = UserModel fields = ('email','password','is_active','is_admin') def clean_password(self): # Regardless of what the user provides, return the … -
why am i getting a tox import error before the dependencies are installed
in my django project, I have a an init.py file that imports celery, I suspect this may be causing tox to complain. /testproj/testproj/ ____init___.py from .celery import app as celery_app when I run tox, the tests successfully run, but I see this error. File "/dir/work/testproj/testproj/celery.py", line 2, in <module> from celery import Celery ImportError: cannot import name Celery mobilereports installed: amqp==1.4.9,anyjson==0.3.3,appdirs==1.4.0,Babel==2.3.4,billiard==3.3.0.23,cached-property==1.3.0,celery==3.1.24 What I find strange is that the import error is above the actual imports where celery gets imported. Why am I getting this error? celery is in my requirements.txt which is being installed by tox as you can see above, so why would i get an import error before the deps actually get installed? tox.ini [tox] envlist = mobilereports skipsdist = True [env] commands = ./runtests.sh setenv = DJANGO_SETTINGS_MODULE=testproj.settings PYTHONPATH={toxinidir} [base] deps = -r{toxinidir}/requirements.txt [env:testproj] basepython = python3 deps = {[base]deps} -
BooleanField not showing the selected value on Update
In a model I have defined the following field: manager = models.BooleanField(choices=BOOL_TYPE_CHOICES, default=BOOL_TYPE_NO) In forms: 'manager': RadioSelectWidget(choices=BOOL_TYPE_CHOICES) In widget: class RadioSelectWidget(forms.RadioSelect): template_name = 'widgets/radio-select.html' I use a custom widget just to add some classes to the Django html. The problem is not the widget, because I use the same widget in combination with SmallInteger an there are no issues. But with Boolean, one update, no option is selected, on create is ok, the default one is selected. -
Celery Tasks on Django Models
I'm trying to learn how to use celery to check a date every day on one of my models. One of my models holds an expiration date and a boolean field that says whether their insurance is expired or not. The model is pretty big so I'm going to post a condensed version. I think I have two options. Either run a celery task on the model method or rewrite the function in my tasks.py. Then I need to use Celery beat to run the schedule to check daily. I've got the function to work, but I'm passing in the model objects directly which I think is wrong. I'm also having trouble on how to use the args in the celery beat scheduler inside of my celery.py. I'm really close to getting this to work, but I think I'm going about executing a task in the wrong way. and I think executing a task on the model method might be the cleanest, I'm just not sure how to accomplish that. models.py class CarrierCompany(models.Model): name = models.CharField(max_length=255, unique=True) insurance_expiration = models.DateTimeField(null=True) insurance_active = models.BooleanField() def insurance_expiration_check(self): if self.insurance_expiration > datetime.today().date(): self.insurance_active = True self.save() print("Insurance Active") else: self.insurance_active = False self.save() … -
How to deploy Django on IIS with git hooks using virtenv on a remote Windows server?
I successfully installed and setup Django (2.0.2) using Python 3.6.4 on IIS on a remote Windows Server 2012 R2 (in a VPN environment) accordingly to this instruction: http://blog.mattwoodward.com/2016/07/running-django-application-on-windows.html I'm using SQL Server as backend and I stored the sensitive data such as the DJANGO_SECRET_KEY, DATABASE_PASSWORD etc. as environment variables in the FastCGI Settings at the IIS (see the above link, section Configure FastCGI in IIS step 14) At this point I asked me, how to deploy my apps and do all the necessary setps like install packages from requirements.txt, collectstatic, makemigrations etc. With googleing I found a possible solution using git hooks, especially a post-receive hook accordingly to this post: https://dylanwooters.wordpress.com/2015/02/21/one-command-deployments-to-iis-using-git/ So I successfully setup Bonobo Git Server on the same IIS accordingly to this instruction: https://bonobogitserver.com/install/ My thought was to put all the required commands into this post-receive hook file as I would do in the development environment. I ended up with this file at location \inetpub\wwwroot\Bonobo.Git.Server\App_Data\Repositories\myapp-master\hooks\post-receive: #!/bin/sh DEPLOYDIR=/c/apps/myapp VIRTENVDIR=/c/virtualenvs/myapp GIT_WORK_TREE="$DEPLOYDIR" git checkout -f cd $VIRTENVDIR source Scripts/activate cd $DEPLOYDIR pip install -r requirements.txt python manage.py collectstatic --noinput python manage.py makemigrations python manage.py migrate I grant permission to the Scripts/activate file and I receive no erros during push from … -
getting data from one django to a template from another django app
Have Two Django Apps. Work and Blog The Blog App template folder has the index.html Here is the view.py from work from django.shortcuts import render from . import models from work.models import Work from blog import views # Create your views here. def work(request): template_name = "blog/templates/index.html" work_list = Work.objects.all context={'work_list':work_list} return render(request,template_name,context) I want it to be shown in index.html which is in the blog app <div class="work"> <section id = "work-list"> <div class="container"> <div class = "row"> {% for works in work_list %} <div class="col-md-4"> <div class="lol"> <img class="img-rounded img-responsive" src = "{{works.image}}" alt=""> </div> </div> {%endfor%} </div> </div> </section> </div> index.html is in the blog app This is the directory blog template index.html models.py views.py Work views.py models.py -
Django templates links broken
I have two pages that use base.html as a base template: index.html and login.html. login.html has a fully functional nav bar (links and :hover working) where index.html shows the nav bar but won't recognise the links. Bear with me as this is my first post, so I have no idea what I need to provide etc... base.html: <!DOCTYPE html> <html> <head> <title>{% block title %}Graduate Proofreading | Professional Essay Proofreading{% endblock title %}</title> {% block head_meta %} {% block head_meta_charset %} <meta charset="UTF-8"> {% endblock head_meta_charset %} {% block head_meta_contentlanguage %} <meta http-equiv="Content-Language" value="en-UK" /> {% endblock head_meta_contentlanguage %} {% block head_meta_viewport %} <meta name="viewport" content="width=device-width, initial- scale=1"> {% endblock head_meta_viewport %} {% endblock head_meta %} {% block head_css %} {% block head_css_site %} <!--=================================CSS LINKS==========================================--> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link rel="stylesheet" href="https://www.w3schools.com/lib/w3-theme-cyan.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"> <script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script> <!-- Custom fonts for this template--> <!-- Custom styles for this template--> {% endblock head_css_site %} {% block head_css_section %} <style type="text/css"> </style> {% endblock head_css_section %} {% block head_css_page %} {% endblock head_css_page %} {% endblock head_css %} </head> <body> <!-- Hidden Side Navigation --> <nav class="w3-sidebar w3-bar-block w3-card w3-animate-left w3- center " style="display:none" id="mySidebar"> <h1 class="w3-xxxlarge w3-text-theme">Side Navigation</h1> <a href="#" … -
Django Login Incorrect password showing for correct password
I am making a login form and using Django 1.8 Python 3.5 But I am getting Incorrect password for valid username and password what should I do ? I have made a simple login form but am not able to figure out the error , please help This is my login/forms.py from django import forms from mainpage.models import User from django.contrib.auth import ( authenticate, login, logout, get_user_model, ) class UserLoginForm(forms.Form): username=forms.CharField(max_length=40) password=forms.CharField(max_length=40,widget=forms.PasswordInput) def clean(self,*args,**kwargs): username=self.cleaned_data.get("username") password=self.cleaned_data.get("password") user_qs = User.objects.filter(username=username) if user_qs.count() == 0: raise forms.ValidationError("The user does not exist") else: if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("Incorrect password") if not user.is_active: raise forms.ValidationError("This user is no longer active") return super(UserLoginForm,self).clean(*args,**kwargs) This is my login/views.py def login_view(request): form1=UserLoginForm(request.POST or None) print(request.user.is_authenticated()) if form1.is_valid(): username=form1.cleaned_data.get("username") password=form1.cleaned_data.get("password") user=authenticate(username=username,password=password) auth_loginwa(request,user) if(request.user.is_authenticated()): return redirect("home2") context= { "form1": form1, } return render(request, "login.html",context) This is my mainpage/models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) -
Working with ManyToManyField
How to get a choice from one to several Executors (owner) from the group "Technical support", in the selection field in the application in the admin panel. Now I can only configure to receive one, and no more, performers. Used ForeignKey: class Application(models.Model): ... owner = models.ForeignKey(User, null = True, blank = True, limit_choices_to={ 'groups__name': 'Техническая поддержка'}) After reading, I realized that i can get them through ManyToManyField, and did the following: class Owner(models.Model): executor = models.ForeignKey(User, null = True, blank = True, limit_choices_to={ 'groups__name': 'Техническая поддержка'}) class Application(models.Model): ... owner = models.ManyToManyField(Owner, verbose_name = 'Исполнитель') But, the performer is taken not from the group "Technical support", but from the "executor", which still needs to be created. And even if to create, the choice will be as follows: enter image description here In general, I just can not figure it out. Many thanks to all those who try to help with this problem. -
Sending Data from Django view to model
I have JSON variable which I can get from Javascript.I want to save it in database.I am not able to write exact view function for it My models.py from django.db import models from django.utils import timezone from django.utils import simplejson as json class update_grid(models.Model): data = JSONField(null=True, blank=True) My View.py def save_grid(request): if request.method == 'POST': data = json.loads(request.body)# I want to send this variable to update_grid and save it return HttpResponse('success') # if everything is OK -
Type "unsigned" doesn't exist django
I am really new to Django, I have to query the database and have to take an average of a charfield (tday is charfield) so in order to cast the charfield to int I used extra() function as follows but it gave me an error. Following is my query and then the error: from django.db.models import Avg from django.db.models.functions import Cast tday=TableName.objects.filter(tday__contains="20090").extra({'tday_int':"CAST(tday as UNSIGNED)"}).order_by('-tday_int') The error: django.db.utils.ProgrammingError: type "unsigned" does not exist. Thanks in advance! -
Django: overriding insert, update, delete in a model
Sometimes you want to do something when there is an event for model (on create object, on update object, on delete object). There is a method you can override in Model called save. And it even has a parameter forced_insert which I first thought would always be set to a proper value meaning whether an object will be created or updated. But the parameter is optional and you cannot expect it to be right. Searching in source code of Model led me to methods _do_update and _do_insert, but the underscore at the beginning tells me that this method is not recommended for use. And it also have a lot of parameters which pollute code when you override it. The only solution left that I could find is using django.db.models.signals. But I believe they are meant to be used for external purposes like when you want to create a UserProfile on every User create. But I have some internal purposes like updating fields on update. Also using signals makes code look spreaded and harder to understand. -
Django dynamic localization of "translation strings"
a bit of background, I have a working project written in Django which is something like internet shop with a blog. For now, my customer needs an ability to add translations and new languages on the fly. The model related part can be easily done using one of many libraries (like django-modeltranslation, django-parler ...). The problem is with translatable strings and formatting. Updating translatable strings can be somehow covered by django-rosseta (works with .po, compiles them and reloads the server, but is it ok?). And how to handle adding new language without touching source code (settings.LANGUAGES section)? Ideally, all localization-related data should be stored in the database with some kind of caching. Any ideas? -
django authentification error
I am running into an error where I am logging in a user and it is supposed to redirect to details.html but instead the the url gets parsed but it stays at login.html. I believe there is a problem with the views.py. If there is a better way of doing this please let me know. Thanks views.py @login_required(login_url="http://127.0.0.1:8000/accounts/login/") def patientDetails(request, personalInfo_id): current_user = request.user if personalInfo_id == current_user.id: return render(request, 'personalInfo/details.html', {}) else: return render(request, 'personalInfo/login.html', {}) @login_required(login_url="http://127.0.0.1:8000/accounts/login/") def after_login(request): return HttpResponseRedirect('/personalInfo/details/%d/'%request.user.id) urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^details/$', views.after_login, name='patient'), url(r'^details/(?P<personalInfo_id>[0-9]+)/$', views.patientDetails), ] Picture of what is going wrong -
Django - KeyError when updating User within the Admin Panel
I've been following this tutorial and every time I attempt to save/update the user then I get the following error... KeyError at /admin/accounts/usermodel/1/change/ u'password' Full traceback here... Environment: Request Method: POST Request URL: http://localhost:8000/admin/accounts/usermodel/1/change/ Django Version: 1.11.7 Python Version: 2.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.gis', 'django.contrib.humanize', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', 'rest_framework', 'accounts', 'main', 'objects'] Installed 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'] Traceback: File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in wrapper 551. return self.admin_site.admin_view(view)(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/Library/Python/2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/Library/Python/2.7/site-packages/django/contrib/admin/sites.py" in inner 224. return view(request, *args, **kwargs) File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in change_view 1511. return self.changeform_view(request, object_id, form_url, extra_context) File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in changeform_view 1408. return self._changeform_view(request, object_id, form_url, extra_context) File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in _changeform_view 1440. if form.is_valid(): File "/Library/Python/2.7/site-packages/django/forms/forms.py" in is_valid 183. return self.is_bound and not self.errors File "/Library/Python/2.7/site-packages/django/forms/forms.py" in errors 175. self.full_clean() File "/Library/Python/2.7/site-packages/django/forms/forms.py" … -
PermissionError: [Errno 13] Permission denied in Django
I have encountered a very strange problem. I'm working with django, I create a directory on server, and try to save pickle file into it, this way: with open(path, 'wb') as output: pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL) And get: PermissionError: [Errno 13] Permission denied I tried to give all permissions to this directory, this way: os.chmod(save_full_path, stat.S_IWOTH | stat.S_IWUSR | stat.S_IWGRP) but this didn't help. Although directory seems to have all permissions(0o777), I still get this error. By the way, I have no problems with saving uploaded files to this directory. I'm very new to django, I would really appreciate if someone explained me what am I doing wrong. -
Can we automatically delete entry from database after specified time in Django?
I am not able to think the solution other than creating timer in one thread. Is there any more efficient than this one? -
Bug in production - A static file is corrupted for a specific user?
Sorry for the ambiguous title, I just couldn't find a better description of this bug. One of our users had problems with the site, and saw a Syntax Error in one of the Javascript files in the dev console. When he opened it, he saw it was corrupted: He sent me the contents of the file (went directly to the URL and saved with Ctrl+S) and when I opened it with Sublime it seemed to be nulled-out (the binary is all zeros). This only happened to him and it doesn't seem to go away, even after a full restart. I initially thought it was just a corrupted response and Chrome cached the file, but even with Shift+F5 he is still getting the problem. The user runs Chrome 64.0.3282.186 the server is running django on AWS. -
Django API and Front-End Separation
I am using Djnago for REST API. Currently, I am generating primitive web pages from the same Django project. I think it's in my interest to separate API logic and front end. What is a best way to do this? Should I create another Django app, that just calls this API and generates web pages from template or should I use some other framework for this? Thanks -
I'm new to geodjango. I run python manage.py makemigrations. The following error occurs:
(py35_64) E:\Ahas\GEODJANGO\geodjango>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Anaconda2\envs\py35_64\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 985, in _gcd_import File "<frozen importlib._bootstrap>", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 957, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 697, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\db\models\base.py", line 114, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\db\models\base.py", line 315, in add_to_class value.contribute_to_class(cls, name) File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\db\models\options.py", line 205, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\db\__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\db\utils.py", line 202, in __getitem__ backend = load_backend(db['ENGINE']) File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\db\utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "C:\Anaconda2\envs\py35_64\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "C:\Anaconda2\envs\py35_64\lib\site-packages\django\contrib\gis\db\backends\postgis\base.py", line 6, in <module> from .features import DatabaseFeatures File … -
How to create function for an API function not belonging to any model class?
So I am using Django/DRF for my backend and I want the client (my web app) to be able to make an API call that looks up tags for an image using Google Cloud Vision API. Obviously, I don't want the client to have access to the API key, hence the server should perform the actual call to Google's API. What I'm struggling with currently is where to put this API function. Do I have to create a model for this (even though there is no db table) or is there some way around that? -
'to_field_name' argument on a ModelChoiceField() doesn't seem to be working
Well, pretty much what it says in the title. I'm creating a ModelChoiceField() in one of my Forms, like so: class FormCreatePlace(forms.ModelForm): (...) category = forms.ModelChoiceField(queryset=Category.objects.all(), to_field_name='name') (...) The Category model is defined like so: class Category(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=40) And yet the field itself on the HTML form insists on displaying the primary keys (a series of UUIDs) as the choices. What am I doing wrong? -
How Django stores emojis in mysql tables with utf8 charset?
I have a Django 1.4 app that was saving text in mysql database with utf8 charset. Everything worked fine, but I came across a problem when I wanted to read this data using ruby where strings with emojis were throwing invalid byte sequence in utf-8 exception. Quick search told me that I should've use utf8mb4 charset in mysql, but since these strings don't appear to be valid utf-8 at this moment, simple alter table changing the charset is not fixing the problem. How was Django saving these strings in the first place, making emojis work with utf8 (and not utf8mb4) charset work? -
Django filter choices by keywords
I am using django filter and I am having some issues. I have a filter for "colours" that I wish to have fixed choices for eg. blue, green, red. I would like to have a key, value pair that checks that if a keyword is in that colour, it matches. I am importing a product feed so the colour words may vary e.g blck, charcoal. I also have a filter for "brand" which shows all available brands, however I only want to render options available in that Category. filters.py import django_filters from .models import Product, Brand, Category, Colour, Size from django.forms import CheckboxSelectMultiple class ProductFilter(django_filters.FilterSet): search_price__gt = django_filters.NumberFilter(name='search_price', lookup_expr='gt') search_price__lt = django_filters.NumberFilter(name='search_price', lookup_expr='lt') brand_name = django_filters.filters.ModelMultipleChoiceFilter( label='Brand',widget=CheckboxSelectMultiple, queryset = Brand.objects.all()) colour = django_filters.filters.MultipleChoiceFilter(choices=Colour.COLOURS, label='Colour',widget=CheckboxSelectMultiple) size = django_filters.filters.ModelMultipleChoiceFilter( label='Size',widget=CheckboxSelectMultiple, queryset = Size.objects.all()) class Meta: model = Product fields = ['brand_name', 'colour', 'size'] models.py from django.db import models from mptt.models import MPTTModel, TreeForeignKey, TreeManager class Category(MPTTModel): regex = models.CharField(max_length=100, blank=True) name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_together = (('parent', 'slug',)) verbose_name_plural = 'categories' def get_slug_list(self): try: ancestors = self.get_ancestors(include_self=True) except: ancestors = [] else: ancestors = … -
Django - Serving statics with views and not with django.contrib.staticfiles
Im new in DJango and I need to change current static serving mode removing the /static Alias from Apache configuration (and relative STATIC_URL from default_settings) Alias /static/ /usr/local/app/static/ On django settings: STATIC_URL = '/static/' to a internal serving services using a local view. I have added a new constant in settings.py STATIC_WEB_ROOT = os.path.join(BASE_DIR, 'static/frontend/') urls.py from django.conf.urls.static import static url(r'^%sstatic/(?P<path>.*)$' % , static , {'document_root': STATIC_WEB_ROOT }, name='static.file.serve'), index.html <script type="text/javascript" src="{% url 'static.file.serve' 'frontend/js/jquery-3.2.1.min.js' %}" ></script> Unfortunally, I get a 404: "GET /static/frontend/js/jquery-3.2.1.min.js HTTP/1.1" 404