Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serve entirely static (documentation) website from Django url in Django 1.10
I am using mkdocs for a wiki documentation site that serves markdown tutorials and general information files created by various people. mkdocs ouputs an entirely static site in a site directory. Is there anyway to serve this site in django 1.10? I know you used to be able to do something like this: url(r'^docs/wiki/', 'django.views.static.serve', {'document_root': base.DOCS_ROOT, 'path': 'index.html'}), url(r'^docs/wiki/(?P<path>.*)$', 'django.views.static.serve', {'document_root': base.DOCS_ROOT}), but that no longer works in Django 1.10 because views must be callable lists or tuples. I would prefer to not serve this out of templates because the assets for the website in order not to split the assets mkdocs creates into the django static directory from the html files it creates that would presumably be in templates. error given if attempted to run server: raise TypeError('view must be a callable or a list/tuple in the case of include().') Any simple way to do this with urls? -
Too many python initialization on httpd start
im runing python/django on apache using modwsgi i've been looking trough my apache error_log and i've noticed something strange i only have 2 virtual host with wsgi daemon but when i start httpd service i get lots of python initialization (i've counted 17) here is one the other one is just like this WSGIDaemonProcess myproject python-path=/home/xyz/public_html/myproject:/usr/local/lib/python3.4/site-packages/ WSGIProcessGroup myproject WSGIScriptAlias / /home/xyz/public_html/myproject/myproject/wsgi.py <Directory /home/xyz/public_html/myproject/myproject> <Files wsgi.py> Order deny,allow Require all granted WSGIProcessGroup myproject </Files> </Directory> Alias /static/ /home/xyz/public_html/myproject/static/ <Directory /home/xyz/public_html/myproject/static> Require all granted </Directory> here is what i get when i start httpd [Tue Nov 22 06:23:46.979171 2016] [unique_id:info] [pid 14914] AH01566: using ip addr 136.243.122.67 [Tue Nov 22 06:23:47.000460 2016] [ssl:info] [pid 14914] AH01887: Init: Initializing (virtual) servers for SSL [Tue Nov 22 06:23:47.000491 2016] [ssl:info] [pid 14914] AH01914: Configuring server static.67.122.243.136.clients.your-server.de:443 for SSL protocol [Tue Nov 22 06:23:47.002249 2016] [ssl:info] [pid 14914] AH02568: Certificate and private key static.67.122.243.136.clients.your-server.de:443:0 configured from /var/cpanel/ssl/cpanel/mycpanel.pem and /var/cpanel/ssl/cpanel/mycpanel.pem [Tue Nov 22 06:23:47.002850 2016] [ssl:info] [pid 14914] AH01876: mod_ssl/2.4.18 compiled against Server: Apache/2.4.18, Library: OpenSSL/1.0.1e [Tue Nov 22 06:23:47.002916 2016] [suexec:notice] [pid 14914] AH01232: suEXEC mechanism enabled (wrapper: /usr/local/apache/bin/suexec) [Tue Nov 22 06:23:47.003027 2016] [:notice] [pid 14914] ModSecurity for Apache/2.9.0 (http://www.modsecurity.org/) configured. [Tue Nov 22 … -
How do I use a dictionary from django in my google maps api?
I'm using the Google maps api and Django to build a web app. I want to display on the map some markers and infowindows that have information relating to my app. I have a dictionary in my views.py file that has the data I need, however I cannot use that dictionary because it does not work with javascript. How should I pass in my dictionary from views.py to the google-maps.html file, so that I can use it in my javascript code? -
Uploading a file to django model with a form - is_valid() fails
I'm trying to upload a file to a django model with a form, however it fails when it reaches form.is_valid(). I'm adding the form to a twitter bootstrap modal, which I guess could be causing issues? When I print form.errors, I get a message saying that the form is required. I'm obviously adding a text file to the form before submission, so I'm not sure what the issue could be. views.py - Successfully gets past 'request.method == 'POST'. Fails at form.is_valid() if request.method == 'POST': form = ConfigurationForm(request.POST, request.FILES) print("ERROR " + str(form.errors)) if form.is_valid(): print("Success") elif not form.is_valid(): print("Failed") forms.py from django import forms from .models import NetworkApplications class ConfigurationForm(forms.Form): config_file = forms.FileField(label="Select a file") class Meta: model = NetworkApplications In my template: <form method="post" enctype="multipart/form-data">{% csrf_token %} {{form.config_file}} </form> request.FILES seems to be empty. form.errors returns this: <ul class="errorlist"><li>config_file<ul class="errorlist"><li>This field is required.</li></ul></li></ul> -
ValueError: not enough values to unpack (expected 2, got 1)
the following is my code views.py from django.shortcuts import render from .forms import MedicineForm from .models import Medicine def index(request): all_medicine = Medicine.objects.order_by('id') return render(request, 'medicine/index.html', {'all_medicine': all_medicine}) def add(request): if request.method == 'POST': form = MedicineForm(request.POST) if form.is_valid(): new = Medicine() new.name = form.cleaned_data['药品名称'] new.price = form.cleaned_data['药品价格'] new.number = form.cleaned_data['药品编号'] new.sort = form.cleaned_data['药品分类'] new.unit = form.cleaned_data['计价单位'] new.save() return render(request, 'medicine/index.html') else: form = MedicineForm() return render(request, 'medicine/add.html', {'form': form},) forms.py from django import forms class MedicineForm(forms.Form): 药品编号 = forms.IntegerField() 药品名称 = forms.CharField(max_length=100) 药品价格 = forms.IntegerField() jj_choice = { '瓶': '瓶', '包': '包', '盒': '盒', } 计价单位 = forms.ChoiceField( choices=jj_choice ) 药品分类 = forms.CharField(max_length=100) add.html: {% extends 'polls/index.html' %} {% block medicine_form %} <form action="http://localhost:8000/medicine/add/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="添加药品" /> </form> {% endblock %} traceback: File "E:\p\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "E:\p\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "E:\p\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "F:\ddjj\x\mysite\medicine\views.py" in add 25. return render(request, 'medicine/add.html', {'form': form},) File "E:\p\lib\site-packages\django\shortcuts.py" in render 30. content = loader.render_to_string(template_name, context, request, using=using) File "E:\p\lib\site-packages\django\template\loader.py" in render_to_string 68. return template.render(context, request) File "E:\p\lib\site-packages\django\template\backends\django.py" in render 66. return self.template.render(context) File "E:\p\lib\site-packages\django\template\base.py" in render 208. return … -
'collections.OrderedDict' object has no attribute 'id'
I have an Event model and it has a many2many field with default user model. class Event(models.Model): name = models.CharField(max_length=50) type = models.CharField(max_length=50) location = models.CharField(max_length=255) start_hour = models.CharField(max_length=50) end_hour = models.CharField(max_length=50) creator = models.CharField(max_length=50) info = models.CharField(max_length=255, default='') users = models.ManyToManyField(User) def __str__(self): return self.name Now, I am trying to update this many2many field like following; //my serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id',) class EventSerializer(serializers.ModelSerializer): users = UserSerializer(many=True) class Meta: model = Event fields = ('id', 'users') def update(self, instance, validated_data): submitted_users = validated_data.get('users') if submitted_users: for user in submitted_users: user_instance = User.objects.get(id=user.id) instance.users.add(user_instance) instance.save() return instance //views.py class UpdateParticipants(generics.UpdateAPIView): queryset = Event.objects.all() serializer_class = EventSerializer However, I am getting an error like in the belowe image -
django error logging : [Errno 13] Permission denied
im trying to enable error loging for my site so i've created a file called log.txt i nthe root of my project /home/xyz/public_html/projectname/log.txt and in my setting.py in this address : /home/xyz/public_html/projectname/projectname/settings.py i have a simple logging setting : LOGGINGs = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'log.txt', 'formatter': 'verbose' }, }, 'loggers': { 'django': { 'handlers':['file'], 'propagate': True, 'level':'DEBUG', }, } } this works fine in my localhostbut when i put it online when i'm trying to start the server i get : [Tue Nov 22 04:27:37.817043 2016] [wsgi:error] [pid 3619] [remote 111.113.21.35:0] ValueError: Unable to configure handler 'file': [Errno 13] Permission denied: '/log.txt' here is the error stack : (XID d4tgu5) Database Connect Error: Access denied for user 'leechprotect'@'localhost' (using password: YES) [Tue Nov 22 04:36:25.934018 2016] [wsgi:info] [pid 4882] mod_wsgi (pid=4882): Create interpreter 'myproject.com|'. [Tue Nov 22 04:36:25.960785 2016] [wsgi:info] [pid 4882] mod_wsgi (pid=4882): Adding '/home/xyz/public_html/myproject' to path. [Tue Nov 22 04:36:25.961397 2016] [wsgi:info] [pid 4882] mod_wsgi (pid=4882): Adding '/usr/local/lib/python3.4/site-packages/' to path. [Tue Nov 22 04:36:25.963133 2016] … -
Flask oauth_state error
First of all I am so sorry from all people which is reading my question (because it can be silly question ))))). I am new in Flask development. When I am running code I got an error of auth_state. Please help me to solve this problem. -
jqte automatically removes a line when save
I'm using jquery-te 1.4.0 I have it on my django template, initialised like so $('#mytextarea').jqte(); My content would be like (a) Apple (b) Banana (c) Carrot Then made (a) Apple to bold or all items Save the form and it'd come out as (b) Banana (c) Carrot And when you add (a) Apple again, it'd delete some other lines or it won't add at all. Anyone knows what is causing this issue? -
Django REST: Displaying a feed from a queryset and API JSON response
Currently I have a ListView which displays local posts class ListPosts(generic.ListView): queryset = Post.objects.filter(visibility='PUBLIC').order_by('-created_on') template_name = 'app/post_templates/list_posts.html' context_object_name = 'posts_list' paginate_by = 10 This works well, but I am not trying to incorporate responses from an API that gives the same info and more than is in our local Post objects, but of course needs some work to fit exactly. What is the easiest way to have both sources of information show up in the same stream (hopefully with pagination)? -
deploying to heroku from local machine
I have django project running on my machine in virtualenv. Is there a way I can deploy my project on Heroku directly? I followed steps mentioned in heroku documentation but i am kind of confused with req.txt since my project already have req.txt in virtualenv. I am new to django heroku techs. Any guidance is highly appreciated. -
Django adding custom decorator to admin urls
I have a custom decorator that I implemented to use Duo Push 2FA. Which looks something like this: views.py @duo_auth.duo_auth_required def get_stuff(request): page = request.GET.get('page', 1) If it does not meet the requirements it'll bounce you to a page that requires you to authenticate via DUO. And I've gone as far as to decorate all my views with it, but when it comes down to the admin page, I'm not entirely sure how to integrate it there. urlpatterns = [ url(r'^admin/', admin.site.urls), Is it possible to add the decorator on the urls pattern? -
How do I re-evaluate my urls.py file after every test within a Django tests.py file?
I have the following construction in my urls.py - it allows me to visually check the format of emails that I send in the browser when I'm developing: urlpatterns = [Various url pattenrns] if settings.DEBUG: urlpatterns += [URL Pattern for checking emails] My issue is that when I run my test suite the code only checks settings.DEBUG one time - not each time a test or even a TestCase runs. I'm trying to use the @override_settings decorator before my tests that apply to the DEBUG=True urlpattern with something like: # Most of my tests run fine with Debug=False @override_settings(DEBUG=True) # Tests that use the URL pattern for checking emails However, I can't seem to get this to properly toggle the Url pattern between tests...presumably because my urls.py file only loads once for the entire app's tests. Is there a way to use this type of construction in my urls.py and run my tests? Is there a reason I shouldn't be using this type of conditional in my urls.py? -
Where do I put my django Template Context Processor setting in Django 1.10
I'm trying to migrate an old project over from Django 1.6 to 1.10. I have read the documentation but I am still having trouble understand how to handle Templates in my settings.py In my old settings I had: TEMPLATE_CONTEXT_PROCESSORS = [ "django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.core.context_processors.tz", "django.core.context_processors.request", "django.contrib.messages.context_processors.messages", ] How do I migrate this over to 1.10? Can I add it to the following? TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(PACKAGE_ROOT, 'templates')], }] Currently when I run my Django project in 1.10, I get an error that says TEMPLATE_* settinsg were deprecated in Django 1.8 -
object does not support item assignment
Olá! I dont have any idea whats happen with my "/" where direct to my swagger. Was working normally, but appear this problem right now: Traceback: File "/home/guilherme/.virtualenvs/api/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/home/guilherme/.virtualenvs/api/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/guilherme/.virtualenvs/api/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/home/guilherme/.virtualenvs/api/local/lib/python2.7/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/guilherme/.virtualenvs/api/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 477. response = self.handle_exception(exc) File "/home/guilherme/.virtualenvs/api/local/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception 437. self.raise_uncaught_exception(exc) File "/home/guilherme/.virtualenvs/api/local/lib/python2.7/site-packages/rest_framework/views.py" in raise_uncaught_exception 448. raise exc Exception Type: TypeError at / Exception Value: 'Link' object does not support item assignment Request information: GET: No GET data Anyone have idea whats happen? Tks (sorry for my terrible english) -
Referring to related object instance
I have list of people on the group detail page. I'm trying to remove person from group and redirect page back to that group. from .models import Person, Group def person_remove(request, slug): instance = get_object_or_404(Person, slug=slug) instance.delete() the_group = ? group_slug = ? return redirect('group_detail', slug=group_slug) As you can see I'm passing 'slug' parameter from Person object, but I'm trying to redirect to that Group detail page which contains that person. -
Obtain extended User parameters into template
I extended admin's User model with my OperatorProfile class in order to add an avatar and some other fields. My model looks like this: def user_directory_path(instance, filename): ext = os.path.splitext(filename)[-1].lower() name = 'operators/avatar/user_{0}{1}'.format(instance.user.id, ext) if os.path.exists(os.path.join(settings.MEDIA_ROOT, name)): os.remove(os.path.join(settings.MEDIA_ROOT, name)) return name class OperatorProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.FileField(upload_to=user_directory_path, null=True, blank=True) And my question is: what is the proper way to retrieve OperatorProfile additional information in admin template? Do I have to declare a new context processor or is there a way to extend user and obtain something like this? {% firstof user.get_short_name user.get_username %} <img src="{% static user.get_avatar %}" /> -
What happens when a Django table hits max on an ID/PK column?
Lets imagine that you have an application where an specific table has A LOT new objects (in Django terms) created. Nevermind how many are deleted, but let's say it is sufficient to keep the table functional. After quite a while, how unlikely it may ever be, the table hits max on the ID/PK column. What happens next? How does Django handle that situation? -
Django stopped finding application static files
I have a Django 1.9.8 app that's working most of the times. For some reason, Django stopped service application static files, including those of the build-in admin application. Running collectstatic only looks for files in my STATICFILES_DIR, as does findstatic. I do have django.contrib.staticfiles in my INSTALLED_APPS, and yet - Django does not look for its apps' static files. I'm stumped and don't even know where to look next. -
Why am I getting an invalid syntax error on a line that doesn't exist?
I'm trying to chip away at upgrading an old Django project from 1.6 to 1.10 and I'm encountering a strange error. I'm getting a syntax error on line 25 of something that is only 10 lines long. When I run the Django project, I get: SyntaxError at / invalid syntax (accounts_extras.py, line 25) Request Method: GET Request URL: http://172.17.0.3:8000/ Django Version: 1.10.3 Exception Type: SyntaxError Exception Value: invalid syntax (accounts_extras.py, line 25) account_extras.py from django import template from django.template.defaultfilters import stringfilter register = template.Library() @register.filter @stringfilter def upto(value, delimiter=None): return value.split(delimiter)[0] upto.is_safe = True Part of my views.py def home(request): if request.user.is_authenticated(): return redirect('/storefront') else: return render(request, 'homepage.html') -
unixODBC Driver Manager Can't open lib
I'm trying to connect to SQL Server db using django 1.10 and pyodbc, Mas Os X 10.11.5 Firstly, when I'm typing python manage.py inspectdb the traceback is ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'FreeTDS' file not found (0) (SQLDriverConnect)") So I've installed brew install freetds so my /usr/local/lib/ contains libct.4.dylib libct.dylib libodbc.dylib libodbccr.dylib libodbcinst.dylib libsybdb.a libct.a libodbc.2.dylib libodbccr.2.dylib libodbcinst.2.dylib libsybdb.5.dylib libsybdb.dylib The question is what should I write in odbcinst.ini? Am I doing it the right way? -
Django Homepage 400 when debug=False
So my app works fine in the development server when Debug=True, however, when I switch it to False, my homepage is giving me back a 400 back. I have some endpoints return json and they work fine. I'm using Django 1.10.2 urls.py from django.conf.urls import url from django.contrib import admin from fim_table import views urlpatterns = [ url(r'^$', views.create_home), url(r'^data/', views.data), ... ] views.py from django.shortcuts import render from django.views.decorators.csrf import csrf_protect from lockdown.decorators import lockdown from .models import Fim, FimDeleted from django.http import HttpResponse from django.db.models.functions import Lower from django.template.context_processors import csrf import json @csrf_protect def create_home(request): return render(request, 'table.html', {'csrf': csrf}) # returns all of the data, unfiltered/response is json @csrf_protect def data(request): # show distinct names only fims = Fim.objects.annotate(name_lower=Lower('crib_name')).order_by('name_lower').distinct('name_lower') # fims need to be not a queryset but an array of dicts to be json dictionaries = [ idToString(name.as_dict()) for name in fims ] mydata = {"aaData": dictionaries} return HttpResponse(json.dumps(mydata), content_type='application/json') settings.py DEBUG = False ALLOWED_HOSTS = ["*"] -
Error while running django project
Hello I am doing a django (python) project while running the project I got this error. I dont know what is the error and how it can be solved. C:\Users\SujanRajs\Desktop\YAAS-master\YAAS-master\usatyal\YAAS>python manage.py runserver Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django-1.8.4- py2.7.egg\django\core\management\__init__.py", line 338, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django-1.8.4-py2.7.egg\django\core\management\__init__.py", line 303, in execute settings.INSTALLED_APPS File "C:\Python27\lib\site-packages\django-1.8.4-py2.7.egg\django\conf\__init__.py", line 48, in __getattr__ self._setup(name) File "C:\Python27\lib\site-packages\django-1.8.4-py2.7.egg\django\conf\__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "C:\Python27\lib\site-packages\django-1.8.4-py2.7.egg\django\conf\__init__.py", line 92, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) ImportError: No module named YAAS.settings -
SQL Where Clause and Django Timezone
I have noticed that when I return records from my SQL database using the following: the_records = records.objects.filter(datetime__contains="2015-01-15"), I get back the wrong records because the timezone is affecting the function call somehow - I know this because if I temporarily disable the timezone, the right records are returned. Can anyone offer assistance on what I should do to fix this problem (I still need to use the timezone). Regards, Mark -
How to stop Django from escaping the # symbol
I am trying to use SVG sprites for the icons in a site, like this: <svg aria-hidden="true" class="icon"> <use xlink:href="{% static 'images/site-icons.svg#icon-twitter' %}"></use> </svg> However this doesn't work because the # gets escaped by Django and so I end up with: <svg aria-hidden="true" class="icon"> <use xlink:href="{% static 'images/site-icons.svg%23icon-twitter' %}"></use> </svg> So no icons are rendered. I have isolated that the problem is the escaping, since it works if I paste the contents of site-icons.svg in the template, and do <svg aria-hidden="true" class="icon"> <use xlink:href="#icon-twitter"></use> </svg> so the problem is in the escaping. Does anybody know how to avoid this escaping from happening?