Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use Django fields to set schema of a JSONField
Is there any way to specify the schema of a Django PostgreSQL-specific JSONField with other Django fields? For example, the JSONField is a list of objects that their model is defined separately. -
Is a separate Python instance started for each instance of a Django application via Apache?
I'm a little confused as to how Apache manages separate "instances" of a Django application. Let's say I do the following: Go to the URL of my Django application Open up a new browser tab In the new tab, also go to the URL of my Django application Are two Python instances started, one for each browser tab? The application contains a form that a user fills out. After they submit the form, a POST request is sent back to the view. The view then calls another function to do something with the POST data. Let's say I do that in the first browser tab. While that function is running, if I submit the form now in the second browser tab, will running that function be blocked until the function is done running in the first tab? Or are separate Python instances started? I'm just trying to figure out if I need to start a separate process each time the function is called from the view, in order to support multiple "instances" of the application (e.g., either in separate browser tabs or multiple users accessing the application simultaneously). Thanks for any clarification! -
Assign manytomanyfield to another manytomanyfield
I have a PaymentOrRefund model. Negative amounts, obviously, are refunds. Each payment/refund is registered against one or more invoices. class PaymentOrRefund(models.Model): amount = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) invoices = models.ManyToManyField(Invoice, blank=True, related_name="payments") variables in the view are: refund and payment_to_refund When a payment is made, the invoices against which the payment is registered are chosen client-side. When a refund is made, then the PAYMENT against which the refund is to be made is chosen client-side, but the invoices for the REFUND are set on the server side. These invoices need to be assigned from the payment_to_refund. This does not work: refund.invoices = payment_to_refund.invoices nor does this: refund.invoices.all() = payment_to_refund.invoices.all() -
Versioning a REST API in Django where API is generated from model dynamically
I'm building a REST API in Django that will allow me to drill down into related model objects dynamically via the URL. Unfortunately I don't think Django is capable of handling my needs for versioning, here. The goal is to have the information in models.py be the only source of true for what my object relations are and have the code that's processing the URL be super generic (with no specific knowledge as to what my model objects are). For example, assume my models.py has a simple structure like: class Parent(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=64) class Child(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) parent = models.ForeignKey(Parent) name = models.CharField(max_length=64) The is a one-to-many relationship between a parent and children. My REST API takes a url like this: http://tempuri.org/myapp/Parent/{PARENT_ID}/Child and dynamically finds the "Parent" table, and the particular parent, based on the ID. Then looks dynamically for a FK relationship to the table called "Child" and returns all child elements as JSON. Here is the problem. I'd ultimately like to have my API be versioned: http://tempuri.org/myapp/v1/Parent/{PARENT_ID}/Child Where "v1" represents the version of the API, and thus, the version of the model. Database fields may change, be added, removed, etc. and … -
Filter two dates in one query django/python
Is there a way I can filter two datefield columns from a table on the same query? Example: I have date_ots and date_lta I need to filter and get the result from today + 4 days on both columns. Thanks for your attention, Alex -
Django: models intermittently instantiated without reverse lookup fields, FieldDoesNotExist error
I'm running a server with Debian, Apache2, and WSGI to serve an intranet application. There are several models with foreign key relationships. Intermittently, relatively infrequently, an object will be instantiated and will not get the reverse lookup fields for those classes that have a foreign key to the object. It is very intermittent, but it generates a FieldDoesNotExist exception and the user action fails. If they were submitting something to the database, it is lost because of this failure. Very annoying. I have been experiencing this for a couple of years, and anecdotally it seems related to load on the server. Can anybody give me any direction on trying to solve this. When I run the code that fails with the exact same inputs the failure doesn't exist. So, is it just swamp gas in Florida, some heavy radioactive bombardment of gamma rays or is there something that I can investigate in the framework to see why it is failing on occasion? Here are a couple of the tracebacks for the similar errors: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/fast/file/views.py" in upload_file 1035. item_date File "/var/www/fast/file/views.py" … -
Django shuts down intermittenly
I have a django application running on apache2 and mod_wsgi. Recently the server started getting restarted / shut down intermittently without a uniform frequency. Is there a chance that it happens when some specific .py files are accessed? My error log seems to be empty however. -
Django/Django-CMS Session variables with old values
I've got a site in Django/Django-CMS in which I want to save some data from one page to another. I'm saving the data in the session variable: request.session['yb_name'] = request.POST.get('name') The problem is that sometimes my pages get and old value of yb_name instead of the new one. I print the variable in my context processor and the value is the right one but in the template shows me and old one. This doesn't happen every time. Also this happens inside templates from custom plugins I've made. I print it in the template like this: <input type="text" name="name" value="{{ request.session.yb_name|default_if_none:'' }}"> The first thing that I tried was to delete the variable and then create it again the the new value: if request.session.get('yb_name', None): del request.session['yb_name'] request.session.modified = True request.session['yb_name'] = request.POST.get('name') request.session.modified = True But the problem persists. Any ideia what i could be? Thanks :) -
How does Annotate F() on ForeignKey work?
I have a very simple test project with the following models: class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Pizza(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category, related_name='pizzas') def __str__(self): return self.name For test purpose, I created 4 instances of "Pizza", all with the same Category: 'Test Pizza' 'Test' 'Another One' 'Yoplahihou' Here is a simple code and its result: [print(p.id, p) for p in Pizza.objects.all()] 1 Test Pizza 2 Test 3 Another one 4 Yoplahihou Up to this point everything is fine. A simple modification to this code to add an annotate gives: [print(p.id, p, "| test:", p.test) for p in Pizza.objects.annotate(test=F('category'))] 1 Test Pizza | test: 1 2 Test | test: 1 3 Another one | test: 1 4 Yoplahihou | test: 1 Still good, (they all belong to the category with id 1). But where I completely lose it is with the following result: [print(p.id, p, "| test:", p.test) for p in Pizza.objects.annotate(test=F('category__pizzas'))] 1 Test Pizza | test: 1 1 Test Pizza | test: 2 1 Test Pizza | test: 3 1 Test Pizza | test: 4 2 Test | test: 1 2 Test | test: 2 2 Test | test: 3 2 Test | test: … -
Django login AttributeError: 'AnonymousUser' object has no attribute '_meta'
I have this code: from django.contrib.auth import logout, login, authenticate ... if User.objects.filter(email=email).exists(): existing_user = User.objects.get(email=email) user = authenticate(username=existing_user.username, password=existing_user.password) login(request, user) According to the docs, this should work, but it doesn't, it gives me the error: request.session[SESSION_KEY] = user._meta.pk.value_to_string(user) AttributeError: 'AnonymousUser' object has no attribute '_meta' Maybe the problem happens becouse I am using JWT Authentication with Django Rest Framework? It is just an django-powered API, so I guess it is a different scenario, but I don't understand what could be causing the problem. -
Django, form is_valid() is always false
I'm learning Django and have some troubles with forms. I try to create a simple form where I type a name and show it on another page. But is_valid() always returns false. Please, help me to find my error forms.py from django import forms class OrderForm(forms.Form): user=forms.CharField(max_length=100) views.py def order(request): return render(request, 'myapp/order.html', {}) def contact(request): username='not logged' if request.method == 'POST' : form=OrderForm(request.POST) if form.is_valid(): username=form.cleaned_data['username'] else: username='not worked' else: form=OrderForm() return render(request, 'myapp/contacts.html', {'username':username}) order.html <form name = "form" action = "{% url 'contact' %}" method = "POST" > {% csrf_token %} <input type="text" name="username" placeholder="Name"> <button type="submit">Login</button> </form> contacts.html You are : <strong>{{ username }}</strong> -
Django: Passing Array Data to Views with Ajax
I am using ajax to pass an array data to Django (1.10 under Python 3.5) view for further processing. However, I noticed that the passing is not success and results in None. I am wondering what place I have gone wrong and can anyone suggest solution to this. Thanks a lot. Details are as below: Ajax query to pass array final_ele to view as the variable final_ele_view: $.ajax({ url: "../exportNews/", method: "POST", data: { final_ele_view: 'final_ele', csrfmiddlewaretoken: '{{ csrf_token }}' } }); Then in the urls.py: urlpatterns = [ url(r'^admin/exportNews/', views.exportNews), ... Then in views.exportNews: from annoying.decorators import ajax_request @ajax_request @csrf_protect def exportNews(request): arr_tag = request.POST.getlist('final_ele_view[]') return HttpResponse(arr_tag) -
python manage.py system_ckeck command
With the command python manage.py system_ckeck, I got the following [Checking system users] - template_system_users_1 [OK] - template_system_users_2 [OK] - template_system_users_3 [OK] [Checking mail templates] - fr:template_1 [OK] - fr:template_2 [OK] - fr:template_3 [OK] - fr:template_4 [OK] - fr:template_5 [OK] - fr:template_6 [OK] - fr:template_7 [MISSING] - fr:template_8 [OK] template_7 is missing and I don't know how to fix that issue. Could anyone be able to explain to me, roughly, how could I fix that? -
Django: How to include several views/classes in the same url?
I would like to have both a contact form, a newsletter form and a photo slider/portofolio in index.html. Everything drawn into this page only. Am I correct to assume it has something to do With "URL dispatcher" in the documentation? And could someone please help me with some examples on how to point everything to the same URL? Want everything to redirect back to the index when done, after email has been sent, after registering for newsletter and so on. Just to explain better what I actually mean here as I don't have the knowledge to do it in correct terminology. Thanks in advance for all the help I can get. -
How to examine my database in Django
Beginner question. I have done a few Migrations in my project/app, and think I put some test data into my database. What is the quickest way to check my django database at /myproject/db.sqlite3? -
How to limit a view to non logged in user only?
I want to open my login view only to non logged in users. means once user is logged in, he/she can not access login view by hitting /login/ url manually. Thanks in advance :) -
Django - Redirect only after closing the javascript modal manually
I have a comment form in Django, and after submiting the comment, there's this modal popup that displays some text, but it is appearing only for a few seconds until the page redirects. But I want the modal to be there until I manually click on the "cross" button (or anywhere outside of the modal box), and then the page should redirect to the location as specified. views.py: def add_comment_to_project(request,pk): post = get_object_or_404(Project, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('project_detail', pk=pk) //here it redirects. else: form=CommentForm() return render(request, 'portfolio/add_comment_to_project.html', {'form':form}) add_comment_to_project.html: {% extends 'portfolio/base.html' %} {% block content %} <h1>New Comment</h1> <form method="POST" class="project-form"> {% csrf_token %} {{ form.as_p }} <button id="myBtn" type="submit" class="save btn btn-default">Send</button> </form> <!-- the Modal (prompt after clicking the send button) --> <div id="mymodal" class="modal"> <!-- Modal Content --> <div class="modal-content"> <span class="close">&times;</span> <p>Thank you for your response ! :).<br>It has been recorded. It will be displayed once it has been approved by the author.</p> </div> </div> {% endblock %} javascript: // Get the modal var modal = document.getElementById('mymodal'); // Get the button that opens the modal var btn = document.getElementById("myBtn"); // Get … -
Django login doesn't work
I tried to create a login view like the following: def user_login(request): if request.method == 'POST': # use request.post.get('<variable>') as it returns None when it doesn't exist username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect('rango/index.html') else: return HttpResponse('Your Rango account is disabled!') else: print("Invalid login details: {0}, {1}".format(username, password)) return HttpResponse("Invalid login details supplied!") else: return render(request, 'rango/login.html', {}) This seems to be the correct way to do so, but when I try to open the page in my browser, I get the following error: TypeError at /rango/login/ login() missing 1 required positional argument: 'user' Request Method: GET Request URL: http://localhost:8000/rango/login/ Django Version: 1.9.10 Exception Type: TypeError Exception Value: login() missing 1 required positional argument: 'user' Exception Location: C:\Users\Johannes\tangowithdjango\lib\site-packages\django\core\handlers\base.py in get_response, line 147 Python Executable: C:\Users\Johannes\tangowithdjango\Scripts\python.exe Python Version: 3.6.0 Python Path: ['C:\\Users\\Johannes\\tangowithdjango\\tango_with_django_project', 'C:\\Users\\Johannes\\tangowithdjango\\Scripts\\python36.zip', 'C:\\Users\\Johannes\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Johannes\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Johannes\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\Johannes\\tangowithdjango', 'C:\\Users\\Johannes\\tangowithdjango\\lib\\site-packages'] Server time: Thu, 12 Jan 2017 17:56:38 +0100 Has anyone encountered something similar or knows a solution to the problem? I already searched and tried around for a bit but couldn't find an answer. -
Custom Save Method with Mixin: Cannot create a consistent method resolution order (MRO)?
I wrote a mixin to validate users with a custom save method but I keep getting the following error: Getting TypeError: Cannot create a consistent method resolution order (MRO) for bases ValidateUserMixin, Person Is there a way to get this to work? class ValidateUserMixin(object): def save(self, *args, **kwargs): try: self.__class__.objects.get(first_name=self.first_name, last_name=self.last_name, dob=self.dob) except self.__class__.DoesNotExist: super(ValidateUserMixin, self).save(*args, **kwargs) class Person(ValidateUserMixin, models.Model): first_name = models.CharField(max_length=100) middle_name = models.CharField(max_length=100, blank=True, null=True, help_text='Middle name or Middle initial') last_name = models.CharField(max_length=100) suffix = models.CharField(max_length=3, blank=True, null=True) preferred_name = models.CharField(max_length=100, blank=True, null=True) title = models.CharField(max_length=10, blank=True, null=True) sex = models.CharField(max_length=1, default='U', choices=SEX_CHOICES) race = models.CharField(max_length=25, blank=True, null=True) ethnic_origin = models.ForeignKey('EthnicOrigin', blank=True, null=True) dob = models.DateField(verbose_name='Birthday', blank=True, null=True) class Member(ValidateUserMixin,Person): pass -
Django Taggit - AttributeError: can't set attribute
yesterday I installed PostgreSQL as db for the website That I'm developing. After the installation the computer restarted. What's wrong? I lost all the environment variables (i'm using windows 10). So I had to re add python to the path. After That I created the db I replaced the data on settings.py. I run the website but it gave an error. So I installed the psycopg2 to let postgres work with django. No way. I Decided to go back to sqlite3 for the moment, so I edited the settings.py and run the website. the error Told the there was no application named Taggit. (???) It's not normal. I installed it and everything was working fine. I reinstalled it (version 0.17.1). I do not know If These events are connected ... this the reason I tell you everything. now: On every single projects where I use django Taggit I receive the same error (even on the One That I do not open from months) ... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x00000181AA17DAE8> Traceback (most recent call last): File "C:\Python35\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python35\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\Python35\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception … -
Custom creation of permissions in django model
Now I have models.py like this class FileCategory(models.Model): file_type = models.CharField(_('type'), max_length=128) def __unicode__(self): return self.file_type class Doc(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) file_category = models.ForeignKey('FileCategory', null=True) file = models.FileField(upload_to='documents/', null=True, blank=True) class Meta: permissions = (("upload_file", "upload file"), ("delete_file", "delete file"), ("download_file", "download file"), ("access_file", "access file"), ) Now I want to add permissions for every FileCategory table For example If I have filecategory numm, dumm and summ I want to automatically have permissions ("access_file_numm","access_file_summ","access_file_dumm", ) I tried to make a solution like this: permissions = (bla,bla,bla, )+\ ("access_file_%s" (type.__str__() for type in FileCategory.objects.all()), "access %s"(type.__str__() for type in FileCategory.objects.all())) And sure I want to migrate them to the database -
Django streaming media files stuck in Chrome
I'm using this code to serve media files as chunked response. Everything works fine in Firefox but it get stuck everytime after small period of time in Chrome and it refreshes downloading again after like 1 minute. https://i.imgur.com/JpBWbQp.png Live example: http://easyupload.cz/TillYou%27reDead I also tried serving via Nginx but I cannot do that because of issue with 'X-Accel-Redirect' that doesn't allow encoded URLs and since there are special characters like =?' in it I really need encoded URLs. Always ended up with 404 not found. Nginx error without encoding: *23015 open() "/usr/local/nginx/html=" failed (2: No such file or directory) Nginx error with encoding: *22820 open() "/****/****/****/media/****/2016_03_13_21_01_54_Hled%C3%A1n%C3%AD.png" failed (2: No such file or directory) I'm fine with both of solutions, either django serving or nginx serving but cannot make work any of them. import os import urllib from wsgiref.util import FileWrapper from pathlib import Path import datetime import re range_re = re.compile(r'bytes\s*=\s*(\d+)\s*-\s*(\d*)', re.I) class RangeFileWrapper(object): def __init__(self, filelike, blksize=8192, offset=0, length=None): self.filelike = filelike self.filelike.seek(offset, os.SEEK_SET) self.remaining = length self.blksize = blksize def close(self): if hasattr(self.filelike, 'close'): self.filelike.close() def __iter__(self): return self def __next__(self): if self.remaining is None: # If remaining is None, we're reading the entire file. data = self.filelike.read(self.blksize) if … -
django received the post value is not complete
i posted the data to a django view function but the data seem not completion,i had check the data in my chrome browser,it worked,but when i viewed the post data in django ,it not worked! i think the data that i post is filtered by the django. here is the data in my browser: 1$精品红茶$01-12 22:06$1 here is the data received in django view function u'1$精品红茶$01-12' there is any way that i can get the completion data from view function? -
Django join queries from multiple models
Consider following models: class Employee(models.Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) class MonthName(models.Model): name = models.CharField(max_length=128) class Month(models.Model): name = models.ForeignKey(MonthName) year = models.IntegerField() class Group(models.Model): name = models.CharField(max_length=128) class EmployeeGroup(models.Model): employee = models.ForeignKey(Employee) month = models.ForeignKey(Month) group = models.ForeignKey(Group) class Status(models.Model): name = models.CharField(max_length=128) class EmployeeStatus(models.Model): employee = models.ForeignKey(Employee) month = models.ForeignKey(Month) status = models.ForeignKey(Status) I need to display some Employees with particular Status in specified Month. Along with their names i need to display group names they belong to. I could do something like this: statuses = models.EmployeeStatus.objects.filter(month=some_month, status__name="Current") groups = models.EmployeeGroup.objects.filter(month=some_month) But to join these queries (assuming some sorting) i would have to iterate over them. Can i acheive this other way? Looks like there should be model class EmployeeData(): employee = models.ForeignKey(Employee) month = models.ForeignKey(Month) group = models.ForeignKey(Group) status = models.ForeignKey(Status) But redesigning application is the last resort - we have plenty of data already. -
django migrate - not applied
I've a problem right now. I ran python3 migrate and my terminal just stopped. The migration I wanted to apply was '0105_context' i restarted session to server and did : python3 manage.py migrate --list and got : [X] 0104_likes [ ] 0105_context So my migration is saved but not applied . How can i solve it right now? I've tried : python3 manage.py migrate my_proj 0105_context but still anything happens Django 1.9 Thanks