Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-storages upload to S3 closes server with no error
I'm using Django 2.x and django-storages to upload media files to the S3 Bucket. My model is like class Media(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True, default=None) file = models.FileField(upload_to=get_media_upload_path) The Django settings have DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_STORAGE_BUCKET_NAME = os.environ.get('S3_STORAGE', 'test-bucket') AWS_DEFAULT_ACL = 'public-read' and the environment variable is set for AWS_ACCESS_KEY_ID=my-key AWS_SECRET_ACCESS_KEY=my-secret When I upload a file from the postman, it closes the server without any error. I tried debugging DRF Serializer's save method def save(self, **kwargs): log.info('Saving with kwargs: {}'.format(kwargs)) new = super().save(**kwargs) log.info('Saved: {}'.format(new)) return new It prints the first line, but no output after the super().save() line. Removing django-storages configuration from the settings file is working fine and uploading files in the local directory. -
I want to change the display of SnippetChooserPanel of BlogIndexPage by Client in Wagtail site
I want to change the display of SnippetChooserPanel of BlogIndexPage by Client. However, I don't have an idea to change the display. I want to display only the contract of the same client. But now all contracts are visible. What I investigated: Filter query set wagtail-ModelAdmin.get_queryset() def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(client=request.client) -
Couldn't set up mod_wsgi for my Apache and Django
Need guides to set up mod_wsgi on Windows for my XAMPP Apache and Django project. I'm using Python 3.7.3(win32), Django 2.2.3 and Apache 2.4.39(win64). Errors appear when after i set "MOD_WSGI_APACHE_ROOTDIR=C:\xampp\apache\bin" and pip install mod_wsgi. I'm not sure what i did wrong at this step? Read about Visual Code 14.0. Downloaded it and i still got error. ERROR: Command errored out with exit status 1: command: 'c:\program files (x86)\python37-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\CHEEHO~1\\AppData\\Local\\Temp\\pip-install-41s5l0d2\\mod-wsgi\\setup.py'"'"'; __file__='"'"'C:\\Users\\CHEEHO~1\\AppData\\Local\\Temp\\pip-install-41s5l0d2\\mod-wsgi\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\CHEEHO~1\AppData\Local\Temp\pip-record-um32pphd\install-record.txt' --single-version-externally-managed --compile cwd: C:\Users\CHEEHO~1\AppData\Local\Temp\pip-install-41s5l0d2\mod-wsgi\ Complete output (33 lines): c:\program files (x86)\python37-32\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'bugtrack_url' warnings.warn(msg) running install running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\mod_wsgi copying src\__init__.py -> build\lib.win32-3.7\mod_wsgi creating build\lib.win32-3.7\mod_wsgi\server copying src\server\apxs_config.py -> build\lib.win32-3.7\mod_wsgi\server copying src\server\environ.py -> build\lib.win32-3.7\mod_wsgi\server copying src\server\__init__.py -> build\lib.win32-3.7\mod_wsgi\server creating build\lib.win32-3.7\mod_wsgi\server\management copying src\server\management\__init__.py -> build\lib.win32-3.7\mod_wsgi\server\management creating build\lib.win32-3.7\mod_wsgi\server\management\commands copying src\server\management\commands\runmodwsgi.py -> build\lib.win32-3.7\mod_wsgi\server\management\commands copying src\server\management\commands\__init__.py -> build\lib.win32-3.7\mod_wsgi\server\management\commands creating build\lib.win32-3.7\mod_wsgi\docs copying docs\_build\html\__init__.py -> build\lib.win32-3.7\mod_wsgi\docs creating build\lib.win32-3.7\mod_wsgi\images copying images\__init__.py -> build\lib.win32-3.7\mod_wsgi\images copying images\snake-whiskey.jpg -> build\lib.win32-3.7\mod_wsgi\images running build_ext building 'mod_wsgi.server.mod_wsgi' extension creating build\temp.win32-3.7 creating build\temp.win32-3.7\Release creating build\temp.win32-3.7\Release\src creating build\temp.win32-3.7\Release\src\server C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.22.27905\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -IC:\xampp\apache\bin/include "-Ic:\program files (x86)\python37-32\include" "-Ic:\program files (x86)\python37-32\include" "-IC:\Program Files … -
unable to open pdf file in django
my file directory is : site -search -factfinder -pdf_reports test.pdf in my base.html file, i have : <a class="linkbtn" href='/factfinder/pdf_reports/{{ab.0.file_name}}.pdf' >open pdf</a> but on clicking the link, i get redirected to http://localhost:8000/factfinder/pdf_reports/test.pdf and i get an error stating page not found. i also get following details to error : Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ elasticsearch_results/ [name='elasticsearch_results'] pdf_open [name='pdf_open'] pdf_open_2 [name='pdf_open_2'] rating [name='rating'] parse_pdf [name='parse_pdf'] filters [name='filters'] run_model [name='run_model'] The current path, factfinder/pdf_reports/test.pdf, didn't match any of these. -
Get UID and token obtain from password reset in react form
I am working on password reset and I have used django rest-auth, I have successfully got the token and uid from email link by hitting rest-auth/password/reset/, but for to confirm I want the token and uid in react form so I can change it how can I get the uid and token which the rest auth return in email link in react js form axios.post('http://127.0.0.1:8000/rest-auth/password/reset/',payload) .then(res=>{ console.log(res) }) .catch(err=>{ console.log(err) }) its working perfect and it returns me: http://127.0.0.1:8000/rest-auth/password/reset/confirm/MQ/594-5faaa46be4277e6a1879/ how can I get the uid and token from url in react form? -
DJANGO - ModuleNotFoundError No module named "[MY PROJECT, not an app]"
Lots of questions about it here, but nothing seems to answer mine. I am trying to host my django website in linux server with apache, using the mod_wsgi. I am getting the error: ModuleNotFoundError: No module named 'bnboats_webproject': /home/bnboats/public_html/python/bnboats_webproject/wsgi.py The mentioned 'bnboats_webproject' is my project, which has settings, wsgi, urls ... Not an app to be installed. My folder structure is like this: - PYTHON/ - bnboats_webproject/ (my project) - bnboats_app/ (my app) - venv/ (my virtual env) - mod_wsgi-4.6.5/ - manage.py - ... In httpd.conf, I have entered: WSGIScriptAlias / /home/bnboats/public_html/python/bnboats_webproject/wsgi.py WSGIDaemonProcess bnboats.com python-path=/home/bnboats/public_html/python:/home/bnboats/public_html/python/venv WSGIProcessGroup bnboats.com <Directory /home/bnboats/public_html/python/bnboats_webproject> <Files wsgi.py> Require all granted </Files> </Directory> It returns a 500 Internal Error, the host company debugged for me and sent me this log: [Thu Aug 22 11:38:29.461405 2019] [cgi:error] [pid 28312] [client xxx.xx.xxx.xx] AH01215: Traceback (most recent call last):: /home/bnboats/public_html/python/bnboats_webproject/wsgi.py [Thu Aug 22 11:38:29.461575 2019] [cgi:error] [pid 28312] [client xxx.xx.xxx.xx] AH01215: File "/home/bnboats/public_html/python/bnboats_webproject/wsgi.py", line 20, in <module>: /home/bnboats/public_html/python/bnboats_webproject/wsgi.py [Thu Aug 22 11:38:29.461627 2019] [cgi:error] [pid 28312] [client xxx.xx.xxx.xx] AH01215: application = Cling(get_wsgi_application()): /home/bnboats/public_html/python/bnboats_webproject/wsgi.py [Thu Aug 22 11:38:29.461713 2019] [cgi:error] [pid 28312] [client xxx.xx.xxx.xx] AH01215: File "/usr/lib64/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application: /home/bnboats/public_html/python/bnboats_webproject/wsgi.py [Thu Aug 22 11:38:29.461749 2019] [cgi:error] [pid 28312] [client … -
Django Module for FusionCharts: CORB issue
I am trying to use a simple Django Module for FusionCharts example given in the documentation but I am getting CORB issue. I am using exact code and it seems to run fine, but instead of graph I get this error: Cross-Origin Read Blocking (CORB) blocked cross-origin response https://fusioncharts.github.io/fusioncharts-jquery-plugin/ with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details. -
How do I create a single instance of a model through multiple html pages?
I've just gotten started with Django and I'm having trouble creating the flow I have in mind for a Q&A type application where users choose who they want to answer their question. I have a single Request model as below: models.py class Request(models.Model): user = models.ForeignKey('auth.User') topic = models.ForeignKey(Topic) description = models.TextField() responder = models.ForeignKey(Responder) created_date = models.DateTimeField() published_date = models.DateTimeField(blank=True, null=True) The flow would be as follows: on first page, user chooses what topic they want (general knowledge, movies, etc.) on second page, user fills out a form describing their question on third page, user chooses a responder out of a list of available responders on fourth page (if user is not logged in), they log in So the instance of the object is created through four separate pages. What I currently have is the instance created all in one form/html page: forms.py class UserRequestForm(forms.ModelForm): class Meta: model = Request fields = ('user','topic','description',) widgets = { 'description': forms.Textarea(attrs={'class': 'form-control'), 'user': forms.HiddenInput(), } html page {% load bootstrap3 %} {% block content %} <form method="POST"> {% bootstrap_form form %} {% csrf_token %} <button type="submit" class="btn btn-primary btn-block">Ask</button> </form> {% endblock %} I haven't been able to find any documentation to … -
How to create multivalued field using django rest framework
i want to create a user registration api using django rest-framework,having fields name,email,address and other. I want to make the other field multivalued input field so that this field can take multple input in api. i used this model class User(models.Model): Name=models.CharField(max_length=20) email=models.EmailField(max_length=50) address=models.CharField(max_length=50) otherAddress=models.ForeignKey('self') i want my api field should be like 1)Name 2)email 3)address 4)other-->taking more than one or two inputs -
django queryset cannot run function inside annotate and Sum
I have two queryset and I want to do Addition from those two queryset but one query value are Int type (e.g. 1.5, 2.75 ) but others have time like string (e.g. 12:20:59). I need to convert that string to Int type so I can do use Sum Function in Annotate. First queryset timesheet_total_by_project = TimesheetEntry.objects.filter(created_by_id=current_user, timesheet__for_date__gte=start_tim, timesheet__for_date__lte=end_date, project__is_visible=True).values('project__name', 'project__id').distinct().annotate(totalsum=Sum('minutes', output_field=FloatField()) / 60.0) 2nd Queryset ticket_total_time = Ticket.objects.filter(assigned_to=user,total_time__isnull=False,project__is_visible=True).values('title','project__id').distinct().annotate(totalsum=Sum('total_time', output_field=FloatField()) / 60.0) I have tried def get_sec(time_str): print("string",time_str) """Get Seconds from time.""" h, m, s = time_str.split(':') return int(h) * 3600 + int(m) * 60 + int(s) ticket_total_time = Ticket.objects.filter(assigned_to=user,total_time__isnull=False,project__is_visible=True).values('title','project__id').distinct().annotate(totalsum=Sum(get_sec('total_time'), output_field=FloatField()) / 3600.0) Expected Output is would be 12.5 but output for print("string",time_str) string total_time Also says ValueError: not enough values to unpack (expected 3, got 1) -
AttributeError: 'list' object has no attribute 'lstrip'
For the past 3 hours I'm trying to send an email with csv attachment to a list of emails fetched from the database, but I'm getting an error which I am not really sure why is it occurring. I double checked my code for mistakes if there was any unicode getting passed etc, to avoid that I converted the fetched data into str but no use. If I run the script independently it executes and sends the email with the attachment without a problem but in Django it's giving an error. The emails in the list are made for Checking whether if this error was only for database related but it's not. It shoes up for the pre-defined list as well. I got the code snippet from Here: Here ERROR Performing system checks... Unhandled exception in thread started by Traceback (most recent call last): File "C:\Users\BITSWI~1\Desktop\LCRPRO~1\VE\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\BITSWI~1\Desktop\LCRPRO~1\VE\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "C:\Users\BITSWI~1\Desktop\LCRPRO~1\VE\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\BITSWI~1\Desktop\LCRPRO~1\VE\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\BITSWI~1\Desktop\LCRPRO~1\VE\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\BITSWI~1\Desktop\LCRPRO~1\VE\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Users\BITSWI~1\Desktop\LCRPRO~1\VE\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File … -
Where to host wagtail/django
Hi I have a bit of experience in WordPress but none in PHP however, I do in python. As you can imagine editing plugins to suit my needs is a bit hit and miss. I recently discovered wagtail and saw it ran on django, for me this would be far better. I researched how to host django remotely and got thousands of tutorials on python 2.7. The website says # in a Python 3 virtual environment pip install wagtail wagtail start mysite cd mysite pip install -r requirements.txt python manage.py migrate python manage.py createsuperuser python manage.py runserver Do you just ssh in and do this as you would on a local machine, if so which host should I use and how do you even ssh a web server. Thanks in advance -
How can i add auto counter to model objects?
I had 4 objects but when i deleted one, i shown based on object id not actual numbers of objects ? Model objects https://i.stack.imgur.com/QBbCV.png -
How to create separate URL in Django using Ajax
Here, There are 3 button in single template, How to call the separate URL for each button in views and ulrs.py The 3 buttons are Save Delete Copy We write the functionality for copy button, We clicking the save button the copy functionalities working 3 buttons image -
Updating data into multiple Table -> MultipleObjectsReturned at /client/update-client
I am trying to update the data into 3 tables. I have not set up the primary-foreign key relation bcoz of project requirement. I got this error - MultipleObjectsReturned at /client/update-client get() returned more than one BankDetails -- it returned 2! from views, I'm sending the data into 3 models but its updating one table only. Views.py @csrf_exempt def update_client_details(request): # try: client_master_dict = [] client_master_dict = json.loads(request.body) client_data_bank = client_master_dict['data'][0]['bank_details'] client_data_doc = client_master_dict['data'][0]['document_details'] records, client_id = ClientDetails.update_client(client_master_dict['data'][0]) for i in range(len(client_master_dict['data'][0]['bank_details'])): bank_data = BankDetails.update_bank_detail(client_data_bank[i],client_id) for j in range(len(client_master_dict['data'][0]['document_details'])): document_data = DocumentDetails.update_document_detail(client_data_doc[j],client_id) datum = json.dumps(records) data = json.loads(datum) returnObject = { "status" : messages.SUCCESS, "message" : messages.CLIENT_UPDATE_SUCCESS, "results" : data } return JsonResponse(returnObject,safe=False) Models.py (ClientDetails Table) @classmethod def insert_client_details(cls, cilent_master_dict): try: client_obj = ClientDetails() client_obj.client_id = "CL"+str(int(time.time_ns() * 10)) client_obj.client_name = cilent_master_dict['client_name'] client_obj.client_pan_no = cilent_master_dict['client_pan_no'] client_obj.client_adhar_no = cilent_master_dict['client_adhar_no'] client_obj.legal_entity_name = cilent_master_dict['legal_entity_name'] client_obj.credit_period = cilent_master_dict['credit_period'] client_obj.client_tin_no = cilent_master_dict['client_tin_no'] client_obj.client_email_id = cilent_master_dict['client_email_id'] client_obj.head_office_name = cilent_master_dict['head_office_name'] client_obj.office_contact = cilent_master_dict['office_contact'] client_obj.office_name = cilent_master_dict['office_name'] client_obj.office_email_id = cilent_master_dict['office_email_id'] client_obj.gst_number = cilent_master_dict['gst_number'] client_obj.office_country = cilent_master_dict['office_country'] client_obj.office_state = cilent_master_dict['office_state'] client_obj.office_district = cilent_master_dict['office_district'] client_obj.office_taluka = cilent_master_dict['office_taluka'] client_obj.office_city = cilent_master_dict['office_city'] client_obj.office_street = cilent_master_dict['office_street'] client_obj.office_pincode = cilent_master_dict['office_pincode'] client_obj.contact_person_name = cilent_master_dict['contact_person_name'] client_obj.contact_person_designation = cilent_master_dict['contact_person_designation'] client_obj.contact_person_number = cilent_master_dict['contact_person_number'] client_obj.contact_person_email = cilent_master_dict['contact_person_email'] client_obj.contact_person_mobile = … -
ERROR: Command errored out with exit status 1:
ERROR: Failed building wheel for mysqlclient ERROR: Command errored out with exit status 1 error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ RROR: Command errored out with exit status 1: 'c:\python\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Admin\AppData\Local\Temp\pip-install-sxz0ni7x\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\Admin\AppData\Local\Temp\pip-install-sxz0ni7x\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-li2rtx7t\install-record.txt' --single-version-externally-managed --compile Check the logs for full command output -
Django form instance test fail
I used datetime picker in front end. author creation form class AuthorCreationForm(forms.ModelForm): class Meta: model = Author fields = ('first_name', 'last_name', 'born', 'died', 'image', ) ====================================================================== FAIL: test_author_form (book.tests.test_view.TestAuthorCreatePage) Traceback (most recent call last): File "/home/kaung/workspace/library-management-system/config/book/tests/test_view.py", line 460, in test_author_form self.assertIsInstance(form, self.creation_form) AssertionError: is not an instance of -
i am getting an NoreverseMatch at / ,
I am trying to improve my models and html files for my project and while finding the solution on internet ive got this particular error. i've tried importing render and resolvers, and also trying looking out for solution on stackoverflow but nothing works for me. #here's urls.py from django.contrib import admin from django.urls import path from accounts import views as accounts_views from django.contrib.auth import views as auth_views from boards import views urlpatterns = [ path('boards/<int:pk>/topics/<topic_pk>/', views.topic_posts, name='topic_posts'), path('boards.<int:pk>/topics/<topic_pk>/reply/', views.reply_topic, name='reply_topic'), ] #here's line from base.html where its showing error <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#mainMenu" aria-controls="mainMenu" aria- expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> #here are my models.py file from django.contrib.auth.models import User from django.db import models from django.utils.text import Truncator class Board(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) def __str__(self): return self.name def get_posts_count(self): return Post.objects.filter(topic__board=self).count() def get_last_post(self): return Post.objects.filter(topic__board=self).order_by('- created_at').first() and i am getting this error "Reverse for 'topic_posts' with arguments '(2, '')' not found. 1 pattern(s) tried: ['boards/(?P<pk>[0- 9]+)/topics/(?P<topic_pk>[^/]+)/$']" -
How to alter label tag of fieldset in admin.tabularinline
I customized my add user form in my django admin, using admin.tabularinline. So whenever the admin adds a user, information about Usermodel and UserProfile model is saved at the same time. However, the label tag of the UserProfile form says 'Staff Profiles'(with 's'). And it doesn't look good because there is only one profile for one user. Any ideas how to change the "Staff Profiles" into "Staff Profile"? See the picture for refenrce: -
Normalize Django Field's Value
I wrote a custom django field to normalize the urls our system received. However, the url will only return normalized value after reload. from django.db import models def _rewrite_internal_url(url): # return 'http://www.google.com/1.jpg' class NormalizedURLField(models.URLField): def to_python(self, value): value = super().to_python(value) return _rewrite_internal_url(value) def from_db_value(self, value, expression, connection): if value is None: return value return _rewrite_internal_url(value) class DjangoTest(models.Model): url = NormalizedURLField() instance = DjangoTest.objects.create(url="http://www.google.com/2.jpg") print(instance.url) # still http://www.google.com/2.jpg instance.referesh_from_db() print(instance.url) # update to http://www.google.com/1.jpg -
How to remove the error when migrate in django?
I have a code which is to show the balance 0 in html page by default when someone new register itself. After makemigrations it works but after typing migrate it didn't work. Instead it gives me error. How to deal with this? models.py class Balance(models.Model): amount = models.DecimalField(max_digits=12, decimal_places=2, default=0) owner = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) views.py @login_required def balance(request): try: balance = request.user.balance except Balance.DoesNotExist: balance = None return render(request, 'nextone/balance.html', {'balance': balance}) Html page {% if balance.amount %} <h2>Your Balance is Rs. {{balance.amount}}</h2> {% else %} <h2>Your Balance is Rs. 0</h2> {% endif %} Error after I migrate File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\commands\migrate.py", line 234, in handle fake_initial=fake_initial, File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File … -
How to force to use new database when run python manage.py test in Django?
When I type python manage.py test Sometimes I get asked if I want to delete the test database. Type 'yes' if you would like to try deleting the test database 'test_replicate_live', or 'no' to cancel: yes WHen I want to keep the test database, I know the command is : python manage.py test --keepdb I would like to know if there's a way to force the deletion of test database without waiting for the question to appear. Sometimes I just know ahead of time, I want to delete the test database. Is tehre a python manage.py test --nokeepdb -
Bootstrap theme disappears when passing pk parameter, but uses Bootstrap4 default design
I'm using a bootstrap theme, Looper. Everything was going great on my "prescription_request_review.html" page, which contains a Bootstrap table and a Bootstrap form, until I added a pk parameter to the page. Instead of displaying my bootstrap theme as every other page does, it displays what I assume are Bootstrap4 defaults (bright blue button, plain white background, simple design.) I tried removing part or all of the {% block extrahead %} in prescription_request_review.html, but all it does is remove ALL Bootstrap components. Why would my theme change just because I'm passing a pk to the page? vhome.html Page where user can click prescription in rxtable.html, redirecting to the page I'm having the issue with: {% extends 'app/main/base.html' %} {% block extracss %} <link rel="stylesheet" type="text/css" href="static/assets/DataTables/datatables.css"/> {% endblock extracss %} {% block content %} {% include "app/veterinary/snippets/rxtable.html" %} {% endblock content %} {% block extrascripts %} <script type="text/javascript" src="static/assets/DataTables/datatables.min.js"></script> <script type="text/javascript"> $(document).ready( function () { $('#vrxTable').DataTable({ "order": [[ 6, "desc" ]], "paging": false, "info": false, "searching": false, "columnDefs": [ { "targets": 0, "orderable": false } ] }); }) </script> {% endblock extrascripts %} rxtable.html (actual table where the buttons are that lead to my problem page: <!-- list of open … -
Cannot redirect to correct URL after login using allauth get_login_redirect_url
I have a custom user model and am using django-allauth to manage the login ,sign up, logout functions. I have 5 user types and after each type login, they will be directed to separate pages. The usual LOGIN_REDIRECT_URL is not suitable for me since it can only redirect to one page no matter what type of users login. I found out that by using Custom Account Adaptor and override get_login_redirect_url()can make it work, so I implemented it. users.adaptor.py from django.conf import settings from allauth.account.adapter import DefaultAccountAdapter from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import resolve_url, redirect class MyAccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): # path = super(MyAccountAdapter, self).get_login_redirect_url(request) current_user=request.user if current_user.user_type == 1: path='doc/dochome/' elif current_user.user_type == 2: path='lab/labhome/' elif current_user.user_type == 3: path='recep/recephome/' elif current_user.user_type == 4: path='patient/patienthome/' elif current_user.user_type == 5: path='admini/adminhome/' else: return HttpResponse("Your Rango account is disabled.") return path # .format(username=request.user.id) settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_DIR = os.path.join(BASE_DIR, 'static') TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') MEDIA_DIR = os.path.join(BASE_DIR, 'media') MEDIA_ROOT = MEDIA_DIR # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'e$w4_d)z(z)4+5r98#@c4%52ymmd@96fv@x6#zzc7vs-aznqdo' # … -
Django delete error when foreignKey on_delete=CASCADE
I see the following errors occasionally and don't understand why. query DELETE FROM "cart_cart" WHERE "cart_cart"."id" IN (211244) 23:13:27 exception ForeignKeyViolation: update or delete on table "cart_cart" violates foreign key constraint "cart_cartline_cart_id_c7b9981e_fk_cart_cart_id" on table "cart_cartline" DETAIL: Key (id)=(211244) is still referenced from table "cart_cartline". When my cart_cartline table definition has the following line.. class CartLine(ItemLine): cart = models.ForeignKey( "Cart", on_delete=models.CASCADE, related_name='cart_line_set', ) Shouldn't django just delete the cart and the related cart lines?