Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django Connection With Cassandra
Created default Superuser Role cassandra Socket.gaierror: [Errno 11004] getaddrininfofailed Even after the superuser has been created the above error pop up while running the command python manage.py sync_cassandra -
how to deploy a Django app in AWS EC2?
I have an app API build using django rest framework. Now I use manage.py runserver to run it. What is the best way to deploy this app in my ec2 server? -
django project urls.py syntax error
I have downloaded a django project and run ./manage.py runserver. And the code generate following error url(f'{API_PREFIX}/', include('rest_framework.urls', namespace='api')), ^ SyntaxError: invalid syntax urls.py is like this. API_PREFIX = r'^v(?P<version>[0-9]+\.[0-9]+)' urlpatterns = [ ... url(f'{API_PREFIX}/', include('rest_framework.urls', namespace='api')), ... ] I am new to django and please help me how to fix it. -
Order of Django Data Migrations
I am using the sites application (django.contrib.sites) in my application. I have created a data migration which sets the values of the current site when the database is created, however my data migration is being executed before the sites application is installed. How can I force my data migrations to be executed after the sites migrations. This project is intended to be a seed to be used for other projects, and I often delete the database and start fresh so it is important that the initial makemigrations/migrate commands work out of the box. My migrations file exists in the main application folder: project folder ..+app ....+migrations ......-0001_initial.py Here is the content of the migration file: from __future__ import unicode_literals from django.db import migrations def set_development_site(apps, schema_editor): Site = apps.get_model('sites', 'Site') current= Site.objects.get_current() current.domain = "localhost:8000" current.name = "Django-Angular-Webpack-Starter" current.save() class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.RunPython(set_development_site), ] And the output from the python manage.py migrate command: Operations to perform: Apply all migrations: admin, app, auth, authentication, authtoken, contenttypes, sessions, sites Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying authentication.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying app.0001_initial...Traceback (most recent call last): File … -
Django Error: Deadlock found when trying to get lock; try restarting transaction
Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 223, in get_response response = middleware_method(request, response) File "/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/middleware.py", line 49, in process_response request.session.save() File "/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/db.py", line 64, in save obj.save(force_insert=must_create, using=using) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 710, in save force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 738, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 822, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 861, in _do_insert using=using, raw=raw) File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 127, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 920, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 963, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py", line 124, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute self.errorhandler(self, exc, value) File "/usr/local/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue OperationalError: (1213, 'Deadlock found when trying to get lock; try restarting transaction') -
Django filter package
I have installed django filter the docs are here https://django-filter.readthedocs.io/en/master/ my code is from django import forms import django_filters from facilities.models import Facility from categories.models import Category from amenities.models import Amenity from locations.models import Location from catalogue.models import Business class BusinessFilter(django_filters.FilterSet): facilities = django_filters.ModelMultipleChoiceFilter( label='Facility', name='facilities', lookup_expr='contains', widget=forms.CheckboxSelectMultiple(), queryset=Facility.objects.all(), required=False) ammenities = django_filters.ModelMultipleChoiceFilter( label='Amenities', name='amenities', lookup_expr='contains', widget=forms.CheckboxSelectMultiple(), queryset=Amenity.objects.all(), required=False) seasonrate__price = django_filters.NumberFilter(name='seasonrate__price') location = django_filters.ModelChoiceFilter( label='Regions', queryset=Location.objects.regions(), required=False, initial=0) category = django_filters.ModelChoiceFilter( label='Category', queryset=Category.objects.all(), required=False, initial=0) class Meta: model = Business fields = { 'seasonrate__price': ['lt', 'gt'] } def __init__(self, *args, **kwargs): print(dir(self)) category_type = self.data['category_type'] print(category_type) category_type_form = getattr(Facility, str(category_type)) if category_type_form: self.fields['facilities'].queryset = Facility.objects.filter( type=category_type_form) self.fields['amenities'].queryset = Amenity.objects.filter( type=category_type_form) self.fields['category'].queryset = Category.objects.filter( type=category_type_form) super(BusinessFilter, self).__init__(*args, **kwargs) in my views.py i have search_form = BusinessFilter(request=self.request.GET, data={'category_type': category_type}, queryset=business_list) i can't pass the category type so as to customize querysets in my form. I tried also with kwargs with no success -
Post json data getting csrf token missing or invalid
Would appreciate if someone can help me find the problem. I know there are a lot of solutions regarding this specific problem. Have been stuck here for a quite a long time now. My code Views class HolidayList(ListCreateAPIView): queryset = Holiday.objects.all() serializer_class = HolidaySerializer permission_classes = [IsAdminUser, IsAuthenticated] authentication_classes = [SessionAuthentication,BasicAuthentication] url url(r'^$', HolidayList.as_view(), name='holiday-list-api'), Getting this error {"detail":"CSRF Failed: CSRF token missing or incorrect."} my rest framework configuration REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'base.csrf_exempt.CsrfExemptSessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.IsAdminUser', ), } Tried to use CsrfExempt but no luck. What am i missing here ? from rest_framework.authentication import SessionAuthentication class CsrfExemptSessionAuthentication(SessionAuthentication): def enforce_csrf(self, request): return -
Django template iteration through structure
Good morning I have the following structure coming from the backend: sentences_info = [ { "keyword": "", "sentences": [ { "sentence_id": "", "sentence": "" }, ... ], ... }, ... ] I need to put this structure in my template, in a checkbox form, like this: <form> <h3>Keyword: {{ keyword }}</h3> <div class="form-check"> <label class="form-check-label"> <input type="checkbox" class="form-check-input" id="{{ sentence_id }}" value="{{ sentence_id }}"> {{ sentence }} </label> <label class="form-check-label"> <input type="checkbox" class="form-check-input" id="{{ sentence_id }}" value="{{ sentence_id }}"> {{ sentence }} </label> ... </div> <h3>Keyword: {{ keyword }}</h3> <div class="form-check"> <label class="form-check-label"> <input type="checkbox" class="form-check-input" id="{{ sentence_id }}" value="{{ sentence_id }}"> {{ sentence }} </label> <label class="form-check-label"> <input type="checkbox" class="form-check-input" id="{{ sentence_id }}" value="{{ sentence_id }}"> {{ sentence }} </label> ... </div> ... </form> I tried some iterations, but can't make sense to put this on the template so far..can someone help me, please? -
Django templates inheritance
For example: base.html <body> {% block content} {% endblock %} </body> base_index.html {% extends 'base.html' %} {% block content %} something {% endblock %} # add new block "for_child" to fill in with next inheritance <h1>Name: {% block for_child %} {% endblock %}</h1> base_index_child.html {% extends 'base_index.html' %} {% block for_child %} Peter {% endblock %} Result base_index_child.html: <body> something <h1>Name:</h1> </body> But i want (base.html -> base_index.html -> base_index_child.html) <body> something <h1>Name: Peter</h1> </body> How to get this? -
get ID from UUID field(in master) and then insert it to detail serializer
We have 2 table in database, which is Lookups(master) and LookupCodes(Detail). class Lookups(models.Model): lookup_uuid = models.UUIDField(db_index=True,default=uuid.uuid4, editable=False) class LookupCodes(models.Model): lookupcode_uuid = models.UUIDField(db_index=True, default=uuid.uuid4, editable=False) lookup_id = models.ForeignKey(Lookups,on_delete=models.DO_NOTHING, db_column='lookup_id',related_name='lookupcodes') We dont specify the primary key,so the primary key is id when we migrated that 2 table. Below is our serializable: class LookupCodeSerializer(serializers.ModelSerializer): class Meta: model = LookupCodes fields = ( 'lookupcode_uuid',lookup_id) class LookupSerializer(serializers.ModelSerializer): class Meta: model = Lookups fields = ('lookup_uuid') We are using uuid as lookup_field to perform retrieve,delete,update master and detail form,which is lookup and lookup code. How to perform insert on lookupcode(which is detail),when we already have uuid of lookup(which is master) and dont have the lookup_id? -
"OperationalError, unrecognized token" while searching
I'm getting this error while making any search query: OperationalError at /search/ unrecognized token: "@" My view: class Search(ListView): model = Opinion template_name = 'home/search.html' context_object_name = 'search_results' paginate_by = 10 def get_queryset(self): qs = Opinion.objects.all() keywords = self.request.GET.get('q') if keywords: query = SearchQuery(keywords) vector = SearchVector('text') qs = qs.annotate(search=vector).filter(search=query) qs = qs.annotate(rank=SearchRank(vector, query)).order_by('-rank') return qs My search form: <form class="navbar-form navbar-left" role="search" method="get" action="{% url 'home:search' %}"> <div class="form-group"> <input type="text" class="form-control" name="q" value=""> </div> <button type="submit" class="btn btn-default">Search</button> </form> Any suggestion or feedback will be welcomed and greatly appreciated. Thank you.