Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add dynamic templates inside a layout template in django?
I want to {%include%} 8 different django templates inside 1 layout without making multiple layouts. My goal is to reduce the total number of .html files inside my template folder. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> {%load static%} <link rel="stylesheet" href="{%static 'web/css/style.css'%}"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous"> </head> <body style='margin: 0px;'> {%include 'web/header.html'%} {%include 'web/personal.html'%} {%include 'web/footer.html'%} </body> </html> views.py def index(request): template_name = 'web/index.html' p = personal.objects.all() return render(request,template_name) def personal(request): template_name = 'web/personal.html' return render(request,template_name) def blog(request): template_name = 'web/blog.html' return render(request,template_name) So here are my templates web/personal.html -> Some HTML web/blog.html -> Some HTML . . . web/n.html -> Some HTML I want these files to get included in my layout file dynamically Thank You. -
How to fit output code of tinymce in my container element?
I am using 'tinymce' to output some codes, but the result is overflowing from its main container, like this: I tried to solve it using css, so what I did was this the container that wrapped this code is 'pre.language-markup', so I added the following code: .article-content { # container of pre.language-markup white-space: pre-line; position: relative; */ } pre.language-markup{ position: absolute; max-width: 100% !important; } as a result it added some scroll and decreased abit of its width but yet didn't solve the problem, I usually use that above code to fit a child element in parent, but how do I do this? please help me thank you -
Django - installing mysqlclient error: mysqlclient 1.3.13 or newer is required; you have 0.9.3
I've trawled the forums but cannot find an answer or even any documentation on this. On running the command: python manage.py inspectdb I get the error: mysqlclient 1.3.13 or newer is required; you have 0.9.3 I have tried all the suggested fixes including: -upgrading pip -installing a different wheel (32 bit instead of 64), namely mysqlclient-1.4.2-cp37-cp37m-win32.whl with the command pip install mysqlclient-1.4.2-cp37-cp37m-win32.whl (this works fine without an error but doesn't do the job required!) My objective is to simply connect a legacy mysql database (running inside of XAMPP and myphpadmin) to Django. I've followed the documentation which misses out the need to install mysqlclient, and have got stuck at this point. -
How to manually populate a relational model in Django REST
I'm still new to Django and DRF. I have 2 models (Policy and Rescue) and Rescue is related to Policy by the Foreign Key policy_id. I have no issue to POST a JSON message and get Policy populated with the request data by CreateView. However, the 2nd model Rescue needs be populated based on some calculations from the JSON data POSTed to the Policy. Rescue cannot be POSTed beforehand. I tried hard but had no clue to do so. Is this something to do with nested serializer or something else? I've tried to Can I try this way: inside the class CreateView: class CreateView(generics.CreateAPIView): def create(self, request, *args, **kwargs): my_serializer = self.get_serializer(data=request.data) ... # get a policy object based on 'policy_id' against serializer my_policy = Policy.objects.get(policy_id=my_serializer.data['policy_id']) ... ... # some calculations to work out a rescue id, and will be returned and saved. Rescue.objects.create(rescue_id='QD1234', policy=my_policy) -
How to properly manage multiple databases in django and handle large queries
I have a django based web app that uses two databases. One is for user data (username ,pwds etc) and it is managed through django models. Second DB contains the actual and sensitive data and it is a redshift database. First landing page of my app is a dashboard that pulls in data from redshift and visualizes it in graphs and tables. My only problem is the speed of the application. Dashboard takes almost one minute to load all the data. Time taking activity is query and pandas data frames. What is the best way to deal with this problem and what is the best possible way to optimize the app. Should I divide the dashboard into separate views and load them async? I am also thinking about using redis for same data queries P.S: i am using pyodbc for redshift. -
mySQL legacy database with Django - error due to incorrect version of mysqlclient using XAMPP
I am getting the following error on trying to install mysqlclient. ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. I used the following stackoverflow q/a to help me, but got the above version error. Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' The official Django docs are very sparse on their instructions and do not even mention the need to install mysql client. I also notice that there are various different suggestions. I have two questions: What is the best way to connect an existing/legacy mysql database to Django (what steps should I follow before being able to type the final command: python manage.py inspectdb What is the best way to use an existing mysql database and use it with Django. Note: I currently have XAMPP installed and hope to be able to connect to it on a local host from there. -
How can I add additional fields to my Model in Django
I have a model that looks like this: class Audience(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name.title().replace('_', ' ') class Meta: ordering = ['name'] When I use it in another model, I get a list of all the Audiences in the DB. audience = models.ForeignKey(Audience) I'm trying to add in a custom value to this list of items from the DB like 'Other'. How can I do this? -
i can't COPY Pipfile Pipfile.lock in my directory project in docker
Step 5/7 : COPY Pipfile Pipfile.lock /code/hello_project COPY failed: stat /var/lib/docker/tmp/docker-builder537134578/Pipfile: no such file or directory -
Why do heroku logs show database login attempts with toggling ports? (hackers?)
Today our site went down in a massive way. Checking the logs, we saw a bunch of database activity whereby the connection was being made from different ports. Is this hacker activity? Does the fact they they have the production database username mean that the credentials were compromised? Our team is new to security / infrastructure, so any and all advice to take on next steps if this is hacker activity would be much appreciated. 2019-04-12T17:10:38.046660+00:00 app[web.2]: 2019-04-12 17:10:38.046 49 LOG C-0x7f1ee5975cb0: db1/ProdDBUsername@127.0.0.1:42384 closing because: client close request (age=59) 2019-04-12T17:10:38.046775+00:00 app[web.2]: 2019-04-12 17:10:38.046 49 LOG C-0x193efc0: db1/ProdDBUsername@127.0.0.1:42386 closing because: client close request (age=59) 2019-04-12T17:10:38.046844+00:00 app[web.2]: 2019-04-12 17:10:38.046 49 LOG C-0x1937e70: db1/ProdDBUsername@127.0.0.1:42390 closing because: client close request (age=59) 2019-04-12T17:10:38.047933+00:00 app[web.2]: 2019-04-12 17:10:38.047 49 LOG C-0x1954a48: db1/ProdDBUsername@127.0.0.1:42448 closing because: client close request (age=55) 2019-04-12T17:10:38.048101+00:00 app[web.2]: 2019-04-12 17:10:38.048 49 LOG C-0x193e070: db1/ProdDBUsername@127.0.0.1:42452 closing because: client close request (age=54) 2019-04-12T17:10:38.048216+00:00 app[web.2]: 2019-04-12 17:10:38.048 49 LOG C-0x7f1ee5973e10: db1/ProdDBUsername@127.0.0.1:42456 closing because: client close request (age=54) 2019-04-12T17:10:38.048284+00:00 app[web.2]: 2019-04-12 17:10:38.048 49 LOG C-0x1953660: db1/ProdDBUsername@127.0.0.1:42462 closing because: client close request (age=54) 2019-04-12T17:10:38.048553+00:00 app[web.2]: 2019-04-12 17:10:38.048 49 LOG C-0x7f1ee5972280: db1/ProdDBUsername@127.0.0.1:42484 closing because: client close request (age=52) 2019-04-12T17:10:38.048678+00:00 app[web.2]: 2019-04-12 17:10:38.048 49 LOG C-0x193c1d0: db1/ProdDBUsername@127.0.0.1:42486 closing because: client close request … -
Editing form with FileField removes the file
i have a ModelForm with dynamically generated fields . Everything works fine, but the editing. The input[type=file] loses its file and instead, it puts it in the <a href="/path/to/file"> called "currently". When i submit the form i need those files in request.FILES. I wanted to handle it with Javascript, but it is not possible to change the value of input[type=file]. I would post some code, but it is kinda long so i prefer not to. -
Passing kwargs to nested forms in Django inline formsets
I'm new to Django and I am trying to implement a change tracking system that allows users to assign change types, reasons, and comments to any changes that occur on item instances of a Django model class. I modeled my problem after this example https://github.com/philgyford/django-nested-inline-formsets-example I have a model FK hierarchy of Item -> ItemHistory -> Item Change Reasons (can be multiple reasons per change). I would like to see all changes for a given item and all reasons and comments for all changes for that item in the same page. For the change type and reason, I have implemented a dependent dropdown using JQuery - the queryset for change reasons depend on the selection for change type. The problem I'm facing is displaying the saved change types and change reasons for an existing change on the update view. I'm trying to pass in different querysets to the ChangeReasonsForm form, which are implemented as nested fields in the BaseVersionReasonsFormset formset. I able to pass the querysets from the view up to BaseVersionReasonsFormset but can't seem to figure out how to pass it to the nested forms. Appreciate any help and suggestions in advance! Forms.py class ChangeReasonsForm(forms.ModelForm): change_reason = forms.ModelChoiceField(queryset=ChangeReason.objects.none()) class … -
How to include and activate virtual environment for Django project on apache server
I'm trying to host my Django project with a virtual environment on an apache server. I have activated my virtual environment on the server (and I know this because the virtual environment name is given as a prefix to the terminal prompt). However, it doesn't seem to be working? I have Python 3.6 installed on my virtual environment, but Python 2.7 is the only one that shows when typing and entering 'python' - this is probably because I used 'apt get python-pip' at one point. I have tried editing the server config with: nano /etc/apache2/sites-available/mysite.conf <VirtualHost *:80> ServerName YOURHOSTNAME ErrorLog ${APACHE_LOG_DIR}/mysite-error.log CustomLog ${APACHE_LOG_DIR}/mysite-access.log combined WSGIDaemonProcess mysite processes=2 threads=25 python-path=/var/www/project/mysite python-home=/var/www/project/env WSGIProcessGroup mysite WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py Alias /robots.txt /var/www/mysite/static/robots.txt Alias /favicon.ico /var/www/mysite/static/favicon.ico Alias /static/ /var/www/mysite/static/ Alias /static/ /var/www/mysite/media/ <Directory /var/www/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/mysite/static> Require all granted </Directory> <Directory /var/www/mysite/media> Require all granted </Directory> I have tried changing python-home and python-path, but to no avail. My virtual environment is located in the 'project/env' folder. 'manage.py' is in 'project/mysite'. Other settings, including 'settings.py' I have put in 'project/mysite/mysite'. Any help would be greatly appreciated. -
Migrate Error: Django/Postrgres: DataError Numeric Precision 10000 must be between 1 and 1000
When trying to migrate changes for the first time into my Postgresql DB, I encounter this error. I can successfully migrate and start my app when using the standard SQLite db that DJango comes with. However, when trying to connect to my Postgresql I've been having trouble. I have my Postgresql open with pgAdmin and the databases connected with no data in them. I also have deleted all entries in my django app in case an import error was causing the error. $ docker-compose run web python manage.py migrate Starting src_db_1 ... done Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, courses, products, sessions Running migrations: Applying products.0001_initial...Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) psycopg2.DataError: NUMERIC precision 10000 must be between 1 and 1000 LINE 1: ...r(120) NOT NULL, "description" text NULL, "price" numeric(10... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() ... raise dj_exc_value.with_traceback(traceback) from exc_value File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) django.db.utils.DataError: NUMERIC precision 10000 must be between 1 and 1000 LINE 1: ...r(120) NOT … -
IOError: [Errno 32] Broken pipe with Popen to run command
I've been trying to implement with python 2.7 a function to pass a command to cli to convert videos with ffmpeg, until now works almost great, the problem is that sometimes throws IOError: [Errno 32] Broken pipe and I'm not shure why it's happening. Can you help me with this? This is my function to pass a command to the cli: def _cli(cmd): # TODO validate function errors = False import subprocess try: p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdoutdata, stderrdata = p.communicate() if p.wait() != 0: # Handle error / raise exception # errors used to know conversion success or not errors = True print stderrdata return stdoutdata, stderrdata, errors except OSError as e: print 'error' traceback.print_exc() return e.strerror, e.strerror, errors This is how I call it: c = '/usr/bin/ffmpeg -hide_banner -nostats -i /home/user/original/390f8455-8657-4452-9fd9-0167d1025389.flv -c:v libx264 -c:a aac -strict -2 /home/user/original/390f8455-8657-4452-9fd9-0167d1025389.mp4' print 'Converting command: %s' % c stdoutdata, stderrdata, errors = _cli(c if errors: print 'Converting video error' # obj is django object obj.convert_status = 'error' obj.msg = stderrdata And this is the exception: Traceback (most recent call last): File "/home/user/myapp/env/local/lib/python2.7/site-packages/rq/worker.py", line 799, in perform_job rv = job.perform() File "/home/user/myapp/env/local/lib/python2.7/site-packages/rq/job.py", line 600, in perform self._result = self._execute() File "/home/user/myapp/env/local/lib/python2.7/site-packages/rq/job.py", … -
raw_id_fields does not show all the fields with the magnifying glass button
I have a Model with multiple ForeignKey fields, and I want all of these fields to be shown as a raw_id_fields widget, that is, with the magnifying glass button. Tried salmonella, but I get errors in rendering of the Django Suit template. Tried raw_id_fields = ('tramite', 'asignado_a', 'revisado_por', 'supervisado_por', 'marginado_por', 'recibido_por', 'digitalizada_por', 'firma', ) Also try to send a list raw_id_fields = ['tramite', 'asignado_a', 'revisado_por', 'supervisado_por', 'marginado_por', 'recibido_por', 'digitalizada_por', 'firma', ] but nothing... I am using Python 2.7 and Django 1.8.14 class PeticionAdmin(admin.ModelAdmin): raw_id_fields = ('tramite', 'asignado_a', 'revisado_por', 'supervisado_por', 'marginado_por', 'recibido_por', 'digitalizada_por', 'firma', ) list_filter = ['estado','activo'] search_fields = ['id',] list_display = ('id','tramite','tipo', 'producto', 'fecha_recepcion','notaria','subtotal', 'complejidad' ,'fecha_entrega', 'fecha_vencimiento', 'estado' ,'activo') inlines = [ DocumentoDigitalizadoInline ] admin.site.register(Peticion, PeticionAdmin) I only wish that all these fields with ForeignKey show the magnifying glass button and the window to associate the ForeignKey PD: Sorry for my English:) -
Django "django.core.exceptions.AppRegistryNotReady: Apps aren’t loaded yet.” and production server restart
Urgent, please help! I tried to restart my production server and got this error: “django.core.exceptions.AppRegistryNotReady: Apps aren’t loaded yet.” I reset git to a steady version, and the error is still occurring. Does anyone have any idea what could have suddenly caused this? Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/ec2-user/MYVENV/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/ec2-user/MYVENV/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ec2-user/MYVENV/lib/python3.6/site-packages/django/core/management/__init__.py", line 216, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/ec2-user/MYVENV/lib/python3.6/site-packages/django/core/management/__init__.py", line 36, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/home/ec2-user/MYVENV/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/home/ec2-user/MYVENV/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 10, in <module> from django.db.migrations.autodetector import MigrationAutodetector File "/home/ec2-user/MYVENV/lib/python3.6/site-packages/django/db/migrations/autodetector.py", line 11, in <module> from django.db.migrations.questioner import MigrationQuestioner File "/home/ec2-user/MYVENV/lib/python3.6/site-packages/django/db/migrations/questioner.py", line 9, in <module> from .loader import MigrationLoader File "/home/ec2-user/MYVENV/lib/python3.6/site-packages/django/db/migrations/loader.py", line 8, in <module> from django.db.migrations.recorder import MigrationRecorder File "/home/ec2-user/MYVENV/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 9, in <module> class MigrationRecorder: File "/home/ec2-user/MYVENV/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 22, in MigrationRecorder class Migration(models.Model): File … -
How important is PyYAML when deploying in gooogle app engine with Django?
Recently I tried to deploy my django app in google app engine (standard environment - Python version 3.7 - Django version 2.0.3) but I found a problem. As a previous step to do the deploy I run: pip freeze > requirements.txt But at the time of deploy this error was generated: Error message: `pip_download_wheels` had stderr output: Failed building wheel for PyYAML ERROR: Failed to build one or more wheels error: `pip_download_wheels` returned code: 1. When I realized that the error was due to PyYAML I tried to modify the version in the requirements.txt file, but it didn't work. As last step I opted to remove PyYAML from my requirements.txt file and in this case it worked. The application is deployed and working. However my question is: Is there a problem with having deployed without including PyYAML in the requirements.txt? -
Django DLL load failed: The specified module could not be found
Hello i m new at django. I installed all moduoles from anaconda. Then created a web application with django-admin startproject My project crated successfully. No problem Then i tried to run that project at localhost to see is everything okay or not. And i run that code in command line python manage.py runserver And i get that error: Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0x00000221B6D45A60> Traceback (most recent call last): File "C:\Users\Sercan\Anaconda3\lib\site- packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Sercan\Anaconda3\lib\site- packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\Sercan\Anaconda3\lib\site- packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\Sercan\Anaconda3\lib\site- packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\Sercan\Anaconda3\lib\site- packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Sercan\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Sercan\Anaconda3\lib\site- packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\Sercan\Anaconda3\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Sercan\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _ find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Sercan\Anaconda3\lib\site- packages\django\contrib\auth\models.py", line 2, in … -
Combine two tables/models with same primary key in Django
I have two tables with the same primary key. ip mac 15.30.173.88 48-C0-09-1F-9B-54 27.73.24.156 4E-10-A3-BC-B8-9D 29.37.135.153 CD-00-60-08-56-2A 45.252.59.153 23-CE-D3-B1-39-A6 ip type owner 11.85.19.194 laptop John Doe 27.73.24.156 server XYZ Department 29.37.135.153 VM Mary Smith 56.32.183.230 printer ZWV Department The first table is automatically refreshed every minute. I can't change the database structure or the script that populates it. In a view, I would like to display a table like this: ip mac type owner Alert 15.30.173.88 48-C0-09-1F-9B-54 Unauthorized 45.252.59.153 23-CE-D3-B1-39-A6 Unauthorized 11.85.19.194 laptop John Doe Down 56.32.183.230 printer ZWV Department Down 27.73.24.156 4E-10-A3-BC-B8-9D server XYZ Department OK 29.37.135.153 CD-00-60-08-56-2A VM Mary Smith OK How can I model this? Should I make one of the two primary keys a foreign key into the other one? Once the code is in operation, there will be lots of data, so I want to make sure it's fast enough. What is the fastest way to retrieve the data? -
Django: correct way to pass a list to template on AJAX Done
I've 2 columns of radio buttons: 1) Sizes, 2) Quantities. I need to add a third one called: 3) Prices. This Prices column will be generated thourgh AJAX. I'll make an AJAX call to my view prices that return a list of prices: <class 'list'> [70, 90, 130, 160, 240, 400, 550] On AJAX's done or success, I need to pass that list to the template. I want to be able to access it's value like: prices.0, prices.1, prices.2, etc. So I can do {{ price.0 }} ... views.py from django.http.response import JsonResponse def prices(request): size_selected = request.GET.get("size_selected") c_slug = 'stickers' product_slug = 'stickers-transparentes' prices = list(costo_de_los_productos.objects.filter(category=Category.objects.get(slug=c_slug), product=Product.objects.get(slug=product_slug), size=size_selected).values_list("price",flat=True)) return JsonResponse({'prices': prices}) AJAX's call: <script> function get_prices() { var size_selected = $('input[name=size]:checked').val(); req = $.ajax({ url: "/prices/", data: { // Pass parameters in separate object size_selected: size_selected {#c_slug: {{ product.category.slug }},#} {#product_slug: {{ product.slug }}#} }, }); $('#prices').fadeOut(500).fadeIn(1000); req.done(function (response) { $('#prices').append(response.prices); }); } /// $("document").ready(function () { $('input[name=size]').change(function () { get_prices(); }); }); /// </script> -
Celery/Django can't set multiple queues
I want to create a multiple queues for different tasks. For example emailqueue to sending emails or pipedrive queue to sync tasks with pipedrive API so email does not have to wait until all pipedrives are synced and vice versa. I'm new in routing and I tried two approaches to create queues but none of them seemes to work. 1. This is a preffered approach. I tried to define queue inside @task decorator @task(bind=True, queue='pipedrivequeue') def backsync_lead(self,lead_id): 2. settings.py CELERY_ROUTES = { # tried CELERY_TASK_ROUTES too 'pipedrive.tasks.*': {'queue': 'testqueue'}, ... } In both cases, when I run celery worker manually, I see only one default celery queue. (project) milano@milano-PC:~/PycharmProjects/project$ celery -A project.celery worker -l info -------------- celery@milano-PC v4.2.2 (windowlicker) ---- **** ----- --- * *** * -- Linux-4.15.0-47-generic-x86_64-with-Ubuntu-18.04-bionic 2019-04-12 17:17:05 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: project:0x7f3b47f66cf8 - ** ---------- .> transport: redis://localhost:6379// - ** ---------- .> results: redis://localhost/ - *** --- * --- .> concurrency: 12 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . project.apps.apis.pipedrive.tasks.backsync_all_stages . project.apps.apis.pipedrive.tasks.backsync_lead As you can see in … -
How to test redirect if form.is_valid()
I've builded a view who posts data and redirect to contact/success. My problem is how to test the redirection with assertRedirects? My Views.py: def emailView(request): form = ContactForm(request.POST) if form.is_valid(): gender = form.cleaned_data['gender'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] gender = request.POST['gender'] first_name = request.POST['first_name'] last_name = request.POST['last_name'] context = { 'form': form, } return redirect('success_contact') 'success_contact' is redirecting to URL 'contact/success'. In my tests.py I've tried achieve it this way: form_data = {'gender': '1, 'first_name': 'Luke', 'last_name': 'Skywalker'} form = ContactForm(form_data) response = self.client.post('/contact', form_data) self.assertRedirects(response, '/contact/success/', status_code=302, target_status_code=200) Unfortunately I just got this AssertationError: Traceback (most recent call last): File "/Users/user/Django/contactproj/contact/tests/test_views.py", line 126, in test_view_form_valid target_status_code=200) File "/Users/user/anaconda3/envs/contactproj/lib/python3.6/site-packages/django/test/testcases.py", line 283, in assertRedirects % (response.status_code, status_code) AssertionError: 301 != 302 : Response didn't redirect as expected: Response code was 301 (expected 302) -
CreateWithInlinesView validation in form
Does anyone know how to validate form when CreateWithInlinesView from the Django Extra Views is used? Surprisingly enough def clean(self) and def clean_name_of_the_field ,methods dont work there. I have checked it on function based view , so that they really dont work in CreateWithInlinesView . I could still use validators and def clean() in model, but i would prefer to do it in forms... If you had any experience in CreateWithInlinesView validation -please let me know. Thank you! -
How to serialize multiple models into one serializer for hierarchy structure using Django Rest Framework?
I have four models where I need to serialize three into one for my API. I can get the individual serializers to work as expected, but when combining them into one, I do not get the result I was expecting to see. models.py class President(models.Model): name = models.CharField('Name', max_length=50,) staff = models.ManyToManyField('Member',) def __str__(self): return self.name """ user creates a new member in this model below if a new member is an employee, the object is copied into the Employee model and the user chooses the manager of the employee in the manager field if a new member is a manager, the object is copied into the Manager model """ class Member(models.Model): president = models.ForeignKey( President, on_delete=models.CASCADE, related_name='members', ) manager = models.ForeignKey( 'Manager', on_delete=models.CASCADE, related_name='manager', ) name = models.CharField('Name', max_length=50,) email = models.EmailField('Email Address',) title = models.CharField('Title', max_length=50,) staff_type = ( ('Manager', 'Manager'), ('Employee', 'Employee'), ) def __str__(self): return self.name class Employee(models.Model): president = models.ForeignKey( President, on_delete=models.CASCADE, related_name='employeePresident' ) manager = models.ForeignKey( 'Manager', on_delete=models.CASCADE, related_name='employeeManager' ) name = models.CharField('Name', max_length=50,) email = models.EmailField('Email Address',) title = models.CharField('Title', max_length=50,) def __str__(self): return self.name class Manager(models.Model): president = models.ForeignKey( President, on_delete=models.CASCADE, related_name='managerPresident' ) name = models.CharField('Name', max_length=50,) department = models.CharField('Department', max_length=50,) def … -
Oracle Databases with ldap, How we will provide Django connection DATABASE json in settings
I have a oracle database JDBC connection string jdbc:oracle:thin:@ldap://<LDAP Server String>/<Database Service Name><LDAP Context> is in format. How we will use these parameters in Django application as a database?