Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue when trying to create a filtered query in Django
I am trying to create a filtered query in Django 1.5 but I get nothing back. More specifically I do this: autocomplete_light.register(my_model, search_fields=['title'], choices=my_model.objects.filter(detail_url='/detailed/'), autocomplete_js_attributes={'placeholder': 'Resource name..', },) The above returns nothing. I thought using the "filter" functionality the query behaves like the equivalent LIKE of SQL. If I try to filter with the exact string, then it works properly. What am I missing here? -
nginx redirects not working after adding trailing slash
I am using nginx with django. Actually i am moving an old site to a new domain. In the process I have also updated the url structure of post and pages. Here is how nginx configuration looks like: server { server_name 44.41.211.161; access_log off; location /static/ { alias /home/project/Sites/project/static/; } rewrite ^/old-url$ http://example.com/updated-url permanent; location /media/ { alias /home/project/Sites/project/media/; } location / { proxy_pass http://127.0.0.1:8001; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } } If i visit http://example.com/old-url nginx perfectly redirects old-url to http://example.com/updated-url but if i visit http://example.com/old-url/ (with a trailing slash) it returns a 404 error. How do i prevent a 404 error and redirect http://example.com/old-url/ to http://example.com/updated-url -
How to validate a json structure in Python3
I am using Python3.5 and Django for a web api.When I refer to input, I refer to a HTTP request parameters. I have a parameter where I am expecting a JSON data which I need to validate before processing further. I have a base json structure that the input has to be in. Example, { "error": "bool", "data": [ { "name": "string", "age": "number" }, { "name": "string", "age": "number" }, ... ] } The above JSON represents the structure that I want my input to be in. The keys are predefined, and the value represents the datatype of that key that I am expecting. I came across a Python library(jsonschema) that does this validation, but I can't find any documentation where it works with dynamic data. i.e. the objects inside the JSON array 'data' can be of any number, of course this is the most simple scenario I came up with for explaining the basic requirement. In cases like these, how can I validate my json? -
Django: Migrating database on heroku fails due to CommandError: App 'my_app' does not have migrations
I am trying to deploy an django application to heroku, but are experiencing some wierd problems. I am trying to migrate the database for the first time, but when running: heroku run python manage.py migrate the different apps registered in INSTALLED_APPS are not detected. Further more if I run the command: heroku run python manage.py makemigrations my_app a migrations file is created: my_app/migrations/0001_initial.py: - Create model UserProfile - Create model Company - Create model CompanyProductRelation - Create model GiftCardCode - Create model Product - Create model ProductImage - Create model Type - Create model Wish - Add field product to companyproductrelation - Add field company to userprofile But if i then run: heroku run python manage.py migrate company_service I get an output saying: CommandError: App 'my_app' does not have migrations. I have been searching the web all day, but can not seem to find anyone having the same issue as me. All the apps are registered in INSTALLED_APP, and they all have a __init__.py file in their respective folders. I am currently on Django 1.10.6 -
Modifying imported bootstrap code within html file
I am making a django web application where I have base.html and base_bootstrap.html files. My base_bootstrap.html file contains the following two lines to use bootstrap CSS: <!-- Bootstrap core CSS --> <link href="http://v4-alpha.getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet"> . . . Is there a way for me to modify the following css in order to change the #999 into a # without creating a separate css file? pre { border: 1px solid #999; page-break-inside: avoid } <!-- Custom styles for this template --> <link href="http://v4-alpha.getbootstrap.com/examples/dashboard/dashboard.css" rel="stylesheet"> -
PostgreSQL on AWS ECS: psycopg2.OperationalError invalid port number 5432
I'm having a problem with database connection via psycopg2 on AWS ECS. I have an App container and a DB container. Containers are linked. The App has an entrypoint script that checks if the DB is up before starting an app server. $ until psql -h "$DB_HOST" -U "$DB_USER" -c '' && >&2 echo "Postgres is up"; do >&2 echo "Postgres is unavailable - sleeping" sleep 1 done > Is the server running on host "db" (172.17.0.3) and accepting > TCP/IP connections on port 5432? > Postgres is unavailable - sleeping > Postgres is up This part works fine, but as soon as the app server starts and tries to connect to the DB I get the following error: psycopg2.OperationalError: invalid port number: "tcp://172.17.0.3:5432" I have no idea what could be the case. This works fine when running locally with Docker. Any hints would be appreciated. Thanks! -
Django - Remove add new record from form widget>
I have created a form widget that is automatically adding a add new record section at the top of the form, which i do not want to be there. can someone tell me how to disable this? I just want to display the variables not the add form. forms.py class TemplateVariablesWidget(forms.Widget): template_name = 'sites/config_variables.html' def render(self, name, value, attrs=None): sc_vars = ConfigVariables.objects.filter(type='Showroom') wc_vars = ConfigVariables.objects.filter(type='Major Site') context = { 'SConfigVariables' : sc_vars, 'WConfigVariables' : wc_vars, } return mark_safe(render_to_string(self.template_name, context)) class VariableForm(forms.ModelForm): variables = forms.CharField(widget=TemplateVariablesWidget, required=False) class Meta: model = ConfigVariables fields = "__all__" admin.py class ConfigTemplateAdmin(admin.ModelAdmin): list_display = ('device_name', 'date_modified') def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = extra_context or {} #extra_context['include_template'] = '/path/to/template.html' extra_context['include_form'] = VariableForm return super(ConfigTemplateAdmin, self).change_view( request, object_id, form_url, extra_context=extra_context, ) change_view.html {% block extra_content %} {% if include_template %} {% include include_template %} {% endif %} {% if include_form %} <form method="POST" class="post-form"> {% csrf_token %} {{ include_form.as_p }} </form> {% endif %} {% endblock %} page that is loaded: -
change password link on login page
I have default /admin/login/ and page and default http://localhost:8000/password_reset I'd like a "forgot your password?" link on login page. Is there a straightforward way to do it or do should i just override the template? -
django-rest-framework-gis and filters
Could this configuration apply to DRF when django-rest-framework-gis is used for serializer ? 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.DjangoFilterBackend', 'rest_framework.filters.SearchFilter' ) my views.py : class ReferenceGeoViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint that allows References to be listed as a GeoJson feature collection. """ queryset = Reference.objects.all().order_by('name') filter_fields = ('id',) search_fields = ('name', 'description') pagination_class = None serializer_class = ReferenceGeoSerializer and my serializers.py from rest_framework_gis.serializers import GeoFeatureModelSerializer class ReferenceGeoSerializer(GeoFeatureModelSerializer): """ A class to serialize locations as GeoJSON compatible data """ class Meta: model = Reference geo_field = "geom_point" fields = ('id', 'url', 'name', 'description', 'year', 'publication') i can't get it working in DRF API. -
django-autocomplete-light initial data using Select2 widget
I have a form field with autocomplete (using django-autocomplete-light app and Select2 widget), which serve as a search filter and it works as expected. When I submit the form and search results are listed, I would like to set this form field initial value to previously submitted value - so the user can adjust some of the search parameters instead of setting up all search filters from scratch. This form field will be used to choose one of the ~10000 values, so I need it to load values on-demand. As the form field is not prepopulated with any values, I have no idea how it would be possible to set initial value. models.py class Location(models.Model): place = models.CharField(max_length=50) postal_code = models.CharField(max_length=5) views.py class LocationAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Location.objects.all() if self.q: qs = qs.filter(place__istartswith=self.q) | qs.filter(postal_code__istartswith=self.q) return qs forms.py class LocationForm(forms.ModelForm): class Meta: model = Location fields = ('place',) widgets = { 'place': autocomplete.Select2(url='location_autocomplete') } Any suggestions? Thanks! -
How to add two values and save them with post_save signals
I'm using signals in models.py but when I make a sum this function does it twice instead of just a sum models.py: class Articulo(models.Model): cod_experto = models.CharField(max_length=999, primary_key=True, blank=True) nombre = models.CharField(max_length=999, blank=True) descripcion = models.CharField(max_length=999, blank=True, null=True) on_delete=models.CASCADE) stock = models.IntegerField(blank=True, default=0) total_pedido =models.IntegerField(blank=True, default=0) class Pedido(models.Model): especialidad = models.ForeignKey('Especialidad') articulo = models.ForeignKey('Articulo') blank=True) cantidad = models.IntegerField(blank=True) default='pendiente') def __str__(self): return '{}'.format(self.especialidad, self.articulo, self.cantidad, self.estado) def update_total(sender, instance, **kwargs): instance.articulo.total_pedido += instance.cantidad instance.articulo.save() # register the signal signals.post_save.connect(update_total,sender=Pedido, dispatch_uid="update_stock_count") views.py def Cant_ingresar(request, id_pedido, id_especialidad): especialidad = Especialidad.objects.get(id=id_especialidad) pedido = Pedido.objects.get(id=id_pedido) if request.method == 'GET': form = PedidoEditForm(instance=pedido) else: form = PedidoEditForm(request.POST, instance=pedido) if form.is_valid(): form.save() return HttpResponseRedirect('/solicitar/lista_active/%s/' % id_especialidad) return render(request, 'form.html', {'form':form, 'pedido':pedido, 'especialidad':especialidad, 'pedido':pedido}) As you can see, I first save the cantidad entered in the def of views.py, then in the model with the signals captured with post_save the amount and is summed with total_pedido of the Articulo model, this without problems, but adds two Times the same amount ie, enter a 3 and this goes to total_pedido as 6. Help pls! -
Email-only authentication with django-allauth
I want to set up authentication with e-mails as usernames. My configuration: ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "optional" ACCOUNT_USERNAME_REQUIRED = False However, after creating an account with e-mail example@example.com there's a message Successfully signed in as example15 and a user with username example15. How to completely replace usernames with emails? -
Bad interpreter: No such file or directory
I am trying to deploy my site with EB CLI. Whenever I try to run $ eb --version, it always shows the error below, even though it works on my CMD. Can anyone help me with it? Thank you. /c/Users/username/AppData/Local/Programs/Python/Python35/Scripts/eb: c:\users\user: bad interpreter: No such file or directory -
Django+Apache ModuleNotFoundError: No module named 'myproject'
I have a problem with Apache2.4 + mod_wsgi + Python3.6 (on win10 x64). When I'm trying to access site, i receive this error in Apache. Here are my config files: wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ["DJANGO_SETTINGS_MODULE"] = "myproject.settings" application = get_wsgi_application() settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'secret_key_here' DEBUG = False ALLOWED_HOSTS = ['mysite'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'site.apps.SiteConfig', ] 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', ] ROOT_URLCONF = 'myproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'myproject.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'name', 'USER': 'root', 'PASSWORD': 'pass', 'HOST': 'host', 'PORT': '3306', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATIC_ROOT = 'C:/wampstack-5.6.30-1/apache2/htdocs/static.mysite/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) httpd-vhosts.conf (Apache): <VirtualHost *:80> WSGIScriptAlias / "C:/wampstack-5.6.30-1/apache2/htdocs/myproject/myproject/wsgi.py" ServerName mysite Alias /static "C:/wampstack-5.6.30-1/apache2/htdocs/myproject/static" <Directory "C:/wampstack-5.6.30-1/apache2/htdocs/myproject"> Order allow,deny Allow from all </Directory> </VirtualHost> In httpd.conf … -
django CMS render_model_add twice for same model in template
<h2>News{% render_model_add news.0 %}</h2> <h2>News{% render_model_add news.0 %}</h2> First line works OK and there is a plus icon near "News" label but second line of code shows only label without plus icon. Also when use render_model_block twice for same instance in single template i can edit only the first one. Is there any way how to allow edit add/edit model from multiple places on single page? -
How to edit uploaded csv files using django?
I want to know, how one can edit an uploaded CSV file to the database, using Django admin panel and then save the changes. Details: So I have uploaded a csv file to the database and I want my users to go the Django admin panel, log in with their username and password and then edit the uploaded CSV file and then save the changes. P.S: I am a beginner in Django so any help will be much much appreciated. Thanks :) -
Django not picking up CSS
It just doesnt seem to be picking it up. I don't know where small error could be. Appreciate any insights! The static directory is as follows: Aviation -> static -> - bootstrap - css - fonts - img - js In my base.html I have the following css: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <title>Aviation Website</title> <base href="/" /> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="theme-color" content="#333"> <meta name="msapplication-navbutton-color" content="#333"> <meta name="apple-mobile-web-app-status-bar-style" content="#333"> <meta name="description" content="TBD"> {% block css %} <link rel="stylesheet" href="{% static "bootstrap/css/bootstrap.min.css"%}"/> <link rel="stylesheet" href="{% static "css/user.css" %}"/> <link rel="stylesheet" href="{% static "css/Article-List.css" %}"/> <link rel="stylesheet" href="{% static "css/Team-Boxed.css" %}"/> <link rel="stylesheet" href="{% static "css/untitled.css" %}"/> {% endblock css %} </head> Settings.py: STATIC_ROOT = map_path('static') STATIC_URL = '/static/' STATICFILES_DIRS = [ map_path('static'), ] STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) MEDIA_ROOT = map_path('static/uploads') MEDIA_URL = '/static/uploads/' try: from .local_settings import * except: pass -
Django Sqlite3 how to insert binary to Blob
I want to store binary data (wav data)in the Sqlite3,but just stored the Head "RIFF$" ,how to store the hole data? this is the server code if request.method == 'POST': postDict={} req = json.loads(request.body) postDict['audioFile']=req['audioFile'] postDict['textFile']=req['textFile'] postDict['audioBinary']=sqlite3.Binary(req['audioBinary']) if postDict: insertToDB(conn,cu,postDict['audioFile'],postDict['textFile'],buffer(postDict['audioBinary'])) postDict['audioFile'] and postDict['textFile'] can store rightly but postDict['audioBinary']) only stored "RIFF$",the binary losed,I tested that the POST data is right,just can't store in database.please help me. -
Doing text lookup for a ModelChoiceField on Admin gets an error
I've a model that has a text field I added a form with Django-Autocomplete to get the available objects for this field. In the admin page for this model, i'd like to search for objects, using the my_field field but i get an error "Related Field got invalid lookup: icontains" I understand that i get it because the form's field is now ModelChoiceField, how can i fix it to search based on the SomeOtherModel's name field? from dal import autocomplete import django.forms as forms from django.db import models # models.py class SomeModel(models.Model): some_other_model = models.ForeignKey('SomeOtherModel', ) class SomeOtherModel(models.Model): name = models.CharField(max_length=255) #admin.py class SomeModelAdmin(admin.ModelAdmin): form = SomeModelForm search_fields = ['some_other_model__name', ] #form.py class SomeModelForm(ModelForm): some_other_model = forms.ModelChoiceField( queryset=SomeOtherModel.objects.all(), widget=autocomplete.ModelSelect2(url='control:someothermodel-autocomplete', ) ) -
HTTPS request using python requests library
I am trying to send a https request using python requests library my code is full_url = ''.join(['https://', get_current_site(request).domain, '/am/reply']) data = {'agent_type':'trigger','input':platform,'user':request.user.id} a = requests.get(full_url,params=data,verify=False) The problem is that there is no execution after requests whole code is stucked at this point. I tried to verify my code using python shell and it run perfectly. Is there any way that i can debug whole my requests response that is going on real time or can someone suggest me a solution -
django rest framework doc error
I have installed the katest version of DRF and want to install the API documentation. I did as in http://www.django-rest-framework.org/topics/documenting-your-api/: from rest_framework.documentation import include_docs_urls ... url(r'^docs/', include_docs_urls(title='My API title')), ... When i go to http://127.0.0.1:800/docs, i have this issue: [23/Mar/2017 10:09:23] "GET /docs/ HTTP/1.1" 401 12237 [23/Mar/2017 10:09:24] "GET /docs/schema.js HTTP/1.1" 401 204 [23/Mar/2017 10:09:24] "GET /static/rest_framework/docs/js/jquery-1.10.2.min.js HTTP/1.1" 304 0 [23/Mar/2017 10:09:24] "GET /static/rest_framework/js/coreapi-0.1.0.js HTTP/1.1" 304 0 [23/Mar/2017 10:09:24] "GET /static/rest_framework/docs/js/api.js HTTP/1.1" 304 0 [23/Mar/2017 10:09:24] "GET /static/rest_framework/docs/js/jquery.json-view.min.js HTTP/1.1" 304 0 [23/Mar/2017 10:09:24] "GET /static/rest_framework/docs/js/bootstrap.min.js HTTP/1.1" 304 0 [23/Mar/2017 10:09:24] "GET /docs/schema.js HTTP/1.1" 401 204 In settings DEBUG=True. How should i add /docs/schema.js? -
sort a list of django models by specific fiels
I have a list of dajngo objects, all from the same class and those objects are not save in the DB. I want to sort the list (again, list of models) by specific field in that class. How can I do that? Thanks! -
Django - INSTALLED_APPS for submodule
I created an app called API using django startapp api. I then loaded this app from my main application (app) in the settings.py (app/settings.py): INSTALLED_APPS = [ ... 'api.apps.ApiConfig', ... ] This works great! Then, I created a settings.py file in the api folder (api/settings.py). I would like to load a module called rest_framework from within this submodule (due to reusability). So the api/settings.py file contains the following: INSTALLED_APPS = [ 'rest_framework' ] The rest_framework module, however, is not loaded when I run the application. I found the following workaround (for app/settings.py): from api.settings import INSTALLED_APPS as API_APPS INSTALLED_APPS += API_APPS I think this is not the best way of loading the INSTALLED_APPS in the main application for all submodules. Is there a better way of loading all submodules INSTALLED_APPS? -
why do we use auth.user in ABSOLUTE_URL_OVERRIDES instead of django.contrib.auth.models.User
This seems a common use case: ABSOLUTE_URL_OVERRIDES = { 'auth.user': lambda u: reverse_lazy('user_detail', args=[u.username]) } why do we have to use auth.user in ABSOLUTE_URL_OVERRIDES instead of django.contrib.auth.models.User which is the name of the model? not even Uppercase for the class -
Django: detect module level db queries
Database queries at modul level (aka import-time) can make trouble in django. See: https://groups.google.com/forum/#!topic/django-developers/7JwWatLfP44/discussion Trouble: The real db gets accessed in tests, not the test-database. Monkey patching in app-ready signals are too late ... How can I detect the particular python source line which accesses my database before the app ready signal happens?