Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
django tastypie readonly based on group
I have read a lot of questions and answers on here, so I do question if what I'm trying to do is the wrong thing. I have a django app (1.8.1) I have had to take over as the creator has moved on and not left any documentation or comments in the code. In most respects it would probably be quicker for me to rewrite it in node as I don't have much experience with django. Current situation is: The way the app is currently configured that if you have been added to the app you are added to staff. This means anyone can change data on the app. (front end not admin page) I need to change this so only a group of people can make data changes(via front end) but those added to a different group can only get/see data in the front end form. From what I have seen the API are being done through tastypie(0.13.3). I would have assumed django had a view/readonly/get class but it looks like I have to create it. My question is am I better off doing this in tastypie or django? What is the simplest way to do it? Or is … -
Django gmail SMTP Connection unexpectedly closed
My problem is that i have configured my django project to send emails via gmail SMTP and it worked flawlessly for the past 3-4 month until today. Today it have just started showing me "SMTPServerDisconnected. Connection unexpectedly closed" and i cant make my mind what's the problem. In my settings i have: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'user@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 In gmail "less secure apps" option is enabled. I haven't dont any updates, any password changes, any changes at all... At it just have stopped working today, out of a sudden :/ Any help would be very appreciated. -
Django csrf verification failed. request aborted. csrf token missing or incorrect while having everything in place
i have a html page (done with WYSIWYG), on this page i have a form as big as the page (because i have alot of values i want to be able to send back to my view so i can add the value in the template). So far everything is working, i'm able to send back my values to my view and add them to the datatabase. On this page i also have two combobox, and the goal is that once the first one has a selected value, the value get sent back to the view so i can generate the data that goes inside the second combobox. The problem is that for this operation, i only get the message Django csrf verification failed. request aborted. csrf token missing or incorrect Middleware Settings : MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Template : <form id="frm" method="post" enctype="text/plain">{% csrf_token %} <select name="typeMvmt" size="1" id="typeMvmt" onchange="document.getElementById('ebIdTypeMVT').value = document.getElementById('typeMvmt').value;veriftype();displayProduit();check();send_post();return false;" style="position:absolute;left:220px;top:5px;width:350px;height:28px;z-index:257;"> <option value="0">-- SELECTIONNER UN TYPE DE MOUVEMENT --</option> {% for typemouvement in typemouvements %} <option value={{typemouvement.id}}>{{typemouvement.libelle}}</option> {% endfor %} </select> </form> View : def mouvementCreation(request): idMI = 0 especes = TbEspece.objects.order_by('id') typemouvements = TbTypeMouvement.objects.all() #Get Mouvement informations #Connection … -
django - filtering objects across multiple templates?
I'm trying to filter objects across two templates. One (the parent) should display the five most recently updated, and the other should display them all. I have the latter working perfectly with the following code: Views.py: ... class ChannelProjectList(generic.ListView): context_object_name = 'projects_by_channel' template_name = 'channels/projects_by_channel.html' def get_queryset(self): self.channel = get_object_or_404(Channel, slug=self.kwargs['slug']) return Project.objects.filter(channel=self.channel) ... HTML: {% for project in projects_by_channel %} {{project.name}} {% endfor %} but when I go to "include" it on the parent page it breaks. After some research I understand why that is happening and why that isnt the proper way to do it. I dug around and found this, which seems to be exactly what I'm trying to do but when I implemented it, not only did it not work it but also broke the page that is working. This feels like a pretty simple thing, but where its my first project I'm running into new things every day and this is one of them. -
CSV File import not working django
Iam trying to import csv file to postgresql using Django postgres-copy and converted the file to 'utf-8' format. tabl_name.objects.from_csv(pathFile, dict(var1='Header1',var2='Header2') but getting error like ValueError: Header 'Header1' not found in CSV file.