Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python3 Django ZipFile HttpResponse UnicodeDecodeError
I created a zip file like so: zipped_file = zipfile.ZipFile("csvOutput{}.zip".format(timestamp), 'w') zipped_file.write(sms_file_path) zipped_file.write(mail_maga_file_path) zipped_file.close() And want to send it, which I am currently using this code: response_file = open('csvOutput{}.zip'.format(timestamp)) response = HttpResponse(response_file, content_type="application/force-download") response['Content-Disposition'] = 'attachment; filename=csvOutput{}.zip"'.format(timestamp) return response raise Http404 But maybe something I am using is out of date? Python keeps crashing with a byte it can't decode in unicode: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x94 in position 14: invalid start byte Says line 100 is throwing the error, which would be the line with HttpResponse() Edit: I've changed the content_type to application/zip and am getting a new error (that seems better?): caution: zipfile comment truncated error [output.zip]: missing 3232109644 bytes in zipfile (attempting to process anyway) error [output.zip]: attempt to seek before beginning of zipfile (please check that you have transferred or created the zipfile in the appropriate BINARY mode and that you have compiled UnZip properly) -
How do I get the existing value of the fields in a django form when going back in the browser?
I have a django form which has two select fields the second one being dynamic dependent on the value of the first. The values for the second select is loaded via ajax after the first one is selected. Although this works fine it breaks when going back in the browser. The value for the first select appear but nothing in the second (onchange event not happened yet). However rather than load these in the front event I would rather load these in django via the form, if there is a value in the first select. In the debugger when I go back in the browser it generates a GET request, not a POST and so the form is not bound and has no self.data. How do I get the existing value of the fields in a django form when going back in the browser? (note I am using session with database backend) -
nginx can't link uwsgi
I have installed nginx successfully and uwsgi work well but when I want to link nginx with uwsgi.it's wrong This is my nginx.conf and uwsgi.ini #server { listen 80; server_name localhost; #charset koi8-r; charset utf-8; #access_log logs/host.access.log main; location / { include uwsgi_params; uwsgi_pass 127.0.0.1:8000; root html; index index.html index.htm; } and http=127.0.0.1:8000 #socket=/root/project/learning_log/nginx_uwsgi.socket chdir=/root/project/learning_log/ #chmod-socket=664 master=true processes=4 threads=2 module=learning_log.wsgi #wsgi-file=uwsgi_test.py #stats=127.0.0.1:8000 ./nginx & uwsgi3 --ini /root/project/learning_log/uwsgi.ini when I access 127.0.0.1,it's wrong -
django template tag using for loop value
I have a template tag which is an array so for example to display data i use {{ ques.0 }},{{ ques.1 }} {{ ques.2 }}.....I am trying to display this using a for loop in java script x=5; for(var i=0;i<x;i++){ document.getElementById("question").innerHTML="{{ ques.i }}"; } the value of x may vary.. is there a way by which in the line document.getElementById("question").innerHTML="{{ ques.i }}"; I can get the value of i dynamically from java script and then accordingly he result will be displayed -
How do i specify a file upload in django to a folder in reference to one of the model fields
I have the following django models in my Document app class Section(models.Model): choices = ( ('Haematology', 'Haematology'), ('BloodBank', 'BloodBank'), ('Bacteriology', 'Bacteriology'), ('Parasitoloty', 'Parasitoloty'), ('Chemistry', 'Chemistry'), ('Histopathology', 'Histopathology'), ('Serology', 'Serology'), ('Immunology', 'Immunology'), ) title = models.CharField(max_length = 50, choices = choices) class Meta: verbose_name = "Section" verbose_name_plural = "Sections" def __str__(self): return str(self.title) class Document(models.Model): documentSection = models.ForeignKey(Section) category = models.ForeignKey(DocumentCategory) title = models.CharField(max_length = 100, default = '') description = models.TextField(null = True, blank = True, default = '') documentFile = models.FileField(upload_to = 'uploads/%Y/%m/') fileFormat = models.ForeignKey(FileFormat) uploaded = models.DateField(auto_now_add=True, default=timezone.now) modified = models.DateTimeField(auto_now=True, default=timezone.now) uploaded_by = models.ForeignKey(User) def __str__(self): return str(self.title) When i upload Documents i want then to be saved in a folder like 'uploads/documentSection/ or 'uploads/documentSection/%Y/%m/ My problem is i cant figure out how to take the value of the documentSection and parse it to upload_to = 'uploads/documentSection/ -
Django Docker MySQL docker-compose up error
I am dockerizing my existing Django rest project which uses MySQL as database. I already have an exiting database with some data in it. my dockerfile: FROM python:2.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt My docker-compose: version: '3' services: db: image: mysql environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: libraries MYSQL_USER: root MYSQL_PASSWORD: root web: build: . command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" My settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', #django.db.backends.mysql 'NAME': 'libraries', #local: libraries #server: 'USER': 'root', #localhost:root #root 'PASSWORD': 'root', #local: root #server: 'HOST': 'db', #docker: db #local: localhost #server: 'PORT': '3306', } } My docker-compose build was successful. However, docker-compose up gives me error with following log: D:\Development\Personal projects\library_backend>docker-compose up Creating librarybackend_web_1 Creating librarybackend_db_1 Attaching to librarybackend_db_1, librarybackend_web_1 db_1 | Initializing database db_1 | 2018-01-15T09:33:20.031132Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). db_1 | 2018-01-15T09:33:20.225632Z 0 [Warning] InnoDB: New log files created, LSN=45790 db_1 | 2018-01-15T09:33:20.259942Z 0 [Warning] InnoDB: Creating foreign key constraint system tables. db_1 | 2018-01-15T09:33:20.304181Z 0 [Warning] No existing UUID has been … -
How to verify password if use rest-auth?
I use the rest-auth to login my User. But there is a new function there, I want user can lock the screen( user have been login), and then if the user want to unlock the screen, he must type in the password, then the backend should verify the password whether is correct. You know this is not login, this is compare the encrypted password to the database, I don't know the django-rest-auth encrypted type. How to verify the password in this scenario? -
Do I really need to put my website inside an app with Django?
I am trying to build a new big project using Django. Thing is, I want most of the content on the main page 127.0.0.1:8000 and not 127.0.0.1:8000/myapp. I know I can build everything also outside of an app, but is it a good practice ? Or what to do here ? Thanks. -
How a server handles requests asynchronously
I understand this is basic but was not able to connect. Suppose a django-server(hosted on a linux system with 3gb ram and 1vCPU) is serving a request (say R1) which takes around 1700ms. and during this execution at 100ms a request R2 comes in. Here, the server is already busy handling R1. So will R2 have to wait for 1700ms - 100ms = 1600ms? How is this handled? Is there something like instances(as in aws) which solves this? -
Django Response Middleware: Get name of view which created the response
I have simple middleware which checks if the HTML in the response is valid or not. If the HTML is not valid an html is not valid" exception gets raised in development systems. Up to now the xception contains the URL and the validation error. Then the developer sees the URL in the well known yellow and gray django debug page. Maybe I am blind, but if I look at the django debug page, I can't see which of my methods/views created the content with the broken html. Is there a way to add more information to the "html is not valid" exception, to assist the developer? The developer should find the relevant method/view easier. -
Django Python3 End-of-central-directory signature not found
I am able to run the following code (from this tutorial) via my local python3 installation and it works (creates a zip file that I can unzip on my mac using unzip file.zip) import zipfile zip = zipfile.ZipFile(‘Python.zip’, ‘w’) zip.write(‘file1.txt’) zip.write(‘file2.gif’) zip.close() However when I run the following code within a django view: zipped_file = zipfile.ZipFile("csvOutput{}.zip".format(timestamp), 'w') zipped_file.write(sms_file_path) zipped_file.write(mail_maga_file_path) zipped_file.close() I am left with a file that throws the following error when attempted to be unzipped: Archive: csvOutput2018-1-15.zip End-of-central-directory signature not found. Either this file is not a zipfile, or it constitutes one disk of a multi-part archive. In the latter case the central directory and zipfile comment will be found on the last disk(s) of this archive. unzip: cannot find zipfile directory in one of csvOutput2018-1-15.zip or csvOutput2018-1-15.zip.zip, and cannot find csvOutput2018-1-15.zip.ZIP, period. T_T -
python - ImportError: cannot import name 'path'
So, i'm learning django and trying to deploy my first project to pythonanywhere.com. Upon trying to migrate the database, I get the error: ImportError: cannot import name 'path' I've read elsewhere that this a feature of dgango 2.0, but i don't get this error on my local machine that's still using 1.11.2. Any help with this would be most appreciated. -
TypeError: unsupported operand type(s) for -: 'str' and 'str' + ValueError: can only convert an array of size 1 to a Python scalar
i have a code here which is working perfeclty fine but when i add another .csv file to compile it these two errors are showing Traceback (most recent call last): File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\ops.py", line 1202, in na_op result = expressions.evaluate(op, str_rep, x, y, **eval_kwargs) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\computation\expressions.py", line 204, in evaluate return _evaluate(op, op_str, a, b, **eval_kwargs) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\computation\expressions.py", line 64, in _evaluate_standard return op(a, b) TypeError: unsupported operand type(s) for -: 'str' and 'str' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/Dawood/Desktop/ML-PredictElections-master/MLAlgorithms.py", line 505, in <module> fTrain, lTrain = preprocessKNN(trainSet) File "C:/Users/Dawood/Desktop/ML-PredictElections-master/MLAlgorithms.py", line 70, in preprocessKNN normalizedDataset = normalizeData(dataSet, normalizeColoumns) File "C:/Users/Dawood/Desktop/ML-PredictElections-master/MLAlgorithms.py", line 19, in normalizeData col_norm = int(col - col.min()) / int(col.max() - col.min()) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\ops.py", line 1262, in f return self._combine_series(other, na_op, fill_value, axis, level) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\frame.py", line 3944, in _combine_series try_cast=try_cast) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\frame.py", line 3958, in _combine_series_infer try_cast=try_cast) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\frame.py", line 3981, in _combine_match_columns try_cast=try_cast) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\internals.py", line 3435, in eval return self.apply('eval', **kwargs) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\internals.py", line 3329, in apply applied = getattr(b, f)(**kwargs) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\internals.py", line 1377, in eval result = get_result(other) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\internals.py", line 1346, in get_result result = func(values, other) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\ops.py", line 1216, in na_op yrav.fill(yrav.item()) … -
Use Logging SocketHandler with Django
I've configured my logging as so: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'cute':{ 'class': 'logging.handlers.SocketHandler', 'host': '127.0.0.1', 'port': 19996 }, }, 'loggers': { 'django': { 'handlers': ['cute'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, }, } But when I try and log out I get an error in the console: TypeError: an integer is required (got type socket) This seems to be happening within an attempt to pickle the log message, I think. What is going on, and how can I get the SocketHandler to work? -
Look up for a Key in a list of dict and retrieve Value in HTML
How can I lookup for a particular key in a list of dict and return the value in my HTML ? for example my list of dict is : [{44:50},{45:67},{46:68}] and I would like to look up in the dict if the key = i.id then print the value How can I do it ? <tbody> {% for i in app_with_resp %} <tr> <td>{{i.first_name}}</td> <td>{{i.last_name}}</td> <td>17/06/86</td> <td>{{appli_score_list[i.index][i.id]}}</td> <td>{{team_score}}</td> <td> <a href="{% url 'website:CandidateDetails' pk1=current_project_id pk2=i.id %}"> Details</a></td> </tr> {% endfor %} </tbody> -
When defining a new resize rule in wagtail, when the run method it is called?
I'm defining a new resize rule in wagtail for the image tag. class FocalAreaOperation(Operation): vary_fields = ( 'focal_point_width', 'focal_point_height', 'focal_point_x', 'focal_point_y' ) def construct(self, size): # Get width and height width_str, height_str = size.split('x') self.width = int(width_str) self.height = int(height_str) def run(self, willow, image, env): // DO SOMETHING return window When I add or modify the focal area of the image the run method is called, but if I remove the focal area the run method is not called. Does anyone know something about it? Thanks a lot, best regards, nifel87 -
Django chatterbot response is not showing in chat window
i am trying Django chatterbot. when i want to interact with bot, bot's response is not showing in chat window. please check the attached image. There is no error in code when i am running it. i also tried python manage.py makemigrations python manage.py migrate python manage.py migrate django_chatterbot python manage.py train i am unable to figure out the problem. Please help. Thanks. -
Django Page not rendered and not visible
I have cloned a project from Git on my laptop. After the installation of all the requirements, while running the server I found out that a page is not rendered correctly, therefore I can't see the body. More precisely the body is not shown on the webpage. Does anyone know why this happened? This is the code: {% block content %} <section id="consultanta_totala"> <div class="pricing_div" id="consultanta"> <div class="container" id="container_consultanta" > <div class="row" id="text1"> <div class="col-xs-12 offset-xs-0 col-sm-10 offset-sm-1 risk_management"> <br><br> <h4> Risk management </h4> <p> • Crearea structurii de securitate a firmei Dvs.</p> <p>• Verificarea antecedentelor penale ale angajatilor</p> <p>• Verificarea compatibilitatii angajatilor</p> <p>• Verificare loialitatii angajatilor</p> <p>• Norme interne de protectie a firmelor</p> <p>• Profiling</p> </div> <br> </div> <br> <div class="row"> <div class=" col-xs-12 offset-xs-0 col-sm-10 offset-sm-1 verificare"> <h4>Verificarea partenerilor de afaceri</h4> <p> Din punct de vedere al:</p> <p>• Solvabilitatii si seriozitatii persoanei</p> <p>• Corectitudinii obligatiilor contractuale</p> <p>• Intentiilor reale si ale concurentei neloiale</p> <br> <br> </div> </div> </div> </div> </section> {% include 'navbar_bottom.html' %} {% endblock %} PS before posting the item on git it worked properly. Thank you! -
django datetime declaration error
I added the following code in models.py : class Conference(models.Model): conf_name = models.CharField(max_length=250) location = models.CharField(max_length=500) note = models.TextField(max_length=500) note2 = models.TextField(max_length=500) date_from = models.DateField() date_to = models.DateField() time_from = models.TimeField(default='HH:MM:ss') time_to = models.TimeField(default='HH:MM:ss') After that I ran migration commands and I got the following traceback : WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'appadmin' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/1.11/ref/databases/#mysql-sql-mode ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/1.11/ref/databases/#mysql-sql-mode ?: (urls.W005) URL namespace 'dev_app' isn't unique. You may not be able to reverse all URLs in this namespace Operations to perform: Apply all migrations: admin, auth, contenttypes, dev_app, sessions Running migrations: Applying dev_app.0016_auto_20180112_0630...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, … -
Showing and hiding menu items in django based on a non-permissions criteria?
I have a field on a Company called leave_approvers which is a ManyToManyField to Users. The leave_approvers can approve leave of other users in the company they are a leave approver for. They also receive an email when leave is requested. I would now like to show or hide the Approve Leave tab in the main layout based on whether the user is a leave_approver. Is the decision to have a leave_approver field flawed as I should be using the built in authorisation or something like django-guardian. Note that I am sending an email to the leave_approvers and that would mean Can I just make a query in the base.html to check if a user is a leave_approver. How can this be done and surely there is a performance hit? -
get absolute url based on requesting namespace
I have a model in one of my apps. The model returns an absolute url based on the namespace i have specified e.g news as below. @models.permalink def get_absolute_url(self): return 'news:detail', (), {'slug': self.slug} whenever i want to get the url i just call {{ article.get_absolute_url }} and it works perfectly. my trouble comes when i try to access the url while on a different namespace e.g sports. The url redirects me to what i have specified in my get absolute url function. (Below is how i have named my namespaces). urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^news/', include('news.urls', namespace='news')), url(r'^sports/', include('sports.urls', namespace='sports')), ] My question is, how do i dynamically get absolute url of the current namespace? -
Why python3.4 is trying to import module form python2.7
I have this weird problem. I have Django1.11 project using Python 3.4. I wonder why it is trying to import pandas from Python 2.7 File "/usr/local/lib/python3.4/dist-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1471, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "/home/ubuntu/workspace/powrbot/company/models.py", line 3, in <module> import pandas as pd File "/usr/local/lib/python2.7/dist-packages/pandas/__init__.py", line 19, in <module> "Missing required dependencies {0}".format(missing_dependencies)) ImportError: Missing required dependencies ['numpy'] FYI: python --version is Python 3.4.3 I run project like: python manage.py runserver 0:8000 Numpy is already installed in 3.4 Requirement already satisfied: numpy in /usr/local/lib/python3.4/dist-packages -
Django set default for Date field to timezone date
I am trying to use my timezone date as the default for DATE Field but I am unable to do so. For DateTime filed setting the default=timezone.now works perfectly but for Date field I can't figure out any way. time = models.DateTimeField(default=timezone.now) This Works date = models.DateField(default=timezone.now) But this does not work date = models.DateField(default=timezone.now().date) And even this doesn't work. -
django_mongokit 0.2.6 not working in Django 1.11
I installed django_mongokit 0.2.6, but it's not working in Django 1.11. While run server shows below error, $ python manage.py runserver Try using 'django.db.backends.XXX', where XXX is one of: u'base', u'mysql', u'oracle', u'postgresql_psycopg2', u'sqlite3' Error was: cannot import name BaseDatabaseOperations Django : (1.11) Pymongo : (2.5) django-mongokit : (0.2.6) pymongo : (2.8) PyMySQL : (0.8.0) settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'example', }, 'mongodb': { 'ENGINE': 'django_mongokit.mongodb', 'NAME': 'example', }, } -
Call a method that is set to use a specific argument, that is not available
I have a question that I do not know how to solve. I have a list view where I list user in a table with on each row some informations such as first_name last_name and a link to the user detail page. the URL for both page are in the form, list view : .../pk1/, detail view : .../pk1/pk2 where pk1 is project_id and pk2 is user_id On that detail page I make some calculation in order to get a user score and I would like to show that user score on each row in my list view. The problem is that in order to calculate that score it extracts data using pk2 which is not available on my list view since the URL contain only pk1 here is an example of one of the method used to calculate the user score: def get_applicant_team_list(self, format=None, *args, **kwargs): current_team_member = list(Project.objects.get(id = self.kwargs['pk1']).team_id.members.all()) current_applicant = MyUser.objects.get(id =self.kwargs['pk2']) current_team_member.append(current_applicant) applicant_response_list = [] for member in current_team_member: applicant_id = member.id applicant_response = get_user_response(applicant_id) applicant_response_list.append({applicant_id:applicant_response}) return applicant_response_list def get_applicant_info_array(self, format=None, *args, **kwargs): response_list = get_applicant_team_list(self) info_array = get_info_array(response_list) return info_array How can I call my methods for each user in the context of my …