Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django website not returning any data when using DNS
I have a simple Django website running on a Digital Ocean instance. I configured my DNS provider to point my URL to the Digital Ocean instance's IP address. When I enter that IP address in a browser everything works as expected but when I use the URL I get the correct site but no data is presented. The site was created using Mezzanine and using postgres as a database. What could be wrong? I'm not sure where/how to troubleshoot this error. -
Make Django pass int value request param as int rather than unicode
I remember coming across such a question some time ago, but couldn't find a link n the internet, so asking this question possibly for the second time. It is very iriitating that Django transforms int value into unicode having to transform the value to integer on every occasion. Is there any native syntax to stop Django doing this ? url(r'some_url/(?P<some_param>\d+)/$', some_view, name = 'some_url') def some_view(request, some_param): a = int(some_param) # Having to write this surplus int is very very irritating JS $.get('/some_url/6545/', function(response){... -
Django transferring data over internet very slowly
I have m4.large EC2 instance setup with apache and django. Website's static files are downloaded normally (apache handles /static folder), but dynamic data generated by django is transferred extremely slowly. It can take up to 8 seconds to fetch 500kB JSON encoded string (cache hit, 2ms to generate return value on the server itself). I created a test view and it displayed the same behaviour. def transfer_test(request): return HttpResponse("."*1000000) # Takes 12-15 seconds to download # Static file with the same contents downloads in less than a second What could be causing this slowdown? I have no middleware set up (other than default ones). Behaviour is consistent across networks and browsers, I am the only one sending requests to the server. When running django server on local machine this does not happen. -
Django export-import/tablib error
I try to import .xls file with code: ... dataset = tablib.Dataset() test_resource = resources.modelresource_factory(model=Product)() file = 'd:\\test.xls' dataset.xls = open(file).read() and it's throw an error: Traceback (most recent call last): File "<console>", line 1, in <module> File "D:\000_open_server\OpenServer\domains\Python\shopenv\lib\site-packages\tablib\formats\_xls.py", line 72, in import_set xls_book = xlrd.open_workbook(file_contents=in_stream) File "D:\000_open_server\OpenServer\domains\Python\shopenv\lib\site-packages\tablib\packages\xlrd3\__init__.py", line 395, in open_workbook biff_version = workbook.getbof(XL_WORKBOOK_GLOBALS) File "D:\000_open_server\OpenServer\domains\Python\shopenv\lib\site-packages\tablib\packages\xlrd3\__init__.py", line 1460, in getbof opcode = self.get2bytes() File "D:\000_open_server\OpenServer\domains\Python\shopenv\lib\site-packages\tablib\packages\xlrd3\__init__.py", line 881, in get2bytes return (hi << 8) | lo #(to_py3): TypeError: unsupported operand type(s) for <<: 'str' and 'int' I have tried to upgrade tablib and django-export-import but this has no effect. I think that this compatibility problem, but export-import and tablib docs say's "python 3+". What else can i try? -
deploying django application without source code
I am working on a django project. I am looking for a method for deploying my application and its update to production server. I think the best way is to run a command which will push only pyc files, configurations files, templates and stuff on my server. What is the best way to do this ? I do not want to deploy source py files. So i won't work with git or svn. Thanks -
Django Models and Django Admin
I have a model called Circuit, in there I have a field name. And then I have another model called CircuitHistoric with a foreign key pointing to Circuit, and two dates. Then in the admin.py I have a CircuitAdmin and I want to display the dates from CircuitHistoric with the property list_display. I know that I need an inner join in SQL but there's a way to do it with Django? -
Django, viewing models from different app
I am super new to python programming and django and i got the basics out of the way. I created a project with two apps, home and video. In my video models.py i have the following data: class Video(models.Model): name = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) I want to do something with this in my home app in the views.py, such as display the data in an html page and currently it is set up as followed: from video.models import Video def display_video(request): video_list = Video.objects.all() context = {'video_list': video-list} return render(request, 'home/home.html', context) in my home.html {% if video %} {% for video in video_list %} <p>{{ video.name }}</p> <p>{{ video.description }}</p> {% endfor %} {% else %} <p>no videos to display</p> {% endif %} my home.html always returns "no videos to display" But when i query Video.objects.all() in my video app it finds 2 objects. any help is appreciated. -
Django get form not ordered list
i changed my admin form when creating new objects to hide some fields, but it orders fields alphabetically, i want to order them as they are in my model.any suggestions? _add_fields = ('name', 'size', 'slug', 'img', 'description', 'quantity') def get_form(self, request, obj=None, **kwargs): model_form = super(ItemAdmin, self).get_form( request, obj, **kwargs ) if obj is None: model_form._meta.fields = self._add_fields model_form.base_fields = { field: model_form.base_fields[field] for field in self._add_fields } return model_form -
Create AbstractBaseUser
Try to create AbstractBaseUser and custom auth. models.py class Account(AbstractBaseUser): account_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) birthday_date = models.DateField(blank=True, null=True) sex = models.TextField(blank=True, null=True) # This field type is a guess. country = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(unique=True, max_length=320) mobile_number = models.CharField(unique=True, max_length=45, blank=True, null=True) registration_date = models.DateTimeField() expired_date = models.DateField(blank=True, null=False) account_type = models.TextField() # This field type is a guess. objects = AccountManager USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'registration_date', 'account_type'] class Meta: managed = False db_table = 'account' AccountManager class AccountManager(BaseUserManager): def create_user(self, first_name, last_name, birthday_date, sex, country, city, email, mobile_number, registration_date, expired_date, account_type, password): fields = [first_name, last_name, birthday_date, sex, country, email, mobile_number, registration_date, expired_date, account_type, password] user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, birthday_date=birthday_date, sex=sex, country=country, city=city, mobile_number=mobile_number, registration_date=registration_date, expired_date=expired_date, account_type=account_type, ) user.set_password(password) user.save() return user setting.py INSTALLED_APPS = [ 'models', ...] AUTH_USER_MODEL = 'models.Account' AUTHENTICATION_BACKENDS = ('models.backend.EmailOrPhoneBackend',) backend.py class EmailOrPhoneBackend(object): def authenticate(self, username=None, password=None, **kwargs): try: # Try to fetch the user by searching the username or email field user = Account.objects.get(Q(mobile_number=username) | Q(email=username)) if user.check_password(password): return user except Account.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an … -
Django local development, remote test and production configuration
I'm writing some django apps and I have this setup: local machine (laptop) that I use for development, with local dev virtualenv remote machine VPS (with public address) used for test. I need to have some end-users testing my app before moving to prod with test virtualenv remote machine VPS (with public address, same as above) used for production with production virtualenv I use git for versioning. The idea that I have so far (after reading various tutorials) to manage everything is: develop on local machine new branch push branch to git deploy branch into test virtualenv test it test passed, push branch to master and deploy into production virtualenv And I have lot of questions about this: is this a recommended approach? how can I get the new branch to test virtualenv and not to production? Do I need to have two separate app folders, one for prod and one for test? How can I then move code from test to prod? Thanks in advance, I'm a django/git novice so I'm trying to approach it in the best way from start. -
Why sessionid is empty string return response Set-Cookie on django?
There is question for me , why django sessionid is empty value, return set-cookie however sessionid value is empty but set Set-Cookie, request on cookie : Cookie: sessionid=;csrftoken=BF8nOVWsMJaX9Gi3aJijGSO97iTyLpNY here sessionid is empty now response this request from django: HTTP/1.1 200 OK Date: Sun, 09 Oct 2016 08:17:15 GMT Content-Type: application/json Connection: keep-alive Set-Cookie: sessionid=; expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/ Content-Length: 18 why any check sessionid is empty or no from django? and response like without Set-Cookie: HTTP/1.1 200 OK Date: Sun, 09 Oct 2016 08:17:15 GMT Content-Type: application/json Connection: keep-alive Content-Length: 18 -
How do I get an iterable count on a template from a Django queryset?
Lets say I am getting a queryset in my views using the following code. topics = Topic.objects.all()[:3] In my template, I am doing this: <table> <tr> <td>#</td> <td>Name</td> <tr> {% for topic in topics %} <tr> <td>{{ topic.count }}</td> <td>{{ topic.name }}</td> <tr> {% endfor %} </table> Basically, I want a table with 1, 2, 3 in the first column, and the names of the topics in the second column. How do I do this? -
How to call a view when open a modal in django
In my project i want that if i click on a button Register it opens a bootstrap modal <div class="modal fade" id="confirm" data-backdrop="static"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Request Pending</h4> </div> <div class="modal-body"> you are already requested.PLease wait </div> <div class="modal-footer"> <button type="button" class="btn btn-info" data-dismiss="modal">OK</button> </div> </div> </div> </div> Now i want when this modal open a view for IncreaseCount will execute def IncreaseCount(request): ...... ...... ...... return render(request, context) This is my button from where modal open <a href="javascript:;" class='btn btn-info' onclick="jQuery('#confirm').appendTo('body').modal('show', {backdrop: 'static'});">Register </a> i want when this modal open an view also called. How can i call a view on opening this modal. -
How is Django able to grant reserved port numbers?
Using this command python manage.py runserver 0.0.0.0:8000 we can host a Django server locally on any port.So a developer can use reserved and privileged port numbers say python manage.py runserver 127.0.0.1:80 So, now I am using port 80 defined for the HTTP protocol. So, why does this not raise any issues and how is this request granted ? -
Python concurrent.futures - method not called
I am running a local django server with the following code: import concurrent.futures media_download_manager = concurrent.futures.ProcessPoolExecutor(max_workers=2) def hello(): print "hello" for i in range(1, 1000): print "submitting task " media_download_manager.map(hello) I am initializing a process pool executor to accept tasks with 2 worker threads. The tasks are being submitter but the worker threads handling the submitted tasks do not seem to have triggered. Following it the console output: submitting task 1 submitting task 2 submitting task 3 submitting task 4 submitting task 5 submitting task 6 submitting task 7 submitting task 8 submitting task 9 Performing system checks... System check identified no issues (0 silenced). October 15, 2016 - 06:09:31 Django version 1.8.4, using settings 'Learn.settings' Starting development server at http://192.168.1.3:8000/ Quit the server with CONTROL-C. Are there any settings I'm missing here or is there any known issue with concurrent.futures module ? -
Django returning static HTML in views.py?
So I have a standard Django project with a basic view that returns a simple HTML confirmation statement. Would it be plausible for me to define all of my HTML in the view itself as a really long string and return that using HttpResponse() I know it's a bit unorthodox, but this is an example of what I'm thinking about: from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import render_to_response def index(request): html = """ <html> <body> This is my bare-bones html page. </body> </html> """ return HttpResponse(html) My corresponding JS and stylesheets would be stored in the same directory as views.py in my app in this example. Just making sure: I am not asking if this works, because I already know the answer is yes, I just want to know if there are any disadvantages/drawbacks to this method, and why don't more people do this? -
Where does Django store CSRF tokens?
I'm assuming that a copy of the token is stored somewhere in the database (because it changes at login so it is persistent~ish), but I can't find it. I've tried manually looking at the table columns, and looking in django.middleware.csrf for clues. Where is it stored? Or a more general version of my question (in case my assumption is wrong and Django doesn't have to store it in the database): How does Django know what token to compare the CSRF-cookie to? -
Django REST could not resolve URL for hyperlinked relationship
I'm have error in my Django REST API(full traceback): Internal Server Error: /api/users/ Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\relations.py", line 361, in to_representation url = self.get_url(value, self.view_name, request, format) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\relations.py", line 298, in get_url return self.reverse(view_name, kwargs=kwargs, request=request, format=format) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\reverse.py", line 50, in reverse url = _reverse(viewname, args, kwargs, request, format, **extra) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\reverse.py", line 63, in _reverse url = django_reverse(viewname, args=args, kwargs=kwargs, **extra) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\urlresolvers.py", line 600, in reverse return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\urlresolvers.py", line 508, in _reverse_with_prefix (lookup_view_s, args, kwargs, len(patterns), patterns)) django.core.urlresolvers.NoReverseMatch: Reverse for 'album-list' with arguments '()' and keyword arguments '{'pk': 1}' not found. 0 pattern(s) tried: [] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\viewsets.py", line 87, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\views.py", line 474, in dispatch response = self.handle_exception(exc) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\views.py", line 434, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\views.py", line 471, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\mixins.py", line 48, in list return Response(serializer.data) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\serializers.py", line 701, … -
Syntax Error with Django, WSGI, and Apache
I am getting a weird error while trying to run my Django site under Apache using mod_wsgi. I have been working on this for hours to no avail. FYI: I am also using Mezzanine. Log: [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] mod_wsgi (pid=15554): Target WSGI script '/opt/mysite/mysite/wsgi.py' cannot be loaded as Python module. [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] mod_wsgi (pid=15554): Exception occurred processing WSGI script '/opt/mysite/mysite/wsgi.py'. [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] Traceback (most recent call last): [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] File "/opt/mysite/mysite/wsgi.py", line 12, in <module> [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] from django.core.wsgi import get_wsgi_application [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] File "/usr/lib/python2.6/site-packages/django/__init__.py", line 3, in <module> [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] from django.utils.version import get_version [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] File "/usr/lib/python2.6/site-packages/django/utils/version.py", line 7, in <module> [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] from django.utils.lru_cache import lru_cache [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] File "/usr/lib/python2.6/site-packages/django/utils/lru_cache.py", line 28 [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] fasttypes = {int, str, frozenset, type(None)}, [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] ^ [Fri Oct 14 … -
How to Make a comma seperated string of specific field in SQL query?
I am using Django 1.8 with python 2.7 I am using connection from django.db And here is my view code : from django.db import connection def someview(request): userId = loadedJsonData.get('userId') cursor = connection.cursor() sql=''' SELECT b.name,b.price,d.type FROM user_table AS a JOIN offer_table AS b ON a.offer_id = b.id INNER JOIN specialities_for_offer AS c ON b.id = c.offer_id INNER JOIN specialities AS d ON c.speciality_id = d.id WHERE a.user_id = %s ''' cursor.execute(sql,[userId]) My question is How to group the data of d.type as comma separated string for every record with same offer_table id. I tried "group by b.id" but it gives only one record for every b.id with one d.type but I need one record for every b.id with all d.type as comma separated string. Thanks In advance. -
Url maps operation in Django
i'm new to django and i'd like to know how the url maps work in detail. from django.conf.urls import url from polls import views urlpatterns =[ url(r'^$',views.index,name='index') ] the url function takes 3 parameters, could you explain how they work and what functionalies they have. I've searched for this, but no detailed information are available for a absolute beginner -
Simple Amazon server
I've been struggling to do this for a while now, for some reason EC2 and Elastic Beanstalk just isn't working properly for me. Hoping that you guys can help me with this. All I want to do is get a free server where I can host my website that's on Django (Python 2.7). I want to be able to ssh into it, so something like a linux box, upload code via FTP into the server, something like Digital Ocean. Does anyone know how I can get this done? :\ -
How to set blank=False in Django form without a Model
I made a Django form by extending forms.Form without a database model. How can i set blank=False on a CharField so that Django validation will check for me wheteher the field is empty or not? -
Import file from another app in Django 1.10
I'm trying to import a file from another app, and I get this error: Unhandled exception in thread started by <function wrapper at 0x7fe7bc281d70> Traceback (most recent call last): File "/home/carlos/.envs/lafam/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/carlos/.envs/lafam/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/home/carlos/.envs/lafam/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/carlos/.envs/lafam/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/carlos/.envs/lafam/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/carlos/.envs/lafam/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/carlos/.envs/lafam/local/lib/python2.7/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/carlos/www/lafam/apps/maquina/models.py", line 6, in <module> from apps.website.managers import GenericManager ImportError: No module named website.managers INSTALLED APPS in settings.py SYSTEM_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] PROJECT_APPS = [ 'apps.website', 'apps.maquina', ] INSTALLED_APPS = SYSTEM_APPS + PROJECT_APPS All my apps are in apps folder. I have an app called "maquina". And this is its modals.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from apps.website.managers import GenericManager from .utils import path_and_rename class Fabricante(models.Model): ... I created a file called managers.py from another app called website from django.db import models class GenericManager(models.Manager): def get_or_none(self, *args, **kwargs): try: return self.get(*args, **kwargs) except self.model.DoesNotExist: return None except … -
Django: How to use AJAX to check if username exists on registration form?
When the user enters a username, I want to check the db if that username already exists and display an error message. How would I do that without refreshing the page? With AJAX? registration_form.html <div class="container-fluid userformcontainer"> <div class="row"> <div class="col-md-offset-2 col-sm-offset-1 col-sm-8 userformdiv"> <h1 class="title userformtitle">Sign up</h1> <form method="POST" class="post-form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit" class="save btn btn-default btn-lg userformbutton center-block">Register</button> {% endbuttons %} </form> </div><!--col--> </div><!--row--> </div><!--container--> views.py class UserFormView(View): form_class = SignUpForm template_name = 'card/registration_form.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] user.first_name = form.cleaned_data['first_name'] user.last_name = form.cleaned_data['last_name'] if not User.objects.filter(username=username).exists(): password = form.cleaned_data['password'] user.set_password(password) user.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('card:deck_list') else: pass else: pass forms.py class SignUpForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'password']