Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django's email library not working on heroku
I am using djangos's send_email function for sending emails to users. Below are my settings. from django.core.mail import send_mail EMAIL_HOST_USER = 'mymail@gmail.com' EMAIL_HOST_PASSWORD='password+' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 This is working fine on local this error env but not on heroku. It is showing: SMTPAuthenticationError -
Django Rest Swagger 2 not parsing Serializer FieldField correctly
Let us say I have the following serializer: class FileUploadSerializer(serializers.Serializer): file = serializers.FileField(max_length=100) My view looks like this: class FileUploadView(generics.CreateGenericAPIView): serializer_class = serializers.FileUploadSerializer parser_classes = (parsers.FileUploadParser,) def post(self, request): # do something here I expected the swagger UI to generate a file upload button that you can click to choose a file from the file system. Instead, I was asked to input a JSON data: In the older version of the Django Swagger, I can just specify the parameter type as file in the YAML docstrings. However, I am using Django Swagger 2+ where YAML docstrings are no longer supported. -
Django celery multiple workers and multiple queues
I have 5 workers named 1-5 and two queues A and B, I need to assign queue A for workers 1 and 2, and 3,4,5 dedicated for B, I need to allocate workers 1 and 2 for the tasks in queue B, when A is empty or 1,2 in idle. I need to configure this in my celery tasks using rabbitmq brocker from django app. Can you specify how to assign queue specific tasks and run workers according to the above logic -
Django Write Authentication Redirect for Blackboxed Route URLs
I'm using a django library called django-dashing that has a predefined set of urls that render a dashboard. I import them like this urlpatterns = [ ... url(r'^dashboard/', include(dashing_router.urls)), ... ] I want the router to be accessible only by administrators, which I can do with some config settings within django-dashing. However, when a non-admin user attempts to access /dashboard/, I want to redirect them to django's /admin/ panel to have them log in, instead of throwing the 403 that django-dashing does. Since the django-dashing views are effectively blackboxed, I was wondering if there was a way to write a 'pre-view' that would intercept the request to /dashboard/, run some code – specifically, doing the appropriate redirects – and then continue onto the actual dashboard. I know this would be easy enough to do by writing two urls, like /dashboard-auth/ which redirects to /dashboard/, but I don't want the user to have to go to one URL to get to another Any suggestions? -
How can I post params to be used as an object in Django
I want to send an ajax Post request to my server with a param to be used like an object: student_name = request.data.get('student_info', {}).get('name') When I send the params like this: student_info: {"name":"Tom", "age": 20} It produce the following error: AttributeError: 'unicode' object has no attribute 'get' The best answer is what I don't need to change my back-end, and solve my problem by sending data properly. Regards, -
What is equivalent Django syntax for SQL query consists of inner join, count, where?
I have a DB which have tables like below: class Maindata(models.Model): index = models.TextField(primary_key=True) dco = models.IntegerField(db_column='DCO', blank=True, null=True) patient = models.IntegerField(db_column='PATIENT', blank=True, null=True) primary = models.IntegerField(db_column='PRIMARY', blank=True, null=True) fsdate = models.TextField(db_column='FSDATE', blank=True, null=True) uhpi = models.TextField(db_column='UHPI', blank=True, null=True) uhpiold = models.TextField(db_column='UHPIold', blank=True, null=True) wghnum = models.TextField(db_column='WGHNUM', blank=True, null=True) idstatus = models.TextField(db_column='IDstatus', blank=True, null=True) fsc2date = models.TextField(db_column='FSC2DATE', blank=True, null=True) iopat = models.TextField(db_column='IOPAT', blank=True, null=True) anndate = models.TextField(db_column='ANNDATE', blank=True, null=True) site = models.ForeignKey('Sitelut', db_column='SITE', to_field='code', blank=True, null=True, related_name='site') and Chemotherapy table: class Chemotherapy(models.Model): index = models.TextField(primary_key=True) patient = models.IntegerField(db_column='PATIENT', blank=True, null=True) primary = models.IntegerField(db_column='PRIMARY', blank=True, null=True) episode = models.IntegerField(db_column='EPISODE', blank=True, null=True) material = models.ForeignKey('Chemomateriallut', db_column='MATERIAL', blank=True, null=True, related_name='material') stdate = models.TextField(db_column='STDATE', blank=True, null=True) enddate = models.TextField(db_column='ENDDATE', blank=True, null=True) method = models.ForeignKey('Chemomethodlut', db_column='METHOD', blank=True, null=True, related_name='method') I'm trying to perform a query which connect the two tables and get some information (below is my query): Select count(*), Chemotherapy.Material, Chemotherapy.METHOD from Chemotherapy inner join Maindata on Chemotherapy.Patient = Maindata.Patient and Chemotherapy.[Primary] = Maindata.[Primary] where ((Maindata.site) = '1749') group by Chemotherapy.MATERIAL, Chemotherapy.METHOD Initially, I used filter and annotate. But then, I realise that it doesn't return the same result (as I don't check whether it has the same primary id). My initial syntax is … -
Wagtail Admin Add Page Returns 404 in Docker Container
When running outside of Docker; everything operates as expected. However, when running inside a container; some Wagtail admin pages return 404. These admin pages all work (ie return 200) when inside a Docker container: http://localhost:8000/admin http://localhost:8000/admin/pages/ http://localhost:8000/admin/pages/2/add_subpage/ I have a number of page types that all work outside of Docker. However, when inside a container; I get a 404 when I try to create a page. When I try to create a page, for example a page called standardpage, it routes to http://localhost:8000/admin/pages/add/app/standardpage/2/ and it throws a 404. This happens for all URL's prefixed with http://localhost:8000/admin/pages/add/ and only when inside a container. version: '2.1' services: nginx: image: nginx:latest container_name: papusa_nginx ports: - "8000:8000" volumes: - ./nginx:/etc/nginx/conf.d - ./static:/static depends_on: - web web: build: . image: karimtabet/papusa container_name: papusa_web depends_on: postgres: condition: service_healthy redis: condition: service_started links: - "postgres:db" expose: - "8000" environment: - SECRET_KEY='stagingkey' - DB_URL=postgres://papusa:papusa@db:5432/papusa - REDIS_URL=redis://redis:6379/1 postgres: image: postgres:latest container_name: papusa_db environment: - POSTGRES_USER=papusa healthcheck: test: ["CMD-SHELL", "psql -h 'localhost' -U 'postgres' -c '\\l'"] interval: 30s timeout: 30s retries: 3 redis: image: redis:latest container_name: papusa_redis And this is the nginx conf that is being used: upstream web { ip_hash; server web:8000; } # portal server { location / … -
FieldError: Unknown field(s) (created_at, modified_at) specified for Account
I am trying to create a timestamp for my model Account, but I don't want my two time stamps (created_at and modified_at) to be editable or even viewable by the user. Everything works fine and as expected until I add editable=False to the created_at and modified_at fields. Here is my model: class Account(models.Model): account_name = models.CharField(max_length=25) active = models.BooleanField(default=True) created_at = models.DateTimeField(null=True, blank=True, editable=False) modified_at = models.DateTimeField(null=True, blank=True, editable=False) def save(self): if self.id: self.modified_at = datetime.datetime.now() else: self.created_at = datetime.datetime.now() super(Account, self).save() class Meta: ordering = ('id',) Here is the obscure error I get when I try to do anything (migrate, runserver, etc): django.core.exception.FieldError: Unknown field(s) (created_at, modified_at) specified for Account As soon as I remove editable=False from both fields, everything works fine. Is this a Django bug? Is there a better way to make the field non-viewable and non-editable by the user? I am using Django 1.9 and Python 3.6.1. Thanks for the help, let me know if you need me to post anything else (views, serializers, etc). Full traceback: https://pastebin.com/JXDEpfUE -
Reverse for 'edit_user' with arguments '(2L,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I have an app named mylibrary where a user can add books. So I'm registering and logged in user and redirect them to index page. Here is what it looks like: mylibrary You can see the drop down menu there's an option, My Profile. This is being generated from base.html. Here's the piece of code I was using: <ul class="dropdown-menu" aria-labelledby="dropdownMenuDivider"> <li><a>Signed in as <br/>{{ user.username }}</a></li> <li><a href="{% url 'mylibrary:edit_user' user.id %}">My profile</a></li> <li><a href="{% url 'mylibrary:index' %}">My Library</a></li> <li><a href="#">Help</a></li> <li role="separator" class="divider"></li> <li><a href="{% url 'mylibrary:logout_user' %}">Sign out</a></li> </ul> This part generates the dropdown menus. So in this part : <li><a href="{% url 'mylibrary:edit_user' user.id %}">My profile</a></li> I'm taking the user id to sort out which user is currently logged in and trying to update his profile. This is in the view class to edit the profile: @login_required def edit_user(request, pk): user = User.objects.get(pk=pk) user_form = UserProfileForm(instance=user) ProfileInlineFormset = inlineformset_factory(User, UserProfile, fields=('address', 'sex', 'phone', 'city', 'bio')) formset = ProfileInlineFormset(instance=user) if request.user.is_authenticated() and request.user.id == user.id: if request.method == "POST": user_form = UserProfileForm(request.POST, request.FILES, instance=user) formset = ProfileInlineFormset(request.POST, request.FILES, instance=user) if user_form.is_valid(): created_user = user_form.save(commit=False) formset = ProfileInlineFormset(request.POST, request.FILES, instance=created_user) if formset.is_valid(): created_user.save() formset.save() return HttpResponseRedirect('/mylibrary/edit_user/') return render(request, … -
Printing Time spent on a view in Django
I have a simple django view which just reads the request and prints it out into the console. Now along with the request body I need to get the start time of the view for a particular session and if after the session has been terminated or there is no request incoming for that particular view for about 1 min, I need to print out a custom string "Device Stopped". Can anyone please help me out to solve this issue. -
Django: How to add notification system to django disqus infrastructure ?
I am new to Django and Recently i have integrated disqus commenting system to my Django Blog Application and now i want to develop notification infrastructure. I need two features : 1) Whenever a user comments , admin should be notified 2) Whenever user replies some comment, the commented user should get notification For comments i have used disqus so i don't have any model/table created. So how can i send notifications, can anyone please help me. how can i achieve this ? Correct me if i m following wrong method. -
For what 'add' or 'create' permission on object (row) level exist
I am using django-guardian, but this shouldn't be of much importance for the question, because it is general for backend permission modelling. I am wondering why 'add' or 'create' permissions exist on object (row) level? How can I check object permissions for something, I am just creating, which doesn't already exist? Are there any special cases, which I didn't consider maybe? Thanks in advance -
How to describe multipart/form-data in apiary blueprint?
So, I'm trying to describe Django Rest Framework's api method that accepts image in Apiary. Here's code that works: path_to_image = '/home/zub3r/Downloads/test_images/2.jpg' data = { 'userpic': open(path_to_image, 'rb') } response = requests.put('http://localhost:8000/', data={"webpage": "http://eastpole.pro"}, files=data, headers={"Authorization": "Token ed23ec44fc004173000d9b755d87f1972bf425ad"}) print response.content How to desccribe it in apiary? -
Change backend authenficiation just for a view and an app
I would like to change the authentification backend just for the view in my api app in django ... For the moment it's working but i have this warning : You have multiple authentication backends configured and therefore must provide the `backend` argument or set the `backend` attribute on the user. How to specify just one auth back just for this view ? My version of django is 1.10.3 thanks and regards -
Django FilteredSelectMultiple
I have a problem trying to use the django FilteredSelectMultiple with forms. When I use this in admin with a model that I try to register everything works as expected, but when I try to create a view and use the FilteredSelectMultiple inside a form something weird happens. The form is rendered as I want, but the choices I make are not saved on the right side of the select field, like this: http://imgur.com/a/1GG9V. The data is saved in the database but everytime I enter this view again, the data is all in the left side of the selected box. Here is the code I am using: distribuidores=forms.ModelMultipleChoiceField(queryset=User.objects.filter(groups__name="distribuidores"), required=True,widget=FilteredSelectMultiple("Distribuidores",is_stacked=False)) class Media: css = {'all': ('/static/admin/css/widgets.css',),} js = ('/admin/jsi18n/',) -
Django - Is it possible to show loader until a start page is loaded?
My view function takes a long time until returning a template. So, I'd like to show something to a user while running the function. Is it possible to show loader until a start page is loaded? What's important is the loader should be shown when loading the first page after first visit of a user? Thank you for reading my question. -
How to add new created page url to modified django-oscar
I'm begginer in django-oscar and i try to manage new view on page. I've already created two pages with django-oscar dashboard, https://ibb.co/cM9r0v and make new buttons in the templates: Lib/site-packages/oscar/templates/oscar/partials/nav_primary.html https://gist.github.com/Kalinar/076fc8144869c3b50fc0bc9e52f825e4 I have no idea how to make a good a href="???" to that new pages on buttons ... can someone help? Maybe there is better way to do it and you can explain it for me ? -
Regex not matching fr or en
I need a regex to match patterns like: /page/my-slug/ /a-langage-acronyme/page/my-slug/ and to not match patterns like: /fr/page/my-slug/ /en/page/my-slug/ I tried: r'^(?!(fr/|en/))page/(?P<slug>[\w-]+)/' But it doesn't even match: /de/page/my-slug/ -
Flask assets in Django: static files
I have a problem with assets on Django. What am I missing? There are all static files in 'static/css'. App is working on local Docker. When I try to modify one of css files and rebuild container, new version of packed_css is not packing. At a result packed.css is contain old version, and during building container data isn't update. The base page contain: {% assets "packed_css" %} <link href="{{ ASSET_URL}}" media="screen" rel="stylesheet" /> {% endassets %} And {% assets "packed_js" %} <script type="text/javascript" src="{{ ASSET_URL }}"></script> {% endassets %} My assets.py: from flask_assets import Environment, Bundle from config import app bundles = { 'packed_js': Bundle( 'js/01.js', 'js/02.js', 'js/03.js', filters='jsmin', output='gen/packed.js'), 'packed_css': Bundle( 'css/01.css', 'css/01.css', 'css/01.css', filters='cssmin', output='gen/packed.css') } assets = Environment(app) assets.register(bundles) Thanks for your help! -
How to run a django project?
I have just downloaded some Django samples from Github, but I cannot find "manage.py" in them so I could run the server. does anyone have any idea about how to run this kind of projects? PLEASE .. -
how to itterate through auth_user table in django?
I have a model named cms_user which has an auth_user id as foreign key.So i want to iterate through cms_user model using request.user. cms_user model:- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from cms.models.masterCmsUserTypes import MasterCmsUserTypes class CmsUser(models.Model): userId = models.ForeignKey(User,db_column='userId') userTypeId = models.ForeignKey(MasterCmsUserTypes,db_column='userTypeId') status = models.BooleanField(db_column="status", default=False, help_text="") isDelete = models.BooleanField(db_column="isDelete", default=False, help_text="") createdAt = models.DateTimeField(db_column='createdAt', auto_now=True, help_text="") modifiedAt = models.DateTimeField(db_column='modifiedAt', auto_now=True, help_text="") idv2 = models.IntegerField(db_column='idV2') class Meta: managed = False db_table = 'cms_user' i want to itterate to cms_user using request.user -
How to get the Azure Webapp App Settings from Django
Azure Webapp has some variables in App-settings which can be found in the portal as the following image: Question: How can I get these values in my Django code? -
ImportError: No module named 'django.contrib.gis.django'
im using postgres database for geodjango. i have installed all required libraries... gdal,geos,proj4,postgis im using virtualenv too im getting that Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0x7f0f3808cae8> Traceback (most recent call last): File "/home/nandu/PycharmProjects/nimkraft- master/env/lib/python3.5/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/nandu/PycharmProjects/nimkraft- master/env/lib/python3.5/site- packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/home/nandu/PycharmProjects/nimkraft- master/env/lib/python3.5/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "/home/nandu/PycharmProjects/nimkraft- raise value.with_traceback(tb) File "/home/nandu/PycharmProjects/nimkraft- master/env/lib/python3.5/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/nandu/PycharmProjects/nimkraft- master/env/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/nandu/PycharmProjects/nimkraft- master/env/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/nandu/PycharmProjects/nimkraft- master/env/lib/python3.5/site-packages/django/apps/config.py", line 120, in create mod = import_module(mod_path) File "/home/nandu/PycharmProjects/nimkraft- master/env/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'django.contrib.gis.django' while including postgis in settings only error occurs or else it works well with postgresql database -
using django variable in JavaScript
I was wondering how to include django variable in JavaScript file. I created two models Category and song , I linked song to category with foreign key. I was trying to write a code in JavaScript so that when a category is selected ,all the songs in the category will be displayed -
Order queryset by related M2M fields Django
I'm trying to order a QuerySet by the field of three related intermediary models. Let me simplify my current scenario, let's assume I have these models. class User(AbstractUser): phone = models.CharField(max_length=20, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) address = models.CharField(max_length=150, blank=True, null=True) about_me = models.CharField(max_length=200, blank=True, null=True) class School(models.Model): created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) name = models.CharField(max_length=50, verbose_name=_(u'Name')) email = models.EmailField(blank=True, verbose_name=_(u'Email')) phone = models.CharField(max_length=15, blank=True, verbose_name=_(u'Phone')) admins = models.ManyToManyField(User, verbose_name=_(u'Administrators'), through='SchoolAdmins', related_name='school_administered') assistants = models.ManyToManyField(User, verbose_name=_(u'Assistants'), through='SchoolAssistants', related_name='school_assisted') instructors = models.ManyToManyField(User, verbose_name=_(u'Instructors'), through='SchoolInstructors', related_name='school_instructed') class SchoolAdmins(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) school = models.ForeignKey(School) order = models.PositiveSmallIntegerField(default=0, verbose_name=_(u'Staff ordering number')) class SchoolAssistants(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) school = models.ForeignKey(School) order = models.PositiveSmallIntegerField(default=0, verbose_name=_(u'Staff ordering number')) class SchoolInstructors(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) school = models.ForeignKey(School) order = models.PositiveSmallIntegerField(default=0, verbose_name=_(u'Staff ordering number')) Notice the order field in the intermediary models SchoolAdmins, SchoolInstructors and SchoolAssistants, it is used to denote the view ordering level when rendering users in a template, thus, the order specied is important (although it can be None, zero or even duplicated) That said, I need to return a QuerySet that is ordered by the order field of the intermediary models. Getting the users is easy: qs = User.objects.filter(Q(schoolassistants__school__id=school_id) | Q(schooladmins__school__id=school_id) …