Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is there both a create_user and a _create_user method in django.contrib.auth.models.UserManager
In the source for django, there is a UserManager class whose job (as far as I understand) is to create users according to a number of received parameters and save them to the database. The class accomplishes this with the use of two methods. One method create_user and one method _create_user, the latter is called by the former. My question is, why the need for two methods? Why not simply have one that does the exact same thing? Like this: def create_user(self, username, email=None, password=None, **extra_fields): """ Creates and saves a User with the given username, email and password. """ now = timezone.now() if not username: raise ValueError('The given username must be set') email = self.normalize_email(email) user = self.model(username=username, email=email, is_staff=False, is_active=True, is_superuser=False, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user -
Django HttpResponse with application/zip type corrupt
When I log the request in my frontend, I see characters like this: PKS/L'�I�rrQUsers/my/local/dev_env/django_app/webapp/webapp/csvs/mailMagaOutput.csv会員id,e-mail,お名前(姓),お名前(名),購入回数 And the response logs the rest of the CSV files I am trying to log as the way they should look... Does this mean that I am not properly encrypting them? The response I am sending (from Django): zipped_file = zipfile.ZipFile("csvOutput.zip", 'w') zipped_file.write(sms_file_path) zipped_file.write(mail_maga_file_path) zipped_file.close() response_file = open('csvOutput.zip', 'rb') response = HttpResponse(response_file, content_type="application/zip") response['Content-Disposition'] = 'attachment; filename=csvOutput.zip"' If I try to unzip the file that python generates on the server, it works just fine. When I try to unzip it locally, I am getting: tar: Too-small extra data: Need at least 4 bytes, but only found 3 bytes -
Wagtail installation: Wagtail command not found
Simple question. Trying to install wagtail. As docs tells, installed wagtail pip package. tigran@tigran:~/projects/website$ pip install wagtail Collecting wagtail Using cached wagtail-1.13.1-py2.py3-none-any.whl Collecting html5lib<1,>=0.999 (from wagtail) Using cached html5lib-0.999999999-py2.py3-none-any.whl Collecting Django<1.12,>=1.8.1 (from wagtail) Using cached Django-1.11.9-py2.py3-none-any.whl Collecting djangorestframework<3.7,>=3.1.3 (from wagtail) Using cached djangorestframework-3.6.4-py2.py3-none-any.whl Collecting django-treebeard<5.0,>=3.0 (from wagtail) Collecting Pillow>=2.6.1 (from wagtail) Using cached Pillow-5.0.0-cp27-cp27mu-manylinux1_x86_64.whl Collecting Unidecode>=0.04.14 (from wagtail) Using cached Unidecode-1.0.22-py2.py3-none-any.whl Collecting django-taggit<1.0,>=0.20 (from wagtail) Using cached django_taggit-0.22.2-py2.py3-none-any.whl Collecting django-modelcluster<4.0,>=3.1 (from wagtail) Collecting Willow<1.1,>=1.0 (from wagtail) Using cached Willow-1.0-py2.py3-none-any.whl Collecting beautifulsoup4>=4.5.1 (from wagtail) Using cached beautifulsoup4-4.6.0-py2-none-any.whl Collecting requests<3.0,>=2.11.1 (from wagtail) Using cached requests-2.18.4-py2.py3-none-any.whl Collecting six (from html5lib<1,>=0.999->wagtail) Using cached six-1.11.0-py2.py3-none-any.whl Collecting webencodings (from html5lib<1,>=0.999->wagtail) Using cached webencodings-0.5.1-py2.py3-none-any.whl Collecting setuptools>=18.5 (from html5lib<1,>=0.999->wagtail) Using cached setuptools-38.4.0-py2.py3-none-any.whl Collecting pytz (from Django<1.12,>=1.8.1->wagtail) Using cached pytz-2017.3-py2.py3-none-any.whl Collecting idna<2.7,>=2.5 (from requests<3.0,>=2.11.1->wagtail) Using cached idna-2.6-py2.py3-none-any.whl Collecting urllib3<1.23,>=1.21.1 (from requests<3.0,>=2.11.1->wagtail) Using cached urllib3-1.22-py2.py3-none-any.whl Collecting certifi>=2017.4.17 (from requests<3.0,>=2.11.1->wagtail) Using cached certifi-2017.11.5-py2.py3-none-any.whl Collecting chardet<3.1.0,>=3.0.2 (from requests<3.0,>=2.11.1->wagtail) Using cached chardet-3.0.4-py2.py3-none-any.whl Installing collected packages: six, webencodings, setuptools, html5lib, pytz, Django, djangorestframework, django-treebeard, Pillow, Unidecode, django-taggit, django-modelcluster, Willow, beautifulsoup4, idna, urllib3, certifi, chardet, requests, wagtail Successfully installed Django-1.11.9 Pillow-5.0.0 Unidecode-1.0.22 Willow-1.0 beautifulsoup4-4.6.0 certifi-2017.11.5 chardet-3.0.4 django-modelcluster-3.1 django-taggit-0.22.2 django-treebeard-4.2.0 djangorestframework-3.6.4 html5lib-0.999999999 idna-2.6 pytz-2017.3 requests-2.18.4 setuptools-38.4.0 six-1.11.0 urllib3-1.22 wagtail-1.13.1 webencodings-0.5.1 Creating project tigran@tigran:~/projects/website$ wagtail start website … -
Google App Engine Flexible
I'm trying to use CodeShip and deploy to Google App Engine. Using this guide. I'm getting this error: appcfg does not support deploying to the Flexible environment Im wondering if I might have done something wrong or if its in CodeShip. Does CodeShip have support Google App Engine Flexible? -
Create SOAP requst by zeep
I'm working on WSDL. I need to create SOAP request using by zeep package. So I implemented the code that from zeep import Client service = Client('https://api.mindbodyonline.com/0_5_1/ClientService.asmx?wsdl') request = service.service.GetClientServices But I could not move on. Because I could not login through this request and pass parameters. I want to fill following all requirement through this request. could anyone tell me that how to pass all this parameters by this request. This is HTTP headers SOAPAction: "http://clients.mindbodyonline.com/api/0_5_1/GetClientServices" Content-Type: text/xml; charset="utf-8" -
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?