Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to know the the name of the URL that is attending a certain request
I am working with Django 1.8. I have fairly large and complex list of urls defined in several apps. One of the requests I'm launching is not being dispatched by the URL that I want. Also, I don't even know which url is atending such a request. So my question is: is there any way of knowing the name of the url that would attend a certain request? -
AttributeError: 'dict' object has no attribute '_meta'
Got code shops = Shop.objects.filter(id__in=list(set(shop_ids))).all() shop_list = [] for s in shops.only(): shop_list.append({ 'id': s.id, 'name': s.name, 'preview': s.preview, }) response_data['shop'] = serializers.serialize('json', shop_list) return response_data ..... AttributeError: 'dict' object has no attribute '_meta' how i can fix it? -
HTML 5 DatePicker events not firing on iOS safari
Im trying to implement a date picker to update a graph with some information from a certain point in time. Using jquery ive tried onblur onchange and onkeyup but none of those events seem to be firing on either chrome or iOS. I then tried onblur= with no success either. Can anyone see what im doing wrong here? <div class="col-50 graph-date-select-container"> <input id="graph-date-input" type="date" class="graph-date-select" style="-webkit-appearance: textfield; -moz-appearance: textfield; height: 20px; margin-top: -15px;" onblur="graphUpdate()"/> </div> function graphUpdate() { alert("graphUpdate called.") var date = new Date($(this).val()); var dateString = "" + date.getDay() + "/" + date.getMonth() + "/" + date.getFullYear(); var url = "{% add_params request.get_full_path period='daily'%}" + "query_param=" + dateString window.location.href = url }; Essentially all that needs to happen is that when the value in the input is changed (the user hides the date input pop up) the dat is passed as a param to the django template and the page reloads with the new information. -
Token based Authentication using django + mongoengine
I'm using mongoengine + django. I need to use Token-based Authentication. I googled a lot but found with django.contrib.auth. Somewhere I found mongoengine.django.auth but it doesn't work for me. Here is the link where I found. May be, I get downvote for this question but my question is simple. Token-based Authentication using django+mongoengine. Most of them are using mysql but I have mongoengine. If it is not possible to implement this scenario. Please suggest me something else where I can achieve my goal. -
Django model with multiple choices
I need to define that model 'Serie' has multiple category (action, adventure, ...). I saw that there's a field called Field.choices, but then the Serie would just have 1 category. Should I define another model named 'Category' with the multiple categories and then set a Foreign Key on the Serie side to Category? There is any other way doing that easier? Thanks. class Serie (models.Model): serie_cover = models.ImageField(upload_to="covers") serie_name = models.CharField(max_length=100) #Category needed def __str__(self): return (self.serie_name) -
Django tables 2 exclude doesn't work
I'm using Django 1.8.7 with djangotables2 1.3.0. I'm trying to build a table using ModelForm (example below). When I try to hide a column using exclude, it still shows all columns. Exclude doesn't seem to have any effect here. A part of my models.py: class Event(models.Model): Name = models.CharField (max_length = 45, blank = False, null = False) Date = models.DateTimeField (auto_now_add=True) Text = models.CharField (max_length = 64, blank = False, null = False) class Meta: ordering = ["-Date", "Name"] verbose_name = "Event" verbose_name_plural = "Events" def __str__(self): return self.Name class Event_Form(ModelForm): class Meta: model=Event exclude = ('Date',) Thanks in advance for any help or ideas! -
Backend not found : social-auth-app-django, for Facebook login
I have been using social-auth-app-django to login through Google and it works fine. I tried the same with Facebook. I used social_core.backends.facebook.FacebookOAuth2under AUTHENTICATION_BACKENDS, and it doesn't work. I get an error message saying "Backend not found". I read the documents and it has nothing to say regarding Facebook backends while all other social backends seems to have the authentication backend support. Any suggestion? In settings.py, SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'accounts.views.save_profile', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.google.GoogleOAuth2', ) # GOOGLE CREDENTIALS SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = "****" SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "****" # FACEBOOK CREDENTIALS SOCIAL_AUTH_FACEBOOK_KEY = '****' SOCIAL_AUTH_FACEBOOK_SECRET = '****' Also, what should be my target url upon click, in templates ? -
Django 1.10: CSRF Token issue in Ajax
I am creating my AJAX request like this: data.push({'csrfmiddlewaretoken': csrf, 'answers': answers}) $.ajax( { type: "POST", url: "http://127.0.0.1:8000/en/list/add/", data: JSON.stringify(data), dataType: 'json' }).done(function (data) { console.log(data) }); But I am still getting error CSRF token missing or incorrect. -
Don't pick up Django form value to javascript function
I'm trying to pick up RadioSelectBox value from my Django form to my template with a javascript part. But I don't overcome to get this variable and put it in my template. I've a very simple form : def ChoiceTheme(request) : if request.method == 'POST': form = ThemeForm(request.POST or None) if form.is_valid(): theme = form.instance.favorite_theme print theme post = form.save() return HttpResponseRedirect(reverse('accueil'), {"theme":theme}) else: form = ThemeForm() context = { "form":form, } return render(request, 'Theme.html', context) I get exactly the good field value with print theme. But I want to place this variable in my html template : {% block content %} <style> ul li { list-style: none; } </style> <div class = "col-sm-8"> <form class = "form" method='POST' action=''> {% csrf_token %} <h3> <span class="glyphicon glyphicon-file"></span> Choix du thème DatasystemsEC </h3> <br></br> {{ form }} <br></br> <button> Valider le thème </button> <script> theme = "{{ }}" $(function() { $('button').click(function() { alert("Vous avez choisi le thème : " + theme); }); })(jQuery); </script> </form> </div> {% endblock content %} I have theme = {{ theme }} but my alert window just display : Vous avez choisi le thème : Do you have any idea ? I'm very sily on this … -
load static files in javascript
i am trying to display an default image if the image from the server is not available. the business.profilePic is dynamically loaded from the server onerror i want to display image from static folder cell1.innerHTML = '{% load static %}<img class="img-responsive" src=' + business.profilePic + 'width="60" onerror="this.onerror = null; this.src={% static search/GoCheck_Logo.png %}" height="80" alt="Logo">'; in html body the {% load static %} is working fine but in javascript i don't have any idea how to do this -
Complicated queryset in django 1.6
I'm working on django 1.6 and I want to filter all Activities when Season's inactive is True. This is possible with models below? class Production hasn't ForeignKey to SeasonProduction and Season. class Activity(models.Model): production = models.ForeignKey(Production, null=True, verbose_name='ProductionId') class SeasonProduction(models.Model): season = models.ForeignKey(Season, verbose_name='SeasonId') production = models.ForeignKey(Production, verbose_name='ProductionId') class Season(models.Model): name = models.CharField('Name', max_length=255) inactive = models.BooleanField(default=True) -
Django Streaming CSV Download with Nginx/uWSGI
I am trying to implement CSV Streaming Download from Django Admin. The requirement is to export the listing queryset (about 5L records) and to prevent timeout, I am trying to implement download using HttpStreamingResponse like mentioned in the below link. https://docs.djangoproject.com/en/1.10/howto/outputting-csv/#streaming-large-csv-files Instead of fixed rows, I have a queryset with iterator(). All works fine with runserver and as soon as I click the export button the file starts downloading with unknown size and all records are exported. But on production with uWSGI and Nginx, the file does not start downloading immediately and records exported in CSV are not complete. Infact the download starts after time = harakiri value (60s) as set in uwsgi config. What am I missing here, can't really find anything specific to implement this with uWSGI and Nginx. My Django version is 1.8, uWSGI version is 2.0.12 and Nginx version is 1.4.6 My uWSGI config (uwsgi.ini) is as under: [uwsgi] uid=someuser gid=someuser chdir=/home/gor/somedir home=/home/gor/virtualenvs/somevirtualenv wsgi-file=%(chdir)/wsgi.py module=wsgi:application socket=/tmp/somesock.sock pidfile=/tmp/someproject.pid logto=/var/log/uwsgi/someproject.log vacuum=True master=True max-requests=5000 workers=1 chmod-socket=666 harakiri=60 My Nginx config is as under upstream django { server unix:///tmp/someproject.sock; # for a file socket } # configuration of the server server { # the port your site will be served … -
InconsistentMigrationHistory error with custom django user model
I am creating a custom user model. I ran the command python manage.py makemigrations accounts and then ran python manage.py migrate accounts which outputs the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 86, in handle executor.loader.check_consistent_history(connection) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/migrations/loader.py", line 292, in check_consistent_history connection.alias, django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default'. Here is my user model: from __future__ import unicode_literals from django.db import models from django.utils import timezone from PIL import Image from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin ) class UserManager(BaseUserManager): def create_user(self, email, username, password): if not email: raise ValueError("Users must have an email.") user = self.model( email=self.normalize_email(email), username=username ) user.set_password(password) user.save() return user def create_superuser(self, email, username, password): user = self.create_user( email, username, password ) user.is_staff = True user.is_superuser = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=40, unique=True) avatar = models.ImageField(blank=True, null=True) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD … -
Why does my Django form show choice not available error?
I am trying to build a dynamic form in Django template. I have two dropdown selections. When the user selects an option in the first one, the available choices in the second dropdown changes dynamically. Here is the jQuery code I use to change the choices in the second dropdown element. $(document).on("change", "[id^=id_form][id$=brand]", function() { var $value = $(this).val(); var $id_prefix = $(this).attr('id').slice(0, -5); $auto_type = $("#" + $id_prefix + "auto_type"); $.ajax({ type: 'GET', url: '/europarts/filter/auto/type/with/brand/' + String($value), success: function(data) { $auto_type.html(data); } }); }); You can see that it fetches some HTML from a link which is basically a bunch of options which will replace the current ones. Here is the code: {% for auto_type in auto_types %} <option value="{{ auto_type.id }}">{{ auto_type.name }}</option> {% endfor %} This works fine! However after I change the options like this and try to submit the form, the form page gets loaded again with the default options in the second dropdown and not the changed ones along with an error that says: Select a valid choice. That choice is not one of the available choices. This error is shown for the second dropdown. How can I fix this? -
Server error when trying to run django project on apache(xampp) - windows
i followed this link (https://www.youtube.com/watch?v=VOkXG0jL_8U&feature=youtu.be) to run my django project on apache server under windows. so i followed step by step of this video but in the last part when i trying to run myproject on apache server i got an error. the error said : Server error! The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script. If you think this is a server error, please contact the webmaster. Error 500 localhost 02/23/17 12:18:17 Apache/2.2.9 (Win32) DAV/2 mod_ssl/2.2.9 OpenSSL/0.9.8i mod_autoindex_color mod_wsgi/3.3 Python/2.7.12 PHP/5.2.6 i add every thing that was needed according to video. my apache httpd.cong file for wsgi configuration is: Alias /media/ "c:/xampp/htdocs/mysite/" <Directory c:/xampp/htdocs/mysite> Order deny,allow Allow from all Require all granted </Directory> <IfModule wsgi_module> WSGIScriptAlias / "c:/xampp/htdocs/mysite/mod.wsgi" </IfModule> and the mod.wsgi file is set to: import os , sys sys.path.append('c:\\xampp\\htdocs\\mysite') os.environ['DJANGO_SETTING_MODULE'] = 'mysite.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() i think the problem is in this line (WSGIScriptAlias / "c:/xampp/htdocs/mysite/mod.wsgi") because when comment it the localhost worked but i dont know how to fix it. i worked on more than 3 days and realy need to solve it but i … -
Getting how the view was called with HttpRedirect in the next view
I have two views in django: one which loads the page, and one which saves a form. I've separated the two so I can stay on the same page without a page refresh causing a resubmit. The create view which saves the form redirects back to the view that loads the page with HttpResponseRedirect. Is it possible, in the load page view, to get if the view was called by the create view with the redirect? So: def holiday(request, value=None, year=None, month=None): if request.method == "GET": # set some variables for the view year = something month = something_else else: # get if the view was executed from a redirect # set year and month to be something2 and something_else2 # calendar holidayform = HolidayForm(request.POST or None, request.FILES or None) context = { "holidayform": holidayform, "calendar": mark_safe(cal), "year": year, "month": month, } return render(request, "tande/calendar.html", context) Then the view that saves the form: def create_holiday(request): overlapping_dates = False if request.method == "POST": #save the form... or don't return HttpResponseRedirect(reverse("tande:holiday")) -
Error 26 frmo memcached_get : Operation now in progress
I'm installing [this platform] on Ubuntu 12.04. It installs and sets up a server, which in my case is on localhost. After a bumpy installation, I managed to get the site online. After a few minutes however, it returned the following error: MemcachedError at / error 26 from memcached_get(:1:views.decorators.cache.cache_): Operation now in progress Request Method: GET Request URL: http://localhost/ Django Version: 1.7.11 Exception Type: MemcachedError Exception Value: error 26 from memcached_get(:1:views.decorators.cache.cache_): Operation now in progress Exception Location: /home/mitchell/opensurf/opensurfaces-master/venv/local/lib/python2.7/site-packages/django/core/cache/backends/memcached.py in get, line 82 Python Executable: /home/mitchell/opensurf/opensurfaces-master/venv/bin/python2.7 Python Version: 2.7.3 Python Path: ['/home/mitchell/opensurf/opensurfaces-master/server', '/home/mitchell/opensurf/opensurfaces-master/venv/bin', '/home/mitchell/opensurf/opensurfaces-master/server', '/home/mitchell/opensurf/opensurfaces-master/venv/lib/python2.7', '/home/mitchell/opensurf/opensurfaces-master/venv/lib/python2.7/plat-linux2', '/home/mitchell/opensurf/opensurfaces-master/venv/lib/python2.7/lib-tk', '/home/mitchell/opensurf/opensurfaces-master/venv/lib/python2.7/lib-old', '/home/mitchell/opensurf/opensurfaces-master/venv/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/home/mitchell/opensurf/opensurfaces-master/venv/local/lib/python2.7/site-packages', '/home/mitchell/opensurf/opensurfaces-master/venv/local/lib/python2.7/site-packages/boto-2.6.0.dev0-py2.7.egg', '/home/mitchell/opensurf/opensurfaces-master/opt/django-queued-storage', '/home/mitchell/opensurf/opensurfaces-master/opt/clint', '/home/mitchell/opensurf/opensurfaces-master/opt/django-imagekit', '/home/mitchell/opensurf/opensurfaces-master/venv/lib/python2.7/site-packages', '/home/mitchell/opensurf/opensurfaces-master/venv/lib/python2.7/site-packages/boto-2.6.0.dev0-py2.7.egg', '/home/mitchell/opensurf/opensurfaces-master/server'] Server time: Thu, 23 Feb 2017 18:46:49 +0100 The page also shows the following traceback. Environment: Request Method: GET Request URL: http://localhost/ Django Version: 1.7.11 Python Version: 2.7.3 Installed Applications: ('admin_tools', 'admin_tools.theming', 'admin_tools.menu', 'admin_tools.dashboard', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'django.contrib.humanize', 'gunicorn', 'storages', 'queued_storage', 'django_extensions', 'account', 'django_forms_bootstrap', 'imagekit', 'compressor', 'endless_pagination', 'cacheback', 'captcha', 'memcache_status', 'common', 'home', 'accounts', 'analytics', 'licenses', 'poly', 'mturk', 'photos', 'shapes', 'bsdfs', 'normals', 'intrinsic') Installed Middleware: ('django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.gzip.GZipMiddleware', 'common.middleware.HotshotProfileMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.doc.XViewMiddleware', 'account.middleware.TimezoneMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware') Traceback: File "/home/mitchell/opensurf/opensurfaces-master/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 87. response = middleware_method(request) File "/home/mitchell/opensurf/opensurfaces-master/venv/local/lib/python2.7/site-packages/django/middleware/cache.py" … -
Adding background image css during production
I'm making a website using Django and Elastic Beanstalk I know you can add a background image in css/html using <div style="background: url({% static 'app/images/image.png' %})"> </div> and this works fine when using the Django development server. However when I deploy this to Elastic Beanstalk my background image doesn't show up because it looks for the image at "http://hostname/static/app/images/image.png". What url should I enter to get this to work on aws. Note that I can get images to show up fine using: <img src="{% static 'app/images/image.png' %> Thanks in advance for your help, I'm sure there is a simple solution to this! -
Using python-magic for file identification, and getting an 'invalid file' error
I was told python-magic is the best way to identify a file type. So I installed it as i'm trying to determine whether a FileField is an image or video, when a user makes a Post. Here's my model: class Post(models.Model): ... image = models.FileField(null=True, blank=True) video = models.BooleanField(default=False) And my view: import magic def post(request): if request.user.is_authenticated(): form_post = PostForm(request.POST or None, request.FILES or None) if form_post.is_valid(): instance = form_post.save(commit=False) instance.user = request.user mime = magic.Magic(mime=True) f = mime.from_file(instance.image) print(f) instance.save() I copied the magic code from the top answer of this question: How to find the mime type of a file in python? However when I submit a Post, I get an error saying: invalid file: <FieldFile: uploadedImage.png> Any idea why it doesn't work? In the view I was going to do something like: if f = 'video': instance.video = True -
Django Rest Framework: Order by user dependent field
I have some products, of which a user can mark some as his favorite products. The favorites are modeled as a many to many relationship between a user profile and a product. I would now like to get the products via API call, but ordered by favorites first, everything else second. Now as this depends on the current request, i cannot do this via Product.objects.all().order_by(...), as the model does not know the current user, and I know of now way to tell the query through the serializer or ModelViewSet. I tried getting two querysets, one with all products, one with all favorites from the user profile in the ModelViewSet, like this: class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductCreateSerializer # ... def get_queryset(self): favorited_products = self.request.user.profile.favorites.all() products = Product.objects.all() queryset = favorited_products | products return queryset This does work, as the entities stay in this order. But this view returns a couple of hundred entities, so when I try to limit the queryset with return queryset[:30], the default ordering seems to take over. Is what I'm trying to do even easily achievable? Did anybody solve a similar problem already? Here are my models: class Product(models.Model): product_name = models.CharField(max_length=200) # ... def __unicode__(self): return … -
Django queryset foreign key conversion
I have 3 models: class User: ... Class Item: ... Class Storage: user = foreignkey(user) item = foreignkey(item) Now I have user_id, I want to use the user_id to see all the item this user have: storage_list = Storage.objects.filter(user__id = user_id) After that I get confused. I tried the following, none of them work. storage_list.item.all() storage_list.item_set.all() -
Complexities of Translating a Medium-size Flask app to Django
We have grown a medium-sized application on Flask, but we are missing the benefits of a framework that comes with more decisions made for us and a solid database migration story. What are the complexities and costs of translating a Flask app to Django? -
Explaination about migrate command in django
Can anyone explain me, how migration will happened in django? Actually I want full backend procedure of "./manage.py migrate" command -
Django : Get date wise count in Datetimefield
I have a class which has datetimefield class Foo(models.Model): id = models.AutoField(primary_key=True, db_column='status_id') date_field = models.DateTimeField(default=django.utils.timezone.now) f1 = models.TextField(blank=True, null=True) f2 = models.SmallIntegerField() I want to apply filter on date in DateTimeField and get the output in following format after doing some query: f2 date_field f1 54 2017-02-01 4 53 2017-02-01 6 52 2017-02-01 2 51 2017-02-01 1 48 2017-02-01 5 47 2017-02-01 2 46 2017-02-01 3 45 2017-02-01 2 41 2017-02-01 1 38 2017-02-01 3 32 2017-02-01 17 30 2017-02-01 3 29 2017-02-01 4 18 2017-02-01 4 14 2017-02-01 5 13 2017-02-01 2 -
django mysql db connection protocol
How can I specify connection protocol in db OPTIONS? If I use: 'ENGINE': 'django.db.backends.mysql', ... 'OPTIONS': { 'protocol': 'TPC', }, error is 'protocol' is an invalid keyword argument for this function I'm trying to set OPTIONS as on Django docs