Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to add angular front end to django rest application?
I have a django rest app and I have my front-end designed with angularjs including homepage and all stuff in one folder I don't know how to connect my front end folder to my django app so that they work integratedly any suggestions? -
I have use the corsheaders config the CORS setting, why when `localhost:8080` access still get the error?
I have use the csrfheaders in my Django backend, but I use the frontend to access the API, I still get the bellow error: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:8080' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. my Django backend project's settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '8cyiv%(rkpv33s_(n8x_5&+6-9&s!ddc!0)98la3=9(y8=k$4u' DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'corsheaders', # the corsheaders 'rest_framework', 'rest_framework.authtoken', 'rest_framework_docs', 'rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth.registration', 'wx_numbers', 'users_management', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = ( 'XMLHttpRequest', 'X_FILENAME', 'accept-encoding', 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( 'localhost:8080' ) ROOT_URLCONF = 'wx_backup.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', ], }, … -
The view myapp.views.registration didn't return an HttpResponse object. It returned None instead
when i try to register with same username it must show error on html page but it show like "The view myapp.views.registration didn't return an HttpResponse object. It returned None instead." when i try to register with same username it must show error on html page but it show like "The view myapp.views.registration didn't return an HttpResponse object. It returned None instead." when i try to register with same username it must show error on html page but it show like "The view myapp.views.registration didn't return an HttpResponse object. It returned None instead. when i try to register with same username it must show error on html page but it show like "The view myapp.views.registration didn't return an HttpResponse object. It returned None instead. when i try to register with same username it must show error on html page but it show like "The view myapp.views.registration didn't return an HttpResponse object. It returned None instead. when i try to register with same username it must show error on html page but it show like "The view myapp.views.registration didn't return an HttpResponse object. It returned None instead." when i try to register with same username it must show error on html … -
How to set Collation in MySQL database with Django 2.* mysqlclient?
I need to set default Collation for MySQL tables with Django 2.*, im using mysqlclient, my settings are: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'charset': 'utf8mb4', }, } } 'charset': 'utf8mb4', This parameter seems don't work properly and tables in DB utf8. Although i want to manually set and tables Collation to utf8mb4_general_ci Will be appreciate for any clues. -
How can I use this for loop variable in django?
CODE: <form> <div class="form-group"> <label for="sel1">Select list (select one):</label> <select class="form-control" id="sel1" style="width: 96px"> {% for i in 150 %} <!-- here is what I ask for --> <option>{{ i + 1989 }}</option> {% endfor %} </select> </div> </form> I want to make year select form which is from 1900 to 2050. How can I use i variable in django template tag? -
django call view according to url version
Lets say I have a versioned url like: /movies/(?P<pk>[a-z]+)/(?P<version>v\d{1,2}\.\d{1,2})/?$, Movies.as_view() which calls the view Movies If the version is v1.2 I would like to call Movies_1_2 and if the version is v0.1 I would like to call Movies_0_1. I would like to know what is the best practice to do this. I am thinking of checking the version in Movies dispatch method and calling the version based view from there according to version. Is it good to do this or there is something else anyone is doing for versioning. I would be glad to know the best practice. P.S. I am not using DRF -
django pass extra parameters to foreignkey field
I have model like: class Profile(models.Model, DictMixin): user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, related_name="profile") display_name = models.CharField(max_length=30) avatar = models.ForeignKey(MyMedia, models.CASCADE, related_name="avatar") class MyMedia(models.Model): media = models.FileField(upload_to="some_dynamic_folder") Here I am having a ForeignKey relation of MyMedia to avatar. When I upload the file I want it to save to specific folder that I pass as a parameter to ForeignKeyField or Manytomanyfield. Lets, say all the profile picture should be saved in profile_picture field and all the contents should be saved in content folder. Is it possible to do this ? Need some suggestins :) -
Modify LDAP user in a GUI (using Django)
So I am currently working on a webapp by using the Django-Framework. After a lot of research, I could not find a way for users, to type in their edits in the webapp and these will automatically change their attributes. This is how I did it ( # import class and constants from ldap3 import Server, Connection, ALL, MODIFY_REPLACE # define the server s = Server('servername', get_info=ALL) # define an unsecure LDAP server, requesting info on DSE and schema # define the connection c = Connection(s, user='user_dn', password='user_password') c.bind() # perform the Modify operation c.modify('cn=user1,ou=users,o=company', {'givenName': [(MODIFY_REPLACE, ['givenname-1-replaced'])], 'sn': [(MODIFY_REPLACE, ['sn-replaced'])]}) print(c.result) # close the connection c.unbind() In the example above, you need to set the user in the script and specifically say, way needs to be changed. Is it even possible with Django or do I need a dynamic script or whatever? If you have any idea, do not hesitate to post it. Thanks in advance. -
How to round up Django money
how do i round up django money? I can't find it in the doc. Thanks in advance! xxx = Money(amount=99.21, currency='SGD') xxx= round(xxx) -
POST vs GET method in Django's view function
My app's urls.py is: from django.urls import path from . import views app_name = 'javascript' urlpatterns = [ path('create_table', views.create_table, name='create_table') My views.py is: def create_table(request): if request.method == 'POST': row_data = "this is row data" context = {'row_data': row_data} return render(request, 'javascript/create_table.html') My create_table.html is: {% load static %} <form action="" method="post"> {% csrf_token %} <button id="create_table">Get data</button> </form> <div id="place_for_table"></div> <script type="text/javascript"> var row_data = "{{ row_data }}" </script> <script src="{% static 'javascript/scripts/create_table.js' %}"></script> And my create_table.js is: function create_table() { document.getElementById("place_for_table").innerHTML = row_data; } document.getElementById("create_table").onclick = function() { create_table() } What I want to achieve is: when the /create table URL is requested, only the button is displayed. When the button is pressed, row_data variable's value is displayed below the button. At this moment the data is displayed for a blink of an eye and then disappears. I guess I am not distinguishing between POST and GET methods correctly in the view function. Also I have based my logic on the assumption that URL is requested using GET method by default. However if I put a print(request.method) at the beginning of my view, it prints POST. Also, whenever I load the page for the first time or … -
Django RegexField field drops case insensitivity -- makes compiled object case sensitive
I need case insensitivity (lack of case sensitive). I compile an object as case insensitive, and immediately afterwards, it works as case insensitive. I can store it in the database, and at that moment, it still works as case insensitive. But when I come back later, case insensitivity is LOST -- the compiled object is CASE SENSITIVE. I'm using PostgreSQL version 10. Here is a shell session that illustrates: In [9]: t Out[9]: (re.compile(r'(Acoustat)', re.IGNORECASE|re.UNICODE), None, None) In [10]: findTitle, findExclude, findKeyWords = t In [11]: oTableRow.oRegExLook4Title= findTitle In [12]: oTableRow.save() In [13]: oTableRow.oRegExLook4Title Out[13]: re.compile(r'(Acoustat)', re.IGNORECASE|re.UNICODE) In [14]: findTitle.search( 'abc ACOUSTAT efg' ) Out[14]: <_sre.SRE_Match object; span=(4, 12), match='ACOUSTAT'> ... In [18]: exit (auctions) rick@conf-k16-2018:~/Devel/auctionbot$ python manage shell Python 3.5.2 (default, Nov 23 2017, 16:37:01) Type 'copyright', 'credits' or 'license' for more information IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help. In [1]: from brands.models import Brand In [2]: oBrand = Brand.objects.all().first() In [3]: oBrand Out[3]: <Brand: Acoustat> In [4]: oTableRow = oBrand In [5]: oTableRow.oRegExLook4Title Out[5]: re.compile(r'(Acoustat)', re.UNICODE) Line above Out[13] shows that the object has the IGNORECASE flag, and Out[14] shows it works as advertised. At bottom, Out[5] shows NO IGNORECASE flag. And yes … -
UnicodeEncodeError: 'charmap' codec can't encode character '\u2264'
I'm using python3.6 in windows7 and django 1.9 I got this error when i run my code. In my code i'm parsing xml data to write a html page. I got that some character is unable to encode properly thats why its throwing an error. \u2264 this is the character(less than or equal) which is the root cause of the error. My question is how to encode this properly in python3 Detailed Error Log: Traceback (most recent call last): File "C:\Dev\EXE\TEMP\cookie\crumbs\views.py", line 1520, in parser html_file.write(html_text) File "C:\Users\Cookie1\AppData\Local\Programs\Python\Python36-32\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u2264' in position 389078: character maps to -
TemplateDoesNotExist error in django polls aplication
I am making a polls application in django and I get the following error: TemplateDoesNotExist at /polls/ This is what my index function looks like this: def index(request): latest_questions = Question.objects.order_by('-pub_date')[0:5] context = {'latest_questions': latest_questions} return render(request, "polls/template.html", context) template.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% if latest_ques %} <ul> {% for question in latest_ques%} <li><a href = '/polls/{{question_id}}/'><b> {{question.ques_text}}</b></a></li> {% endfor %} </ul> {% endif %} </body> </html> Inside of my polls file I have a template file and inside of that I have a template folder inside of that I have another polls folder and inside of that I have template.html. I have tried using render_to_response instead of render, I also tried to add the path to DIRS in settings.py and I tried taking request out of the function. Thank you so much. -
Different migration file names for on external library using Django and docker-compose
I have a project which I added new external library recently. So I re-build my docker images to include this library by running docker-compose build and this is my DockerFile FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN apt-get update && apt-get install -y \ rabbitmq-server \ gettext \ xmlsec1 # Chinese PYPI mirror RUN mkdir /root/.pip/ #COPY ./pip-china.conf /root/.pip/pip.conf RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ RUN DATABASE_URL=None python3 manage.py collectstatic --noinput RUN DATABASE_URL=None python3 manage.py compilemessages After I create my new docker image I run migrations with new field added on my model so it generates this migration file. # -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-03-16 02:46 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wagtailvideos', '0010_auto_20180316_0246'), ('pages', '0117_auto_20180315_0905'), ] operations = [ migrations.AddField( model_name='articlepage', name='header_video', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailvideos.Video'), ), ] so far everything is fine my local works completely perfect. But if build my my docker images on staging/production server it gives me migration file not found. ('wagtailvideos', '0010_auto_20180316_0246') So I have to run makemigrations manually on other servers which gives me different migration filenames … -
django pick from multiple databases for testing
I have multiple databases defined. This is for test profile, and I want to be able to specify which database to be picked for testing. eg: "python manage.py test -db=mysql" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'mysql': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mysql_test', } } I went through the django documentation, but i cant find a clear cut way of doing it. One way of getting around this is setting up environment variables, and define both databases as default. Then use the db based on the database type. please let me know if there is a much better way of doing this. thanks Amal -
Dont know how to use and work href on form ON Django python
Hey I am beginner in Django.I dont know how can I use href on form in django This is my url.py on my Django project name albert(folder) This is my views.py This is my urls on my django APP name (folder)home but it name with login cause it login url.py -
Google API key not working on server but working fine on local server
I am really new to Google API key. When am I testing my code on the local system, it is working fine but on an actual server it giving me SSLHandshakeError. SSLHandshakeError at 'url' [Errno 1] _ssl.c:510: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed -
Django Custom Command with supervisorctl
I have a django custom management command named Stream that when run in a virtual environment or run using /webapps/senticle50/brexit/python-virtualenv/bin/python /webapps/senticle50/brexit/manage.py Stream --settings=brexit.settings.production works but when I put the exact command into a supervisord .conf file and after running: supervisorctl reread && supervisorctl update followed by supervisorctl restart stream it starts the process but the django command is never actually executed as no output is printed to the log file amongst other end goals of the custom django command not being met. stream.conf: [program:stream] command=/webapps/senticle50/brexit/python-virtualenv/bin/python /webapps/senticle50/brexit/manage.py Stream --settings=brexit.settings.production user=senticle50 stdout_logfile = /webapps/senticle50/logs/stream.log ; Where to write log messages stderr_logfile = /webapps/senticle50/logs/stream.log environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 TLDR; the command works outside of supervisor but when run through supervisor the process starts but the command is never run. -
using python Django and Mysql. Data won't insert due to Binlog
When I use django to design a website and delopy, I find I have some trouble if I using MySQL that turn on the Binlog( mode:STATEMENT). Traceback like this: django.db.utils.OperationalError: (1665, 'Cannot execute statement: impossible to write to binary log since BINLOG_FORMAT = STATEMENT and at least one table uses a storage engine limited to row-based logging. InnoDB is limited to row- logging when transaction isolation level is READ COMMITTED or READ UNCOMMITTED.') -
Get every folder inside path
I just want to tell my Django project that the .html file it want can be find in any folder inside "/templates". I know this can be done with a simple pattern like allfolders = "/templates/*" or allfolders '/templates/$' or allfolders = 'templates/^$' I really can't remember the correct way of doing it, its just a simple string manipulation that can tell "The file is inside any folder inside the folder '/templates' without any imports being needed. Thats because i want to organize my templates folder so i can have different folders inside it to point me what type of html is this or from what project, things like that, organization propose. Thanks for your attention and sorry for the lack of code. -
SQL Count Optimisations
I have been using the Django Rest Framework, and part of the ORM does the following query as part of a generic object list endpoint: `SELECT COUNT(*) AS `__count` FROM `album` INNER JOIN `tracks` ON (`album`.`id` = `tracks`.`album_id`) WHERE `tracks`.`viewable` = 1` The API is supposed to only display albums with tracks that are set to viewable, but with a tracks table containing 50 million rows this is query never seem to complete and hangs the endpoint's execution. All columns referenced are indexed, so I do not know why this is taking so long to execute. If there are any potential optimisations that I might have not considered please let me know. -
Travis.yml file not being found in Django project
I have a Django project that needs to be built using TravisCI. Originally, I put the travis.yml file in the root of the project (where the virtual environment would be) and then built it but for some reason, Travis is using default settings since it can't find the yml file. I then moved the file into the src directory and rerun, but the build still wasn't finding the file. Where does the file need to be placed in order for Travis to find it? Travis.yml: language: python python: - "2.7" # setup environment env: - DJANGO_VERSION=1.11.2 - DJANGO_SETTINGS_MODULE='di_photouploader.settings.production' # install dependencies install: - pip install -r requirements.txt # run test scripts script: - python manage.py test -
How do I make a model with a datetime field that does NOT save the time zone?
I have a model that looks like this: class IPLog(models.Model): last_click = models.DateTimeField() When I save an IPLog instance, the time zone gets saved with it. This is a problem for me since I want to compare last_click to a datetime.now() instance, but it throws me an error since the model instance's last_click has a time zone: TypeError: can't subtract offset-naive and offset-aware datetimes. The difference tends to look like this: 2018-03-16 00:24:35.619424 # datetime.now() 2018-03-15 23:55:07.006190+00:00 # last_click How do I stop my model from saving new instances with a time zone? -
Django middleware advised not to use request.POST why?
"Accessing request.POST inside middleware before the view runs or in process_view() will prevent any view running after the middleware from being able to modify the upload handlers for the request, and should normally be avoided." This is from the django documentation. First of all, if I just read the POST, without changing that, how does it even know and how does it prevent the view from doing it's business and second, how is a CsrfViewMiddleware different in that sense? -
How do I print a url path in an `a` tag using the url's name attribute?
In my urls.py I have url("^login-register/$", views.login_register, name="login_register"),. In a template, I can do {% url "login_register" %}. How do I print that value in views.py?