Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and Redis package options
I am busy researching how best to incorporate Redis with my Django based site and am a bit confused when it comes to the available package options. Im trying to decide between: redis-py django-redis django-redis-cache Under the hood, django-redis and django-redis-cache both use redis-py. So why don't I just use redis-py directly? I can't seem to figure out what the benefit of using one of the django packages are if I can simply import redis in my Django project and off I go. I am busy going through the documentation, but can't seem to find anything that directly answers this question. -
Apache - Prefork and Worker
I am trying to build a Python Web Application using Django. On it's official "how-to-install" page, it says Apache and mod_wsgi must be installed. I have manually installed, in my Ubuntu machine, Apache 2.2.31 HTTP Server at the location /usr/local/apache I am looking up for the instructions for installing mod_wsgi from https://pypi.python.org/pypi/mod_wsgi On this site, it says for "system requirement" that the apache prefork or worker mpm along with its respective developer variant needs to be installed. After executing the following command, /usr/local/apache/bin/apachectl -V I am getting many outputs, one of which says that the MPM Server is "Prefork". So, my conclusion is that MPM Servers are prepackaged with Apache. Now, my questions are 1) How to change the MPM Server from "Prefork" to "Worker"? 2) Since I have manually installed Apache, how to install the developer variant of the MPM Server? If it is already installed, how to verify it? -
django make complex queryset
I am writing an app where I have a house with many family in it and just one of Fathers or Mothers is head of house: class House(models.Model): .... def get_head_of_house(self) #searchs in fathers and mothers and find which one is head of house #and returns it class Fathers(models.Model): house = models.ForiegnKey(House) first_name = models.CharField() last_name = models.CharField() is_head = models.BooleanField() .... class Mothers(models.Model): house = models.ForiegnKey(House) first_name = models.CharField() last_name = models.CharField() is_head = models.BooleanField() .... In search form, I get first name and last name of head of a house. I want to search in fathers and mothers and select head of all houses where form.fname is in their first_name or form.lname is in their last_name The problem is where heads are in separate models and I care about matching either first-name or last-name and more important queryset can not be filled manually. How can I create this query? -
python-accessing the next object in database while in for loop
This is my view code. I iterate over all the entries in DB and when rollno matches, I want to store the student name for previous,current and next student in one go. Is there any way to implement it? rollno has alphanumeric values. if request.method == 'POST': rollno = request.POST.get('roll',None) studentlist = Students.objects.all() for st in studentlist: if st.roll_no == rollno: three_students=[*prev_student,current_student,next_student*] -
Database url with % in password not working with sqlalchemy
I'm reading DATABASE_URL from env variable in uwsgi file. My django ORM connection is working with % in password but when I try to connect with sqlalchemy it is not working. from sqlalchemy import orm, create_engine, MetaData from app.settings import DATABASES from urllib import quote_plus con = "mysql+pymysql://{0}:{1}@{2}:{3}/{4}".format( DATABASES['default']['USER'], DATABASES['default']['PASSWORD'], DATABASES['default']['HOST'], DATABASES['default']['PORT'], DATABASES['default']['NAME'] ) engine = create_engine( con, echo=False, pool_recycle=1800, max_overflow = 250, pool_size=200 ) I even tried quote_plus but it did not worked. This does not works mysql+pymysql://api:@>J.6D%qhZ@localhost:3306/table_tmp This works mysql+pymysql://api:@>J.6DqhZ@localhost:3306/table_tmp When I use same password with % via ipython it works but via env variable in uwsgi.ini file it doesn't -
Django store dictionary data in session doesn't persistent
I'm trying to do something similar to a shopping cart. Selected items will be added to self.request.session in a dictionary with their id as key and count as value. The issue is that every time I refresh the page, stored items in this dictionary will be lost and the dictionary stored in session will be set empty. I tried to set the session.modified = True and SESSION_SAVE_EVERY_REQUEST = True but neither worked. Here is the code, the logic is when no item is added before, initial the dictionary and add this item in with count 1, when the cart is initialised then just add this item in with count 1, when this item is already in cart just add up its count by 1: try: self.request.session['item'][id] += 1 except KeyError as e: if e.args[0] == 'item': self.request.session['item'] = dict() self.request.session['item'][id] = 1 else: self.request.session['item'][id] = 1 else: pass self.request.session.modified = True Thanks for your answer. -
django FilterSelectMultiple form filter
I have a django admin form in which I am using a filterSelectMultiple widget. I want to populate this widget with the data that is filtered on the basis of a previously selected drop down value. I tried using ajax call and then filling the widget but the default functions of the widget are not working in this case. class UserForm(forms.ModelForm): state = UserModelStateMultipleChoiceField( widget=FilteredSelectMultiple( verbose_name='states', is_stacked=False, ), queryset=State.objects.all().prefetch_related('country') ) I want to populate this state widget on the basis of the country of the user. How can I achieve this? -
Django: what are the best practices to serve REST requests?
We have a running django app (nginx + gunicorn) and now we're about to add REST layer for external usage. Many requests can hit the app simultaneously. We can't use the django-rest framework. What are the best practices to serve such requests? We would like to answer back fast. dedicated server? nginx tweaks? DB caching? -
Updating other players screen Django
I am developing a small game with four members for a board. When a player moves something, that move has to updated in remaining players screen(their webpage). I ended up tornado, but I can't find any examples for my case. I need to display the move to all players when a move was saved in DB. Polling DB continuously after x seconds may miss some moves. How can I achieve this. -
How to test postgresql specific feature such as JsonField in Django?
I would like to use Postgresql specific JSONField in Django, however, I have not found a way to test with sqlite environment. Any tip for elegant way? -
Upload Image in Django ImageField
I'm try to test my model with ImageField, for this purpose i'm reading .jpg file in binary mode and save in the model. I find a lot of question in StackOverflow, but nothing seems to work for me. testImagePath = os.path.join(settings.BASE_DIR, 'test_image_folder/test_image.jpg') "image" : SimpleUploadedFile(name='test_image.jpg', content=open(testImagePath, 'rb').read(), content_type='image/jpeg') error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte -
Advice on building a web app
Ill just start by saying I know a very basic amount about web app development but I have a project to do for college and my idea was to create a primitive version control web app (something like Gitlab). I was hoping someone could give me advice on whether it is possible or sensible to build it using Django and Reactjs (Would like to use these just to learn). I would even just appreciate if someone could clarify exactly what is involved in undertaking a project like this? Apologies for my naivety, thank you. -
Django image upload from ios app : Check the encoding type on the form erro
I have made APIs in Django and uploading a file from the IOS app. I'm passing file by converting it into data using multipart request. It's uploading fine from the Postman but while posting from application, i'm getting following error, { "userProfilePicture":["The submitted data was not a file. Check the encoding type on the form."] } Can anybody help me with this out? -
Post method redirecting to its own page while submmiting Data from input fields
here are my models: models.py class Customer(models.Model): fname=models.CharField(max_length=200) lname = models.CharField(max_length=100) email=models.CharField(max_length=100) address = models.CharField(max_length=500) city = models.CharField(max_length=200) state = models.CharField(max_length=200) zip = models.IntegerField() username = models.CharField(max_length=100) password = models.CharField(max_length=100) age=models.IntegerField() phone=models.IntegerField() mobile=models.IntegerField() here is my form.py class CustomerForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CustomerForm, self).__init__(*args, **kwargs) fname = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'required': 'required'})) lname = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'required': 'required'})) email= forms.EmailField(widget=forms.TextInput(attrs={'class':'form-control', 'required': 'required'})) address = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'required': 'required'})) city = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'required': 'required'})) state = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'required': 'required'})) zip = forms.IntegerField(widget=forms.TextInput(attrs={'class':'form-control', 'required': 'required'})) username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'required': 'required'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'required': 'required'})) age = forms.IntegerField(widget=forms.TextInput(attrs={'class': 'form-control', 'required': 'required'})) mobile= forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'required': 'required'})) phone = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = Customer fields = ['fname','lname','email','address','city','state','zip','username','password','age','mobile','phone'] here is my view.py @login_required(login_url='/customer/signin/') def createcustomer(request): if request.method == 'POST': form = CustomerForm(request.POST) if form.is_valid(): print ("hello") customer_save=Customer.objects.create( fname=form.cleaned_data['fname'], lname = form.cleaned_data['lname'], email= form.cleaned_data['email'], address= form.cleaned_data['address'], city=form.cleaned_data['city'], state=form.cleaned_data['state'], zip=form.cleaned_data['zip'], username=form.cleaned_data['username'], password=form.cleaned_data['password'], age=form.cleaned_data['age'], mobile=form.cleaned_data['mobile'], phone=form.cleaned_data['phone'], ) customer_save.save() return HttpResponseRedirect('/customer/customertable') else: form = CustomerForm() return render(request, 'customer/createcustomer.html', {'form': form}) now whem I hit Submit button it should redirect on other page called customertable but it is redirecting to its own where we are posting data here is my html page {% extends 'customer/base.html' %} {% block β¦ -
Django what will happen if I use os.environ.__setitem__ to change DJANGO_SETTINGS_MODULE?
I want to change the location of django's settings.py file. But I don't find anyone do this by using setitem. I use this to configure settings successfully,but I want to know , is there some bad consequences ? -
Django: How to get count of a specific column according to two columns
i want to get the count of the user id of this table according to the columns approval_transaction_type and approval_type. the expected result of this would be. Approval Transaction Type ID (60) Approval Type ID (65) = 2 Users Approval Type ID (64) = 2 Users Approval Type ID (63) = 2 Users Approval Type ID (62) = 2 Users Approval Type ID (61) = 2 Users My current code to achieve is this, but it overwrites the sub list and returns the incorrect result(Which i don't understand why the last array will overwrite all the array): for transaction in transaction_types: # Initial Array transaction["approval_types"] = [] for approval_type in approval_types: # Get Count of Users approval_type["count"] = Model.objects.filter(approval_transaction_type=transaction['id'],approval_type=approval_type['id']).values().count() # Assign this sub list to main list transaction["approval_types"].append(approval_type) How do i get the count without looping and use the queryset? Let me know if something is not clear about this. Thanks! -
save datatable data to database
I am trying to create a website using Django. In the website, there is a table which I should be able to edit online and the edit should be reflected to the database. I am using the datatable editor example from the below link as the original datatable editor needs a dedicated license. The script(indented below) is what I am using in my html file instead of whats there on the jsfiddle. I want to save the data to database once I edit any field on the website. http://jsfiddle.net/rmcmaster/bbLjzspf/22/ <script> $(document).ready(function() { var dataSet = [ {% for data_i in table_data %} [{{data_i.name}}, {{data_i.Position}}, {{data_i.Office}}, {{data_i.Salary}}] , {% endfor %} ]; var columnDefs = [{ title: "Name" }, { title: "Position" }, { title: "Office" }, { title: "Salary" }]; var myTable; myTable = $('#example').DataTable({ "sPaginationType": "full_numbers", data: dataSet, columns: columnDefs, dom: 'Bfrtip', // Needs button container select: 'single', responsive: true, altEditor: true, // Enable altEditor buttons: [{ text: 'Add', name: 'add' // do not change name }, { extend: 'selected', // Bind to Selected row text: 'Edit', name: 'edit' // do not change name }, { extend: 'selected', // Bind to Selected row text: 'Delete', name: 'delete' // do β¦ -
DoesNotExist at /admin/login/
DoesNotExist at /admin/login/ Site matching query does not exist. Request Method: GET Request URL: https://tehb123.pythonanywhere.com/admin/login/?next=/admin/ Django Version: 1.9.3 Exception Type: DoesNotExist Exception Value: Site matching query does not exist. Exception Location: /usr/local/lib/python3.5/dist-packages/django/db/models/query.py in get, line 387 Python Executable: /usr/local/bin/uwsgi Python Version: 3.5.1 Python Path: ['/var/www', '.', '', '/home/tehb123/.local/lib/python3.5/site-packages', '/var/www', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages', '/home/tehb123/mysite'] Server time: Thu, 13 Oct 2016 05:34:55 +0000 urls from django.conf.urls import url, patterns, include from django.contrib import admin from django.contrib.flatpages import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('Mysitez.urls')), # url(r'^pages/', include('django.contrib.flatpages.urls')), ] urlpatterns += [ u rl(r'^(?P.*/)$', views.flatpage), ] -
Django global static files
I want to have global static files and templates for all my apps. My apps also will have templates and static files It will look something like this: I am loading my global files like these but it is not working. href="{% static 'bootstrap/css/bootstrap.min.css' %}" projectname]/ <- project root βββ [projectname]/ <- Django root β βββ __init__.py β βββ settings/ β βββ urls.py β βββ wsgi.py βββ apps/ β βββ __init__.py β βββ manage.py β βββ static/ β βββ GLOBAL STATIC FILES βββ templates/ βββ GLOBAL TEMPLATES My settings.py looks like this: STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, '/static') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, '/static'), ) -
django models manager for content type models
I am currently writing a Django Application to contain all the Content Type Models(generic relations) from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.core.validators import RegexValidator class AddressManager(models.Manager) : def create_address(self, content_obj, address1, address2, postal_code): address = Address(content_object = content_obj, address1 = address1, address2 = address2, postal_code = postal_code) address.save() return address class Address(models.Model): address1 = models.CharField(max_length=100, default=None) address2 = models.CharField(max_length=100, default=None) postal_code = models.TextField(default=None) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, default=None, null=True) object_id = models.PositiveIntegerField(default=None, null=True) content_object = GenericForeignKey('content_type', 'object_id') objects = AddressManager() When I use this on local server, it serves its purpose well. However, when I run python manage.py test This error occurs ====================================================================== ERROR: test_address__custom_methods (genericmodels.tests.test_models.TestBasic) ---------------------------------------------------------------------- Traceback (most recent call last): File "/path/genericmodels/tests/test_models.py", line 15, in test_address__custom_methods "t_postal_code") File "/path/genericmodels/models.py", line 11, in create_address postal_code = postal_code) File "/path/env3/lib/python3.5/site-packages/django/db/models/base.py", line 555, in __init__ raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) TypeError: 'content_object' is an invalid keyword argument for this function ---------------------------------------------------------------------- Ran 1 test in 0.310s FAILED (errors=1) Destroying test database for alias 'default'... The test code is as follows : from django.test import TestCase from unittest.mock import MagicMock from genericmodels.models import * from anotherapp.models import β¦ -
Django Model's table not being created when migrated
I am new to Django and have tried to create an api with a model called Words. When I try to 'migrate' the model, I get the following error: 'django.db.utils.OperationalError: no such table: quickstart_words' I have tried python manage.py makemigrations wordCloud and python manage.py migrate wordCloud Both result in the previously described error message. Could someone please tell me what I am doing wrong? My model.py looks like: from django.db import models class Words(models.Model): word = models.CharField(max_length=128) weight = models.IntegerField(default=1) time = models.TimeField(auto_now = False) My directory structure looks like: My settings.py installed apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'wordCloud.quickstart', 'django_feedparser' ] -
Django: request.session is stable even when using multiple server?
According to some Django books and online codes, some values are passed as session variable when needing to redirect(in server side) with some context variables, e.g. request.session['fruit'] = 'apple'. But I wonder it really works well even when I user multiple servers.(Let's call each server as A,B,C) In this case, user's request can be RANDOMLY sent to one of these servers. For example, first request is sent to A server and next request is sent to B server and third request go to A server again. So, I just thought that session data (request.session) could be lost or going messy because of this randomness. Am I right? or Since session is a server-side data based on user's cookie session-id and saved in database, so I don't have to worry about it? Thanks :) -
Django + Queryset + m2m + ForeignKey
I am trying to get a list with unique 'source' and all users added 'terms' for it, e.g. from: user1 1 [3,4,5] user1 2 [1,2] user2 1 [1,2] user2 2 [3,4,5] to: 1 1,2,3,4,5 2 1,2,3,4,5 my model: class User_Filter(models.Model): user = models.ForeignKey(User) source = models.ForeignKey(Source, null=True) terms = models.ManyToManyField(Term) I am playing around with this code: sources = User_Filter.objects.values('source').distinct() This line spits out dict: {'source': 2} {'source': 3} And from this point I am stuck. Any help is really appreciated. -
django-background-tasks indefinite run
The docs says, In Django Background Task, all tasks are implemented as functions (or any other callable). There are two parts to using background tasks: creating the task functions and registering them with the scheduler setup a cron task (or long running process) to execute the tasks It appears there is no way to run django-background-tasks indefinitely, is that correct? -
django-pipeline throwing ValueError: the file could not be found
When running python manage.py collectstatic --noinput I'm getting the following error: Post-processing 'jquery-ui-dist/jquery-ui.css' failed! Traceback (most recent call last): File "manage_local.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 193, in handle collected = self.collect() File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 145, in collect raise processed File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 257, in post_process content = pattern.sub(converter, content) File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 187, in converter hashed_url = self.url(unquote(target_name), force=True) File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 132, in url hashed_name = self.stored_name(clean_name) File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 292, in stored_name cache_name = self.clean_name(self.hashed_name(name)) File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 95, in hashed_name (clean_name, self)) ValueError: The file 'jquery-ui-dist/"images/ui-icons_555555_256x240.png"' could not be found with <pipeline.storage.PipelineCachedStorage object at 0x1073e2c50>. If I run python manage.py findstatic jquery-ui-dist/"images/ui-icons_555555_256x240.png" I get: Found 'jquery-ui-dist/images/ui-icons_555555_256x240.png' here: /Users/michaelbates/GoogleDrive/Development/inl/node_modules/jquery-ui-dist/images/ui-icons_555555_256x240.png /Users/michaelbates/GoogleDrive/Development/inl/staticfiles/jquery-ui-dist/images/ui-icons_555555_256x240.png Here are some relevant settings: STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'pipeline.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', ) STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') My PIPELINE settings dict is huge so I won't post the entire thing, but some parts of it are: PIPELINE = { 'STYLESHEETS': { 'pricing': { 'source_filenames': ( 'jquery-ui-dist/jquery-ui.min.css', ), 'output_filename': 'css/pricing.min.css' }, β¦