Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to filter Haystack SearchQuerySet by boolean field
I've got a view which renders objects to a table via Knockout, powered by a haystack search index which looks like this; class ResultsIndex(indexes.SearchIndex, indexes.Indexable): """ Results indexes for elasticsearch engine """ text = indexes.CharField( document=True, use_template=True ) owner = indexes.IntegerField( model_attr='owner_id', null=True ) category_year = indexes.IntegerField( model_attr='category_year_id', null=True ) event = indexes.CharField( model_attr='category_year__category__event__title' ) category = indexes.CharField( model_attr='category_year__category__name', null=True ) year = indexes.CharField( model_attr='category_year__year__year' ) cannot_claim = indexes.BooleanField( model_attr='category_year__category__cannot_claim', null=True ) def get_model(self): """ Model for the index """ return Results The SearchView attempts to filter this index so that the Result objects where cannot_claim is True aren't shown; class ClaimableResultsListView(SearchView): """ Results list view. """ form_class = ResultsSearchForm template_name = 'results/list.html' http_method_names = ['get'] ordering = ('event', 'category', '-year', 'place') def get_queryset(self): """ Get results """ queryset = super(ClaimableResultsListView, self).get_queryset() queryset.models(Results).exclude(cannot_claim=True) return queryset However the above queryset still contains all objects regardless of the cannot_claim value. I've also tried to do queryset.models(Results).filter(cannot_claim=False) but neither filter the paginated objects. In the javascript before the objects are passed to KO I do a final check to ensure that cannot_claim is False, which at the moment means whole pages of the list may not render because it's not being filtered on. -
How to write backends authentication for product table in django
As i am trying to add backend authentication for this model. can someone suggest how to add to this. models.py class Product(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) type = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2, default="") image = models.ImageField(upload_to='image/product/', blank="True") -
order_create() takes exactly 2 arguments (1 given)
I was trying to do a celery task, the code as follows. task.py from .models import OrderItem from cart.cart import Cart from .forms import OrderCreateForm @task(name="create_order") def create_order(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: try: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) except: pass cart.clear() return None else: form = OrderCreateForm() return None views.py from .models import OrderItem, Order from cart.cart import Cart from .tasks import create_order def order_create(request, order_id): order = Order.objects.get(id=order_id) cart = Cart(request) create_order.delay(order.id) return render(request,'orders/order_created.html', {'cart': cart, 'order': order}) urls.py from .views import order_create urlpatterns = [ url(r'^create/$',order_create, name='order_create'), ] When executing the code I am getting the error 'order_create() takes exactly 2 arguments (1 given)'. Hope somebody can help me to solve it. Thank you. -
Template Block Django run after pageload
I want to include/load/run some html on template only when the page is already loaded, without use another request using Ajax. Exemple: {% block_postpone %} load everything that is inside of this block after the page loaded, and everything that is outside load immediately{% endblock_postpone %} I thinking that I need to change the process code of the template. -
Poor performance using Django Q queries.
I'm seeing quite unexpected performance when using the Q object for queries in Django. Here's an example of the issue. I have a piece of code, which uses union and distinct. import time from webapp.models import MessageRecipient from django.db.models import Q id = ... time.time() MessageRecipient.objects.filter( recipient__pk=id ).union( MessageRecipient.objects.filter( content__sender__pk=id ) ).distinct() time.time() The two times printed are: 1509466150.170969 1509466150.43806 Aka. The query returns within 300 milliseconds. Now if I rewrite the query to use Q, I get the following: time.time() MessageRecipient.objects.filter( Q(recipient__pk=id) | Q(content__sender__pk=id) ) time.time() The two times printed are: 1509466165.580193 1509466187.030747 Aka. The query now takes almost 20 seconds. The database is a postgresql, and there's about one million entries in each table. The question isn't with regards to the specific code, but rather why the Q object has so poor performance? -
How to manually clear/update a cached view in django
My goal is to cache a view until an event occurs where the view's cache would need to expire, otherwise cache for 1 hour. This is what I have in urls.py url(r'^get_some_stuff/$', cache_page(60 * 60, key_prefix='get_some_stuff')(views.StuffView.as_view())), And this works fine. Now I'm trying to fetch the cached view to verify that there's something there and I tried this: from django.core.cache import cache cache.get('get_some_stuff') But this returns None. I was hoping to do something like this: from django.core.cache import cache #relevant event happened cache.delete('get_some_stuff') What's the right way to handle cache? -
How to apply windowing function before filter in Django
I have these models: class Customer(models.Model): .... class Job(models.Model): customer = models.ForeignKey('Customer') payment_status = models.ForeignKey('PaymentStatus') cleaner = models.ForeignKey(settings.AUTH_USER_MODEL,...) class PaymentStatus(models.Model): is_owing = models.NullBooleanField() I need to find out, for each job, how many total owed jobs the parent customer has, but only display those jobs belonging to the current user. The queryset should be something like this: user = self.request.user queryset = Job.objects.select_related('customer' ).filter(payment_status__is_owing=True).annotate( num_owings=RawSQL('count(jobs_job.id) over (partition by customer_id)', ()) ).filter(cleaner=user) I am using 'select_related' to display fields from the customer related to the job. Firstly I haven't found a way to do this without the windowing function/raw SQL. Secondly, regardless of where I place the .filter(window_cleaner=user) (before or afer the annotate()), the final result is always to exclude the jobs that do not belong to the current user in the total count. I need to exclude the jobs from displaying, but not from the count in the windowing function. I could do the whole thing as raw SQL, but I was hoping there was a nicer way of doing it in Django. Thanks! -
Adding Multi-tenancy to Django Viewflow App
I am creating a Django Viewflow application and I am trying to add multi-tenancy to it but I am not sure how to go about it. I am building the application on Django with MySQL (I cannot move from MySQL). The django-multitenant package provides a means to do this by using passing the tenant model to each of my custom models, i.e. class Products(TenantModel): .... Is there a way to configure Django Viewflow to do the same? Thanks for any help. -
Django: creating an empty file in views.py
I want to create a new file with the same name as the object I am creating. I want to create a new "structure object" with the name str in the database and at the same time a new file called str in the designated uploading folder. When I do that I get an AttributeError of 'file' object has no attribute '_committed' Here are my codes: views.py: def create(request): print request.POST filename = request.POST['name'] f = open(filename, "w") structure = Structure(name=request.POST['name'], file=f) structure.save() return redirect('/structures') models.py: class Structure(models.Model): name = models.CharField(max_length=120) file = models.FileField(upload_to='structures') created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.name urls.py: url(r'^create$', views.create), template: <div class="col-md-12"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Créer une nouvelle structure</h3> </div> <div class="panel-body"> <form class="form-horizontal" action="/create", method="post"> {% csrf_token %} <fieldset> <div class="form-group"> <label for="name" class="col-lg-6 control-label">Nom de la structure</label> <div class="col-lg-6"> <input type="text" name="name" id="name"> </div> </div> <div class="form-group"> <div class="col-lg-10 col-lg-offset-2" align="center"> <button type="submit" value="Create" class="btn btn-primary">Créer</button> </div> </div> </fieldset> </form> </div> </div> </div> The code was working just fine until I added the file creating lines in the views.py And this is a screenshot of the error I am getting: Edit: I didn't … -
Is Django built-in authentication design for managing product's users?
Is is safe to use Django's built-in auth to manage product's users? Or should implement my own solution, or use a 3rd party one? -
Docker compose for production and development
So I use Python+Django (but it does not really matter for this question) When I write my code I simply run ./manage.py runserver which does the webserver, static files, automatic reload, etc. and and to put it on production I use series of commands like ./manage.py collectstatic ./manage.py migrate uwsgi --http 127.0.0.1:8000 -w wsgi --processes=4 also I have few other services like postgres, redis (which are common for both production and dev) So I'm trying to adapt here docker(+ -compose) and I cannot understand how to split prod/dev with it. basically in docker-compose.yml you define your services and images - but in my case image in production should run one CMD and in dev another.. what are the best practices to achieve that ? -
How to override Django Allauth password reset url
I am using an angular frontend with django-rest-auth. How do I override the password_reset_rul in the email message to an url of my choice ( the url to the frontend of the app). {% load i18n %}{% blocktrans with site_name=current_site.namesite_domain=current_site.domain %}Hello from {{ site_name }}! You're receiving this e-mail because you or someone else has requested a password for your user account at {{ site_domain }}. It can be safely ignored if you did not request a password reset. Click the link below to reset your password.{% endblocktrans %} {{ password_reset_url }} {% if username %}{% blocktrans %}In case you forgot, your username is {{ username }}.{% endblocktrans %} {% endif %}{% blocktrans with site_name=current_site.name site_domain=current_site.domain %}Thank you for using {{ site_name }}! {{ site_domain }}{% endblocktrans %} Most of the answers I found didn't work or were not clear enough including an issue on this found on the project's github issues. This question seemed right but didn't work for me, I'm thinking there should be a cleaner way to do that. -
pull-right in bootstrap3 didn't work
"pull-right" class in bootstrap 3 didn't work in django templatepull-right here is my code {% block content %} <div class="row"> <div class="col-sm-4 pull-right"> <h1>{{ title }}</h1> <form method="POST" action=""> {% csrf_token %} {{ form|crispy }} <input class="btn btn-primary" type="submit" value="Sign Up!"> </form> </div> </div> {% endblock content %} -
How can I edit the NGINX configuration on Google App Engine flexible environment?
How can I edit the Google App Engine NGINX configuration? There doesn't seem to be much support in the Google docs in regards to the NGINX configuration for apps running in the Google App Engine flexible environment. My app is running fine, but I get this 413 error when I try and upload an audio file (.wav or .mp3). 413 Request Entity Too Large -- nginx My app is running Django (python 3), with Cloud Postgres SQL and Cloud Storage enabled. I researched the error, and it seems I can set a nginx.config file so that it includes "client_max_body_size 80M" - but like I said, there is no documentation regarding how to manually config NGINX on deploy. Any suggestions? -
Using the URLconf defined in SchoolnSkill.urls, Django tried these URL patterns, in this order:
Ok, this is a very common problem that Django people face, and there are a couple of articles already available on the internet,but none of them helps me. I do understand that I need to create my own URLPatterns in my "apps/url", and which I have created one. Below is the URLPatterns from my project"schoolnskill/url": from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^user_info/', include('user_info.urls', namespace='user_info')), ] Below is the url patterns from my apps user_info/url from django.conf.urls import url from . import views urlpatterns = [ url(r'^user_info/index/$', views.IndexView.as_view(), name='index'), url(r'^user_info/register/$', views.RegisterView.as_view(), name='sign_up'), url(r'^register/$', views.UserFormView.as_view(), name='register'), ] I am getting error for "user_info/index" even though I have added it in my URL Patterns. Below is the whole error stack: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/user_info/index/ Using the URLconf defined in SchoolnSkill.urls, Django tried these URL patterns, in this order: ^admin/ ^user_info/ ^user_info/index/$ [name='index'] ^user_info/ ^user_info/register/$ [name='sign_up'] ^user_info/ ^register/$ [name='register'] The current path, user_info/index/, didn't match any of these My Python environment details: Python - 3.6 Django - 1.11.3 IDE - Spyder 3.2.4 -
django not showing post for non super users
so i am creating a blog and every thing was working fine until i logged in as normal user. no error is raised but the problem is that the post_body and title and every thing in the template are disappeared even when i inspect my code in the browser, the strange thing that the comment form is showing? the template: {% extends 'base.html' %} {% block extra_head %} {% load static %} {% load blog_tags %} <link rel="stylesheet" type="text/css" href="{% static 'highlight.js/styles/gruvbox-dark.css' %}"> <script src="{% static 'highlight.js/highlight.pack.js' %}"></script> <script>hljs.initHighlightingOnLoad();</script> {% endblock %} {% block body %} <style> @font-face { font-family: 'post_title' ; src: url('{% static 'FFF_Tusj.ttf'%}') format('truetype'); } #like:hover{ cursor: default; } </style> <style> blockquote { background: #f9f9f9; border-left: 10px solid #ccc; margin: 1.5em 10px; font-family: fantasy; font-size: large; } blockquote p { display: inline; } .post-header{ text-align: center; font-family: Times } .post-body{ font-size: large; } </style> <!-- ajax--> {% if not Post|like:request %} <script> $(document).ready(function() { $("#like").click(function(event){ $.ajax({ type:"POST", url:"{% url 'like' Post.id %}", success: function(data){ i = true; if (i){ var f = document.getElementById('likes'); f.innerHTML = ""; f.innerHTML = {{ Post.votes }} + 1; i = false } } }); return false; }); }); {% endif %} <div … -
Django Oracle Set DB connection password from app
I have 2 databases like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle' , 'NAME': 'hostname:port/SID' , 'USER': 'user' , 'PASSWORD': 'user' }, 'MainDb':{ 'ENGINE': 'django.db.backends.oracle' , 'NAME': 'hostname:port/SID' , 'USER': 'user' , 'PASSWORD': !!! here I want to set this from myApp !!! }, } And I want to connect to the 'MainDb' only after the user enters a correct password. Is there any way to do this? Thanks -
Where to store payment gateway secret key when using python Django with apache server hosted on aws ec2 Ubuntu
Where to store payment gateway secret key when using python Django with apache server? I don't what to store in settings.py as i will checking this file in my git. Can i do it the same way amazon store AWS ec2 keys. If possible how to do it. -
Heroku, Python, Django - Heroku command line not working anymore
I have a Django project that I have deployed on a heroku web server and use PyCharm as my IDE. I used to be able to interact with my web server with "heroku run bash", however, now when I try running "heroku run bash" I get: ▸ stat /.local/share/heroku/client/bin/heroku: not a directory ▸ fork/exec /.local/share/heroku/client/bin/heroku: not a directory I'm not sure what has changed, but I can't seem to connect to my heroku webserver anymore. I can still push changes using git push heroku master, but any other interaction with my heroku server doesn't seem to work anymore. How do I reconnect to my heroku web server again? Thanks in advance for your help! -
Django Request Object in middleware?
I'm constructing a custom Prometheus middleware class to do some monitoring and I'd like to either construct or retrieve the Django Request Framework HttpRequest object for a given request in middleware so that I can capture request.version in my metrics. However, the request parameter in my code below appears to be a WSGIRequest object. Is it possible to discern the DRF HttpRequest object within middleware? Code Below... if django.VERSION >= (1, 10, 0): from django.utils.deprecation import MiddlewareMixin else: MiddlewareMixin = object class CustomPrometheusAfterMiddleware(MiddlewareMixin): def process_response(self, request, response): # Do some cool things return response -
Django Template extensions
Probably a super easy thing to tackle but I have a template for a web page and that template has some common CSS that is linked at the surface. <html> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/index.css' %}"> .... *navbar code in body {%block content%}{%endblock%} </html> for any extending html pages they will have this layout plus some other personalized css. How can I add more custom CSS from a static folder without overriding the current CSS? {% extends "template.html" %} {% load static %} ?Insert custom css for the specific page? {% block content %} *CONTENT* {%blockend%} -
Default value Django admin
I have next code in models: class Color(models.Model): color = models.CharField(max_length=50, verbose_name='Color', default='', blank=True, null=True) class ColorSet(models.Model): color_set = models.ManyToManyField(Color) class Product(models.Model): color_set = models.ForeignKey(ColorSet, verbose_name='Set of color') I need to make sure the administrator can choose the default value in admin panel. He must to choose value from list that he choosed in Many2Many field. How can i do it? -
Length of Django queryset result changes when coerced to a list
I have a reasonably complex queryset thus, which rolls up data by isoweek: >>> MyThing.objects.all().count() 30000 >>> qs = MyThing.objects.all().order_by('date').annotate( dw=DateWeek('date'), # uses WEEK function dy=ExtractYear('date') ).values( 'dy','dw','group_id' ).annotate( sum_count=Sum('count') ).values_list('dw', 'dy', 'group_id', 'sum_count') >>> qs.count() 2000 So far so good. The problem is when I coerce this queryset into a list: >>> len(list(qs)) 30000 Why is this happening? How can I get the list of grouped values that the queryset purports to have when I count() it directly? -
Django Many-to-many limiting choices on a formset so forced removal of inactive?
The requirement is a many-to-many relationship between users and projects. Both User and Project model have an is_active attribute. There is an inline formset when editing the User and Project with an updateview. The many-to-many field is controlled through an intermediate table. On User model: projects = models.ManyToManyField( Project, through=ProjectMembership ) On Project model: users = models.ManyToManyField( settings.AUTH_USER_MODEL, through='ProjectMembership' ) On ProjectMembership intermediate model I am setting the limit_choices_to: user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, limit_choices_to={'is_active': True}, ) project = models.ForeignKey( Project, on_delete=models.PROTECT, limit_choices_to={'is_active': True}, ) On the formset a user can only be assigned to a new project and the same the other way around. The problem comes in with existing project that were made inactive. So you can save active projects to a user: But when you change the is_active status of Stackoverflow Answering to False: And then when you try to save it forces you to delete the row: Ideally I want inactive project to be disabled or not visible at all. Which would mean overriding the get_initial_data or initial queryset. Also they wouldn't be validated with the clean method. How can I specifically fix this? -
ImportError: cannot import name RemovedInDjango19Warning after Django upgrade
I was using Django 1.8 and I wanted to upgrade to the latest version (1.11.6). When I did that I got this error message when trying to run the development server: from django.utils.deprecation import RemovedInDjango19Warning ImportError: cannot import name RemovedInDjango19Warning I can uninstall django and run pip install django=1.9 but I want to keep the latest version. Any tip of how to solve that? Thanks! PS: I'm running python 2.7.13