Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Correctly doing a POST request via AJAX to a Django view
I'm a JS newbie coming from a server-side dev background. Currently I'm learning to perform a POST request via AJAX to a Django (Python) view. I'm running into the error AttributeError: 'NoneType' object has no attribute 'has_header'. Full traceback: Internal Server Error: /pcp/ Traceback (most recent call last): File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/newrelic-2.56.0.42/newrelic/hooks/framework_django.py", line 499, in wrapper return wrapped(*args, **kwargs) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 25, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/views/decorators/cache.py", line 76, in _cache_controlled patch_cache_control(response, **kwargs) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/utils/cache.py", line 59, in patch_cache_control if response.has_header('Cache-Control'): AttributeError: 'NoneType' object has no attribute 'has_header' I need help solving this. The AJAX request includes an image object. Here's how I'm setting it up: function overwrite_default_submit(e) { e.preventDefault(); var form = new FormData(); form.append("image", to_send, img_name); var xhr = new XMLHttpRequest(); xhr.open('POST', e.target.action); xhr.setRequestHeader("X-CSRFToken", get_cookie('csrftoken')); xhr.send(form); } function get_cookie(name) { if (!name) { return null; } var value = "; " + document.cookie; var parts = value.split("; " + name + "="); if (parts.length >= 2) return parts.pop().split(";").shift(); } It seems the object being passed is empty. Which is strange because to_send has a value of Blob { size: 138223, type: "image/jpeg" } whereas img_name … -
Django nginx invalid HTTP_HOST header
I am getting emails every day from bots hitting my server with the wrong http_header. I followed the steps here: Django ERROR: Invalid HTTP_HOST header: u'/run/myprojectname/gunicorn.sock:' And I thought that would solve it. The problem is now that if you try to go to https://35...***/ I can still get it to trigger an Invalid HTTP_HOST email to myself. I tried solving this by adding listen 443 default_server;: server { listen 443 default_server; listen 80 default_server; return 444; } But now legit traffic to my site is also blocked. Here's my full config. Any help is much appreciated. server { # default server listen 80 default_server; return 444; } server { listen 80; server_name mysite.com www.mysite.com; root /home/ubuntu/web/troopers/; location /static/ { # if asset versioning is used if ($query_string) { expires max; } } access_log /home/ubuntu/web/logs/troopersAccess.log; error_log /home/ubuntu/web/logs/troopersError.log; location / { uwsgi_pass unix:///home/ubuntu/web/troopersuwsgi.sock; include uwsgi_params; } # what to serve if upstream is not available or crashes error_page 400 /400.html; error_page 403 /403.html; error_page 404 /404.html; error_page 500 502 503 504 /500.html; # Compression gzip on; gzip_http_version 1.0; gzip_comp_level 5; gzip_proxied any; gzip_min_length 1100; gzip_buffers 16 8k; gzip_types text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript; # Some version of IE … -
Python Django - render OrderedDict in view like json
I'm new in Django and Python. I'm in HTML printing data from python using {{ body.example }} Some data is render ok in plain text, but there one that is printing like this: [OrderedDict([(u'value', u'5650.00'), (u'operation_number', 130990), (u'comments', u'TESTE'), (u'date', OrderedDict([(u'start', 20160519), (u'end', 20160519)]))])] How can I render this type of data like json(becouse the result from api is json): { "value": "5650.00", "operation_number": "130990", "comments": "TESTE", "date": { "start": "20160519", "end": "20160519" } } -
'list' object has no attribute 'prefixed_order_by_field' Django-tables2
In order to show plural tables in a view using Django-tables2, I assigned plural tables to a table variable and use RequestConfig as follows, tables = [ScheduleTable(qs_t2),ScheduleTable(qs_t2125),ScheduleTable(qs_gst)] RequestConfig(request).configure(tables) export_format = request.GET.get('_export', None) "'list' object has no attribute 'prefixed_order_by_field" was the error message when I ran this program. Do you know why? -
clear limit on Django QuerySet
It's possible to limit the results on a QuerySet by doing something like this: qs = MyModel.objects.all()[:3] Since the QuerySet is usually evaluated lazily, is it possible to remove this limit from the qs before it's iterated over? I was hoping for something straight forward like qs = qs[:] or qs = qs[0:] but neither work. So far the only thing I can get to work is qs.query.clear_limits() but I'm not really sure if that's part of the public API (I had to wade through Django source code to find it). -
leaflet with django says openPopup is undefined
I am writing a simple map application and I want to open a popup when the mouse is released over a marker on my map. Here is my code (index.html): {% load leaflet_tags %} <html> <head> {% leaflet_js %} {% leaflet_css %} <style> .leaflet-container { height: 100%; } </style> <script type="text/javascript"> var popup = L.popup(); function onMouseUp(e){ popup .setLatLng(e.latlng) .setContent("HAHA") .openOn(yourmap); } function map_init_basic (map, options) { var marker = L.marker([59.3, 18]).addTo(map); marker.on('mouseup', onMouseUp); } </script> </head> <body> <h1>Stockholm Issues</h1> {% leaflet_map "yourmap" callback="window.map_init_basic" %} </body> </html> I get the error: openOn — leaflet.js:2446 TypeError: t.openPopup is not a function. (In 't.openPopup(this)', 't.openPopup' is undefined) If I just do a bindPopup it works fine. What am I missing? -
Call method on Django fields
class Colour(models): ... def colour_preview(self): return format_html(...) class ColourTheme(models): colour1 = models.ForeignKey(Colour) colour2 = models.ForeignKey(Colour) colour3 = models.ForeignKey(Colour) ... def preview(self): for field in self._meta.get_fields(include_parents=False): if (field.related_model == Colour): field.colour_preview() I have a ColourTheme model with multiple Colour foreign keys, and I want to call a function on each of the Colour objects referred to by those fields. The last line of code above fails. I would like to call colour_preview on all Colour fields without hardcoding them (self.colour1.colour_preview() works but not ideal). How might I achieve this? -
search api returns empty list using drf haystack for elastic search
I have following models, class ProductKeyword(models.Model): name = models.CharField(max_length=100) product = models.ManyToManyField(Product, related_name="products") date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.name) and search index, class ProductKeyWordIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr="name") product = indexes.CharField(model_attr="product") autocomplete = indexes.EdgeNgramField() @staticmethod def prepare_autocomplete(obj): return " ".join(( obj.name, obj.product )) def get_model(self): return ProductKeyword def index_queryset(self, using=None): return self.get_model().objects.filter( date_created__lte=timezone.now() ) and the viewset, class ProductKeywordSearchView(HaystackViewSet): index_models = [ProductKeyword] serializer_class = ProductKeywordSerializer and the url configuration, router = routers.DefaultRouter() router.register(r'prod_key', ProductKeywordSearchView, base_name="prod-key- search") # The API URLs are now determined automatically by the router. urlpatterns = [ url(r'^', include(router.urls)) ] and the settings.py (haystack configuration) HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://localhost:9200/', 'INDEX_NAME': 'bhkhata', 'INCLUDE_SPELLING': True, 'TIMEOUT': 300, }, } i saved data through django shell, and checked that the data are successfully saved in the ProductKeyword model. trying to get result using following search api, http://localhost:8090/api/hs/prod_key/?name=sayaabintel but its returning a empty list with 200 status. i am new in elastic search, so not sure what causing this above api to return a empty list, there could be one possibility that the object i am trying to search, not been indexed in elastic search, so i have … -
uWSGI sometimes stuck and send 502 error
Hello i am using no config file, just use systemd with next command to run uwsgi and very simple config --socket /var/uwgi/uwsgi.socket --module boost.wsgi_django --chmod-socket=666 -p 64 And sometimes i receive 502 like uwsgi is down but all is ok and no errors even log. It look like server is down for a half of a second and then all is ok again. -
FileField does not uploada anything django
please, drop me any advice. I will actually appreciate everything. Whenever I succesfully pass the entire flow uploading a field with the usage of django-based web application, nothing really happen. Proper records are being inserted into the database, but files by itselves are not copied to the server's filesystem. models.py from django.db import models from django.forms import ModelForm from .choices import * from .validators import validateExtensionOfTheFile from django.contrib.auth.models import User class MusicFile(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) image = models.FileField(upload_to="music_images/%Y/%m/%d", null=True, blank=True, validators=[validateExtensionOfTheFile]) forms.py from django import forms from .choices import * from .models import MusicFile class MusicFileForm(forms.ModelForm): class Meta: model = MusicFile fields = '__all__' exclude = ('owner') def __init__(self, *args, **kwargs): super(MusicFileForm, self).__init__(*args, **kwargs) self.fields['image'].required = False views.py @login_required def new_upload(request): if request.method == 'POST': form = MusicFileForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.owner = User.objects.get(username=request.user.username) post.save() return HttpResponseRedirect('/success/confirmed/') else: form = MusicFileForm() return render(request, 'new_upload.html', {'form': form}) new_upload.html {% extends 'base.html' %} {% block content %} <form enctype="multipart/form-data" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary btn-block">Log in</button> </form> {% endblock %} @EDIT setting.py: TEMPLATES = [ { ... ... ... 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, … -
Safe way to have globally accessible JWT token in Django
There's a lot out there on how to issue JWT tokens to clients from Django, but I'm looking for a way to store a JWT token that is issued to the Django app for authentication against an external API. The setup: Django requests and receives token from external API. It is good for 24 hours. Every time a client a makes a request, the app must make an authenticated call to the external API. Ideally, if 3 clients make 2 requests each, we should only need to request a single JWT. 24 hours later, a fourth client makes a request. Django sees that the token is invalid and requests a new one. The problems here: Requests from multiple clients should not each require their own token. The token must be able to be changed (this rules out sticking it in the settings) The token must be stored securely. Ideas so far: Stick in the database with a field listing the expiry time. This seems questionable from a security standpoint. Implement some kind of in memory storage like this https://github.com/waveaccounting/dj-inmemorystorage . This seems like overkill. Any suggestions as to a better way to do this? -
App Engine Flexible: Timed out waiting for the app infrastructure to become healthy
I'm trying several times to deploy a new version of a service on my app engine flexible instance using the sdk and the command "gcloud app deploy", but all i get is this error "ERROR: (gcloud.app.deploy) Error Response: [4] Timed out waiting for the app infrastructure to become healthy.". I Couldn't found any answer about it on the issue tracker of gcp. On this question, he got the same problem, but no one could answered it. Any guidance will be very helpfull. -
how to get value of a model instance at specified time in Django?
I have a point awarding method in my website and I want to create a "top users in last 10 days" list. right now I store and update user scores in Profile model which is: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) points = models.IntegerField(default=0) but I want to get the value of this "point" instance at for example 10 days ago for comparing it to latest value. how can I achieve this? -
Ordering Filter using 2 ordering values(django_filters)
Hello every one is there a way to use OrderingFilter like in django order_by with 2 ordering values queryset.ordery_by('value1', value_2') I have tried order_by = django_filters.OrderingFilter( fields=( ('item_name', 'Items), ('time_from', 'Time'), (('value1', 'value2'), 'Value'), ) ) But received expected string or bytes-like object -
Django permissions analysis
Is anyone aware of a programmatic way of analysing a codebase to see which permissions each view is protected by? I'd like to be able to run a regular report on a site to inform us which views are available and who can see them etc. rather than having to maintain a list by hand. I'm aware of the show_urls command from django-extensions but that doesn't help with the permissions side of things. -
django date filter doesn't update
I made a listview in a django project. But when day go away, filter stay on starting data (start or refresh of web-server). Why it doesn't update every day? this is my code: (table booking for restaurant) models.py: class Table_book(models.Model): name = models.CharField(max_length=50) date = models.DateField() time = models.CharField(max_length=50, choices=TIMES) people = models.PositiveIntegerField(choices=TABLES) telephone = models.CharField(max_length=50) views.py class List_book(ListView): model = Table_book template_name = 'list_today.html' queryset = Table_book.objects.all().filter(date=timezone.now()).order_by('date', 'time') urls.py url(r'^$', login_required(List_book.as_view(), login_url='/login/'), name='home'), in template.html the list objects populate a table. -
django - How to make a custom is_authenticated to verify if a user is connected?
I have a custom user model using AbstractBaseUser, called Users, so I also have a custom authentication backend: https://pastebin.com/waky5AW3 My issue is that I don't know how to check if a user is connected while using this custom user model, because users.is_authenticated will always return true as logged in and user.is_authenticated will always return false and I mean not logged in, ONLY if the user is logging into the CONTROL PANEL, THEN, user.is_authenticated will return TRUE and which means that the user is LOGGED in. This is how I log in the user once form is submitted: email = form.cleaned_data['email_field'] password = form.cleaned_data['password'] temp = OwnAuthBackend() user = temp.authenticate(email=email, password=password) if user is not None: messages.success(request, 'You logged in successfully!') return redirect('index', users = user) The if is not None returns true and the user is redirected to the index with variable users = user and with that success message, and I know it is not a good way because if user comes from another redirect, still logged in but without the variable 'users', it should give him an error. The thing is, How to check if user is authenticated using a custom user model... -
serving media files with dj-static in heroku
I'm trying to serve media files that are registered in django-admin. When accessing an image by api error 404 Not found. I made a configuration as the recommended documentation, but in heroku does not work. settings.py import os from decouple import config, Csv from dj_database_url import parse as dburl BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', default=False, cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS', default=[], cast=Csv()) default_dburl = 'sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3') DATABASES = { 'default': config('DATABASE_URL', default=default_dburl, cast=dburl), } (...) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') wsgi.py import os from dj_static import Cling, MediaCling from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "integrafundaj.settings") application = Cling(MediaCling(get_wsgi_application())) requirements.txt dj-database-url==0.4.2 dj-static==0.0.6 Django==1.11.3 djangorestframework==3.7.7 easy-thumbnails==2.4.2 olefile==0.44 Pillow==4.3.0 python-decouple==3.1 pytz==2017.3 static3==0.7.0 Unidecode==0.4.21 gunicorn==19.4.1 psycopg2==2.7.1 -
is that important to clean data when use self.kwargs.get()?
is that important to clean data when use self.kwargs.get()? for example when we get pk from url in view classes by self.kwargs.get(pk). if answer is yes, how can I clean data? -
Django rest password throws 500 error
I have implemented the Reset password by using django ResetPassword. But It throws the 500 error. I don't know how to find the flow & fix it. 1.I have created the urls.py from __future__ import unicode_literals from django.conf.urls.static import static from django.conf import settings from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import include, path from . import views app_patterns = [ path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('signup/', views.Signup.as_view(), name='signup'), path( 'password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset' ),][enter image description here][1] Also I have created the HTML files (Refer Screenshot) password_reset_form password_reset_done password_reset_confirm password_reset_complete I don't know what I'm missing here. Can anybody help me out? Thanks in advance. -
does not appear to have any patterns in it error
I got an error, Traceback (most recent call last): File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/checks/urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/checks/urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/urls/resolvers.py", line 545, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'django.urls' from '/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/urls/__init__.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. I recently updated Django 1.8 into 2.0,so I think the error happens.I think the way of urls.py causes this error, so I rewrote like from django.urls import include, path app_name = 'App' urlpatterns = [ path('admin/', admin.site.urls), path('app/', include('app.urls')), ] +static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) but same error happens.I really cannot understand why this error happens.How should I fix this?What is wrong in my code? -
I think I'm installing Django, but it doesn't seem to be there
Mysterious. I may not understand virtualenv sufficiently to use it. I created what I thought was a virtual environment: pip3 -m venv myenv pip3 install --ignore-installed django~=2.0.0 Collecting django~=2.0.0 Using cached Django-2.0.1-py3-none-any.whl Collecting pytz (from django~=2.0.0) Using cached pytz-2017.3-py2.py3-none-any.whl Installing collected packages: pytz, django Successfully installed django-2.0.1 pytz-2017.3 001b639f6f87:myenv admin$ ls bin include lib pyvenv.cfg So, where is Django? Actually, this may not be a virtualenv question. Run the same command in a non-venv directory with the same result: no Django. So, I think, maybe there is an issue with Django 2.0 of which I am unaware. Let's try 1.11: 001b639f6f87:django-test admin$ pip3 install --ignore-installed django~=1.11.0 Collecting django~=1.11.0 Downloading Django-1.11.9-py2.py3-none-any.whl (6.9MB) 100% |&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;& #9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&# 9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;| 7.0MB 108kB/s Collecting pytz (from django~=1.11.0) Using cached pytz-2017.3-py2.py3-none-any.whl Installing collected packages: pytz, django Successfully installed django-2.0.1 pytz-2017.3 001b639f6f87:django-test admin$ ls 001b639f6f87:django-test admin$ ls -l 001b639f6f87:django-test admin$ Obviously, unclear on something, but not sure where the problem lies. -
djangocms integration filer_image with apphook objects
I want to add filer_image field to my Gift class instance object. It works as apphook in django-cms. The main problem is that after making migrations and open the view where the form is i don't have loaded js. I already added all tags: {% load staticfiles i18n cms_tags sekizai_tags menu_tags thumbnail filer_tags filer_image_tags %} The model is: class Gift(models.Model): filer_image = FilerImageField(related_name="book_covers") The form: class GiftForm(ModelForm): class Meta: model = Gift fields = '__all__' widgets = { 'name': forms.TextInput(attrs={'class': 'basic-input full-width'}), } The rendered output: Please tell me what am I doing wrong with these. It seems to me like some js files are not loaded. After click it opens FileImageFiler gallery, but I also cannot select any image. -
Restructuring json response from Django REST Framework
My current response which lists all fields in my serialiser is as follows: GET /conversations/<id>/messages returns: { "count": 2, "next": null, "previous": null, "results": [ { "task_id": 21, "conversation_id": 1, "sender": 2, "body": "Hello There" }, { "task_id": 21, "conversation_id": 1, "sender": 2, "body": "Can you do the task" } ] } Instead, since conversation_id , task_id and user_id are repeated, I would like to take them outside the main response. I want to return: { "count": 2, "next": null, "previous": null, "task_id": 21, "conversation_id": 1, "user_id": 1, "results": [ { "sender": 2, "body": "Hello There" }, { "sender": 2, "body": "Second Message" }, ] } serializers.py class MessageSerializer(serializers.ModelSerializer): sender = serializers.ReadOnlyField(source='sender.id') task_id = serializers.SerializerMethodField() conversation_id = serializers.SerializerMethodField() def get_task_id(self, obj): task = Task.objects.filter(task_worker__conversation__message=obj)[0] return task.id def get_conversation_id(self, obj): conversation = Conversation.objects.filter(message=obj)[0] return conversation.id class Meta: model = Message fields = ['task_id','conversation_id','sender','body'] -
How to set interrelated Django model Fields
I have the following simplified problem. Say that I have two Django models, namely a (P)roject and (H)ourly which stores hourly values for the project. Now lets assume that there is a simple relation between these entities, e.g.: H.y = 2*H.x + P.par. Is there an elegant way to implement this? Where to put the help function: def calc_y(x, par): return 2*x+par class P(models.Model): par = FloatField() class H(models.Model): p = models.ForeignKey(P, on_delete.CASCADE) x = FloatField() y = FloatField()