Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get objects in django queryset from given interval
I want to get my queryset to return some objects that are in the given interval for example from position 26 until position 30 , my queryset need to have only 3 elements that are on 27 ,28 , 29 positions.My code: object_query_set = Comment.objects.filter(id_chat=id_chat).order_by('-date')[:26-30] -
Django App vs Apps?
I have read some StackOverflow answers including Django: "projects" vs "apps" and using django apps vs established apps...security? , but I am still looking for advice how to organize my Django application and why? My market place app has following functions and I am trying figure if I should split my app or just build a single app and what implications does this decision have? home - front page, search, and rendered cards for search results detailview - what you see when click the result card booking flow - pinax stripe paymens and few booking views blog - self explaining messages - django-messages with customised view allowing provider - customer communication static - t&c, about and contact static pages task - celery jobs for email and other backgroud stuff as needed For me this is really one app. User seaches provider, finds one, contacts provider and books a service. However when I am look for example applcations this type of functionality is often split to multible apps. My questions is why? I have limited experience on designing software and afraid I am making large mistake here. I plan to separate app with provider listing functions & allowing me to first … -
Create mixin in forms to check passwords
I have some models of Patient, Doctors and so on, then I use them to create forms based on ModelForm with some additional fields: class CreateClinicForm(forms.ModelForm): email = forms.EmailField(required=True) name = forms.CharField(max_length=200, required=True) specialties = forms.CharField(max_length=100, required=True) phone = forms.IntegerField(required=True) class Meta: model = Clinic fields = ('name', 'specialties') And I have password checking in these forms, so it would be nice to use mixin. I have tried to create this one, but it doesn't work. class PasswordMatchMixin(object): password = forms.CharField(max_length=32, required=True) password_confirm = forms.CharField(max_length=32, required=True) def clean_password_confirm(self): password = self.cleaned_data.get('password') password_confirm = self.cleaned_data.get('password_confirm') if password and password != password_confirm: raise ValidationError(_("Passwords don't match")) return self.password_confirm Of course, after that I added it to my forms like this : class CreateDoctorForm(PasswordMatchMixin, forms.ModelForm) : ... Some thoughts or ideas? -
Proxy Alias beetwen two servers
Is that posible to make proxy server beetwen two servers only in apache? I have server1, e.g. http://server1.com And this server comunicate by ajax with temporary server2, e.g. http://server2.com And on the server2 I have a small Django app which comunicate with server3. e.g. def myview(request): #take data from requst #make some extra operations #make another request with requests to server3 #if data from server 3 comes, return it as a response Can I change this django app by apache proxy? If I send request from server1 to http://server2/smt it must be redirect to http://server3/smt and server3 make backend operations and return it -
django file upload case sensitivity
In my django app users are allowed to upload a file that is then saved in the server filesystem while a reference (path to file in FS) is saved to the database. When the file is saved django checks the name against already existing files. If a file with the same name exists a suffix is automatically added to the file name (e.g. test.txt -> test_X9tjHiC.txt). On linux OS django check is case-sensitive, i.e. test.txt and test.TXT are considered different filenames and no suffix is appended. But users can also download the files and of course they may use different a different OS, so if a user downloads the files test.txt and test.TXT a Windows OS sees the files as the same and wants to overwrite the first one. So i want to make django to test against existing files without case sensitivity, while the actual file name should possibly be saved respecting the case sensitivity (firstTest.txt saved as such, and not as firsttest.txt). views.py def addFile(request, element_id, section, **kwargs): element = get_object_or_404(Element, pk=element_id) # if POST request if request.method == 'POST': if hasattr(request,'FILES'): form = forms.AddfileForm(request.POST, request.FILES) if form.is_valid(): file = File(element = element, file = request.FILES['file'], description = … -
Django SECURE_SSL_REDIRECT and 301 HTTP responses
In environments different from local, I set DJ_SSL_REDIRECT = True for my Django project. But now, all my unit tests related to REST API endpoints failed when they are run in another environment (for example, in Travis CI). What is happening is that all HTTP responses are 301 (I'm expecting 2XX or 4XX in my tests) because of the DJ_SSL_REDIRECT setting. How do you deal with this in a simple way? Thanks. Note : I'm using Django Rest Framework 3.5 -
Django templating language doesn't display anything
I have the following code in my views.py: questions = list(Question.objects.all()) for question in questions: print(question.content) return render_to_response('questions.html', questions) Which prints: How much is 2 + 2? What's the tallest mountain on Earth? So the questions list is not empty. questions.html is: <head></head> <body> These are the questions!!! <ul> {% for question in questions %} <li><p>{{ question.content }}</p></li> {% endfor %} </ul> </body> The problem is that when I access questions.html in the browser, the questions' content is not displayed. Why is this happening? -
Django management command mysql errror
I am getting django.db.utils.NotSupportedError: (1235, "This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'") when i try to run this script class Command(NoArgsCommand): def handle_noargs(self, **options): survey_res = SurveyResults.objects.all() for i in survey_res: rescount = SurveyResults.objects.filter(pkey=i.pkey, partner_id=i.partner_id).count() if rescount > 1: objs = SurveyResults.objects.filter(pkey=i.pkey, partner_id=i.partner_id)[:1] SurveyResults.objects.exclude(pk__in=objs).delete() any solutions..? I am trying to delete all records except the latest which have two fields in common. -
Django oracle backend querying with "%s" literal string
Posting here first just to make sure this was not an error on my part. While trying to create objects in the Django admin on a class that has many to many relationship with another class, it raised ORA-00911: invalid character. This is the last query executed before the error : Query : SELECT "GEO"."PESSOA"."OBJECTID" FROM "GEO"."PESSOA" INNER JOIN "GEO"."DJANGO_DOCUMENTO"_PF951 ON ("GEO"."PESSOA"."OBJECTID" = "GEO"."DJANGO_DOCUMENTO"_PF951."PESSOA_ID") WHERE "GEO"."DJANGO_DOCUMENTO"_PF951."DJANGOTESTDOCUMENTO_ID" = %s Why would Python print a literal "%s" ? Traceback : Traceback (most recent call last): File "C:\Users\6036794\Documents\django\djangogirls\myvenv\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Users\6036794\Documents\django\djangogirls\myvenv\lib\site-packages\django\db\backends\oracle\base.py", line 482, in execute return self.cursor.execute(query, self._param_generator(params)) cx_Oracle.DatabaseError: ORA-00911: invalid character -
How to annotate weight column from a python list when filtering/sorting a django queryset?
Let's say I have a model Product and I need to sort the queryset results by highest recommended, then by price. I get the recommendations from an external service as a list of integers and represent the product ids (the smallest the index of a product in that list the highest the recommendation score): [7, 249, 28, 24, ...] I need a way to annotate this when doing: Product.objects.order_by('weight', 'price').annotate(weight=?) to get the products with the highest score first before I apply result paging using [:limit]. For example consider this db: ID Price 1 $0.70 2 $0.99 3 $0.99 4 $0.99 5 $0.99 6 $0.99 7 $0.99 8 $0.99 9 $0.50 10 $0.99 Recommendation: 8, 2, 4 Page size: 5 Expected results: 8, 2, 4, 9, 1 -
Django - beginner- what is the process for passing information to a view via a url?
I am working on my first django project which is also my first backend project. In the tutorials/reading I have completed, I haven't come across passing information back to django without a modelform. My intention is to calculate a value on a page using javascript and pass it to django when a user hits a submit button on that page. The submit button will also be a link to another page. I know I could process the information in a view via the url if I knew how to pass the information back to django. I'm aware that django uses MVC and as I have my models and views in place, I am lead to believe that this has something to do with controllers. Basically, I would like to know how to pass information from a page to django as a user follows a link to another page. I understand that this isn't the place for long step by step tutorials on specific topics but I would appreciate any links to resources on this subject. I don't know what this process is even called so I can't search documentation for it. -
Django Custom 404 handler
We've recently upgraded to Django 1.10 and we're getting this error on the live site: builtins:TypeError custom_404() got an unexpected keyword argument 'exception' The code is as follows: urls.py urlpatterns = [ ... ] handler404 = global_views.custom_404 handler500 = global_views.custom_500 global_views.py def custom_404(request, exception, template_name='404.html'): return page_not_found(request, exception, template_name=template_name) def custom_500(request, exception, template_name='500.html'): return page_not_found(request, exception, template_name=template_name) We've tried many variations of this view but all result in that error. What's going wrong? -
Set verbose_name value as field value
I want to automate the verbose_name value to be the same value as the "name" field value of the object in database table. from __future__ import unicode_literals from django.db import models class Person(models.Model): name = models.CharField(max_length=150, blank=True, null=False) class Meta: db_table = '"ADM"."PERSON"' # Just an example: verbose_name = (super).name.getValue() I wonder if this makes sense or a query will be needed and some "on_update" event -
Python3 doesn't see Django
When I attempt to verify that Python3 can see Django by entering python3 followed by import django into the terminal (so I can print Django's version number), I get the following error: Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named 'django' Python can detect Django if I enter python (followed by import django), but not python3. How can I correct this so Python3 can also detect Django? These are the steps I took to install Django on my local machine: Upgraded pip: sudo -H pip3 install --upgrade pip Downloaded and installed latest version of Python from binary. Created project directory: mkdir django-start && cd $_ Installed virtualenv: pip3 install virtualenv Created an environment: virtualenv env Activated the environment: source env/bin/activate Installed Django: pip install django -
Django custom backend authentication for authenticate to Django REST
In a Django website I wrote a custom backend who authenticates through token authentication to another Django website with REST Framework. In the get_user(user_id) method I need to get the token authentication (because I can't make an api request without it), but I don't know how to do it. I thought to use sessions, but I haven't access to the request object. I try to use a cache variable, but it happens that last authenticated user gets the token of the previous authenticated one (because cache variable was already set)... Any ideas? -
RHEL - Transitioned Django project from Windows throws django.db.utils.Error: ('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found
I inherited a Django project from a former colleague. My first job is to migrate the development version from our production Windows server to a RHEL server. I've setup the same versions of Python and Django that were on Windows, installed the same libraries, fixed the hard coded filesystem paths, and set up a virtual environment that's the same as the one in use on Windows. When I run python manage.py runserver I get the error Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function wrapper at 0x7eff42540de8> Traceback (most recent call last): File "/srv/P27_D19/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/srv/P27_D19/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check_migrations() File "/srv/P27_D19/lib/python2.7/site-packages/django/core/management/base.py", line 437, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/srv/P27_D19/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in init self.loader = MigrationLoader(self.connection) File "/srv/P27_D19/lib/python2.7/site-packages/django/db/migrations/loader.py", line 52, in init self.build_graph() File "/srv/P27_D19/lib/python2.7/site-packages/django/db/migrations/loader.py", line 203, in build_graph self.applied_migrations = recorder.applied_migrations() File "/srv/P27_D19/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/srv/P27_D19/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/srv/P27_D19/lib/python2.7/site-packages/django/db/backends/base/base.py", line 231, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/srv/P27_D19/lib/python2.7/site-packages/django/db/backends/base/base.py", line 204, in _cursor self.ensure_connection() File "/srv/P27_D19/lib/python2.7/site-packages/django/db/backends/base/base.py", line 199, in ensure_connection self.connect() File "/srv/P27_D19/lib/python2.7/site-packages/django/db/utils.py", line 94, in exit six.reraise(dj_exc_type, dj_exc_value, traceback) File … -
send, receive, save local image file with requests / django rest framework
I'd like to http-send (e.g. requests.post) image files from servers/clients (with the requests lib) and receive/save these files with a django rest framework app. How do I do this? Secondly I'd like to know how to extract parts from a QueryDict sent by requests.post in general. And more specific: How do I parse and save the _io-Object from this set of data? # sending app file = "path/to/image.jpg" data = open(file, 'rb') files = { 'json': (None, crawlingResultConnectionsJson, 'application/json'), 'file': (os.path.basename(file), open(file, 'rb'), 'application/octet-stream') } url = "http://127.0.0.1:8000/result/" # receiving/saving django rest framework app r = requests.post(url, files=files) I've tried quite a while know. IYou help would be much appreciated! Thanks! -
Calling a model's method from another model
I am quite new to django so my question might seem very trivial.. I have 2 models (simplified for demonstration purposes): class Subarticle(models.Model): parent_article = models.ForeignKey(Article, related_name='subarticles') priority = IntegerField() .... def getCheapest(self, quantity): //find cheapest subarticle based on qty //code and class Article(models.Model): sub_article_qty = models.IntegerField() def production_cost(self): sub_article = Subarticle.objects.filter(parent_article=self).order_by('priority').first sub_article_price = sub_article.getCheapest(self.sub_article_qty) return sub_article_price*self.sub_article_qty So basically every article has one or more subarticles and I want to be able to find the cost for the article based on the cheapest priced subarticle with the lowest priority number. I am using "rest_framwork" to send the model data with approximately following serializer from .models import Subarticles, Articles from rest_framwork import serializers class SubarticleSerializer(serializer.HyperlinkedModelSerializer): class Meta: model=Subarticle fields=('parent_article','priority') class ArticleSerializer(serializer.HyperlinkedModelSerializer): class Meta: model=Article fields=('sub_article_qty','subarticles','production_cost') But trying to do this like this gives me the following error: Exception raised in callable attribute "production_cost"; original exception was: 'function' object has no attribute 'getCheapest' Is it even possible to do it as I am trying to do or is there some other way of achieving this? -
NoReverseMatch at /forum/
I am trying to implement the django-registration-redux and have used templates written by Andres available at https://github.com/macdhuibh/django-registration-templates . But the problem is whever i run anything i get the NoReverseMatch Error. I tried to render the base.html template to check the error and i got error on line 12. and the base.html is as {% load i18n %} <html lang="en"> <head> <link rel="stylesheet" href="{{ STATIC_URL }}style.css" /> <title>{% block title %}User test{% endblock %}</title> </head> <body> <div id="header"> {% block header %} <a href="{% url 'index' %}">{% trans "Home" %}</a> | {% if user.is_authenticated %} {% trans "Logged in" %}: {{ user.username }} (<a href="{% url 'auth_logout' %}">{% trans "Log out" %}</a> | <a href="{% url 'auth_password_change' %}">{% trans "Change password" %}</a>) {% else %} <a href="{% url 'auth_login' %}">{% trans "Log in" %}</a> {% endif %} <hr /> {% endblock %} </div> <div id="content"> {% block content %}{% endblock %} </div> <div id="footer"> {% block footer %} <hr /> {% endblock %} </div> </body> </html> index.html is as {% extends "base.html" %} {% load i18n %} {% block content %} Index page {% endblock %} and the urls.py as from django.conf.urls import url from . import views app_name = … -
Documenting with DRF Docs Working with DRF
I have currently developed an API with DRF (Django Rest Framework) and I wanted to use a documentation tool for the simplicity. However, I have just noticed that DRF seek for APIViews but not for ViewSets. The problem is that, although it shows the endpoints, because ViewSets does not separately implement methods (get, post, put etc), it does not show the correct methods for the endpoints. In such a case, what should I have been using? I may use DRF Swagger as well, but could not be sure if that works for me or not. Or is there any way of working around to this problem? Thanks! -
python filter instances of a class
I am new to Python, and am currently trying to debug some Python code. I have a view which is currently defined like this: def get_current_budget(project_id, prefetch=False): """ Find budget by empty version number, or if none, check whether there is one with a current marker """ if prefetch: project = Project.objects.prefetch_related('budget_versions', prefetch).get(id=project_id) else: project = Project.objects.prefetch_related('budget_versions').get(id=project_id) try: #budget = project.budget_versions.get(version_number=None) budgets = project.budget_versions.filter(version_number=None) print "Latest version of budget: ", project.budget_versions() """ 1. Check how many elements have been saved to 'budgets' 2. Loop through the elements- assign any with no budget items/ presentation date to a test project 3. Return the element with the budget items/ presentation date """ for budget in budgets: if budget.budget_items == "": budget.project = "test" else: budget.project = project return budget except ObjectDoesNotExist: try: budget = project.budget_versions.filter(version_number=0).order_by('-presentation_date')[0] print "Latest verions of budget (execpt- try): ", project.budget_versions() return budget except IndexError: print 'Budgets found', project.budget_versions.all() return None The purpose of this view is to take a parameter of a 'project id', and, based on that ID, return the latest version of the budget belonging to that project, assigning all of the 'older' budgets to a list. However, when I try to run this view in … -
How to send a file using AJAX call without form data
I need to send a PDF file from ajax to call to Django server, without form data -
Django Models: error when using DateField as ForeignKey
Having an issue when trying to use DateField of a model class as the ForeignKey for another model class, and using default set to today on both classes. The error message is: django.core.exceptions.ValidationError: ["'self.date' value has an invalid date format. It must be in YYYY-MM-DD format."] code: class DailyImage(models.Model): date = models.DateField(auto_now_add=True, unique=True) name = models.CharField(max_length = 1000) image = models.CharField(max_length = 1000) location = models.CharField(max_length = 1000) def __str__(self): return str(self.id) + ": " + self.name + ", " + self.location class JournalEntry(models.Model): date = models.DateField(auto_now_add=True) journal = models.CharField(max_length = 5000) image = models.ForeignKey(DailyImage, to_field='date', default='self.date') The site is a daily journal. Each day, it adds an image from unsplash.it to the DailyImage class, which is then displayed as the header on the home page, and header on the page for the journal entry created that day. When a journal entry is created, it should automatically be referenced to the image that was created that day. testing it in shell, the date fields seem to match, but are formatted as: datetime.date(YYYY, MM, DD) >>> a = JournalEntry.objects.get(pk=1) >>> a <JournalEntry: test> >>> a.date datetime.date(2016, 11, 7) >>> from journal.models import DailyImage as image >>> b = image.objects.get(pk=1) >>> b.date … -
default value as callable is only called once during django migration
I've created the following basic django model : import string import random from django.db import models def create_short_url(): size = 6 chars = string.ascii_uppercase + string.digits url = ''.join(random.choice(chars) for _ in range(size)) print("\nSHORT_URL:%s\n" % url) return url class ShortURL(models.Model): url = models.CharField(max_length=220, ) shortcode = models.CharField(max_length=15, unique=True, default=create_short_url) def __str__(self): return str(self.url) First I only coded the url field. Then I added the shortcode field and provided a function to be called to create default unique values. Django's documentation says If callable it will be called every time a new object is created. Unfortunately, when running the migration, I see only one short url generated and the following exception : $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, shortener Running migrations: Applying shortener.0002_auto_20161107_1529... SHORT_URL:43AY7G Traceback (most recent call last): File "/home/user/django1.10/py3/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/user/django1.10/py3/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: shortener_shorturl.shortcode What is missing to call that function for each entry being migrated? -
Django match current URL and load template
So, I am trying to load a template based on the current URL, and For example: {% if 'foo/bar/gallery' in request.path %} {% include 'web/custom/foo/bar/gallery.html' %} {% endif %} The foo/bar/ is dynamic, as are the directory template locations. The string 'gallery' will always be the same, and can be hardcoded if that matters. How can this be achieved? FYI: still on django 1.3.7