Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update creation and update time pragmatically vs via database trigger
I want to add creation and update timestamps to several models in my django app. And I wonder what way is the best practice? I found that it can be done with auto_now and auto_now_add (or preferably via custom save() method). I call this programmatic way. Another way that comes to mind is defining a trigger function and assigning it to multiple database tables on the level of database (postgresql). So what is the best practice of doing things like that? (This may include total price calculations and any other column info that is calculated using other column data). Triggers or code? Note: This might be an opinion-based question. If so, Let me know in the comment, I will delete the question after I hear one or two opinions of an experienced developer. -
Django Inline for admin panel in foreign relationship with admin.TabularInline
models.py class Parent (models.Model): id = ...... name = ... address = ... class Child (models.Model): id= ... parent = models.ForeignField(Parent) Here in this schema, is it possible to bring Parent form inside Child schema to make editable by admin.Tabularline ? I know it is possible to bring Child Schema into parents schema and make editable. But I am looking for vice versa. Is it possible? -
Django settings: DATABASE_URL is not working
I just created a test application in Heroku so that I can stay in the same Django project, but quickly switch back and forth between connecting to my production database and my testing app database. I created an environment variable on my laptop using export:TEST_DATABASE_URL="...", but even with this below code I am still connected to my production database when I run my Django project on localhost. Does anyone know how i can accomplish this? # ~~~ PROD SETTINGS ~~~ # DATABASE_URL = os.environ['DATABASE_URL'] # DEBUG = 'False' # ~~~ TEST SETTINGS ~~~ DATABASE_URL = os.environ['TEST_DATABASE_URL'] DEBUG = 'True' # tried commenting this code out so it doesn't use the local sqlite file # DATABASES = { # Use this to use local test DB # todo: prod doesn't havea access to django_session... # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # } -
Django: Bad request when sending request using reactJS
I am using django-rest-framework at backend and I am trying to post following data from react frontend. handleSubmit() { fetch('http://127.0.0.1:8000/api/debt/create',{ method: 'POST', headers: { Authorization: `Bearer ${localStorage.getItem('id_token')}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ user: '1', customer: '9', debtKey: 'b1d9ef1b-45ad-4dc5-80cc-95f7994c0aae', createduserKey: '0245abb9-2837-4f37-ae02-9be1b88887ef', totalDebt: 789, receivedAmount: 115, description: 'Debt description', paymentDate: '01.01.2019' }), }).then(response => { console.log(response); return response.json() }).then(json => { //this.setState({ // user:json //}); }); console.log("Form Sumbmssion"); } But I am getting "BAD REQUEST" error. What I am missing? Thanks -
Django forms.MultipleChoiceField with CheckboxSelectMultiple and Bootstrap custom-control-input is reset when form.is_bound
I have a form field: Forms.py colors = forms.MultipleChoiceField( required=True, widget=forms.CheckboxSelectMultiple, choices= [(1,'blue'),(2,'red'),(3,'green')] ) I can easily render this field like this: Template.html {{ form.colors }} And get something that looks like this: So the html code looks like that: <ul id="id_colors"> <li><label for="id_colors_0"><input type="checkbox" name="colors" value="1" id="id_colors_0" checked=""> blue</label> </li> <li><label for="id_colors_1"><input type="checkbox" name="colors" value="2" id="id_colors_1" checked=""> red</label> </li> <li><label for="id_colors_2"><input type="checkbox" name="colors" value="3" id="id_colors_2"> green</label> </li> </ul> This is really simple ! And it's working fine. Now, let's say I want to render this differently, exactly like this: With bootstrap custom-control-input. Bootstrap documentation show this code to achieve this: <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck" name="example1"> <label class="custom-control-label" for="customCheck">Check this custom checkbox</label> </div> So, in my template I did something like that: Template.html <div class="custom-checkbox"> <ul id="id_colors"> {% for key, value in colors %} <li> <input type="checkbox" class="custom-control-input" value="{{key}}" name="colors" id="id_colors_{{ forloop.counter0 }}"> <label class="custom-control-label" for="id_colors_{{ forloop.counter0 }}">{{value}}</label> </li> {% endfor %} </ul> </div> (Where "colors" is just my list that I pass to the template thru the view) With that template, the field looks exactly like I want. When rendered, the html looks like this: <ul id="id_colors"> <li> <input type="checkbox" class="custom-control-input" value="1" name="colors" id="id_colors_0"> <label class="custom-control-label" … -
How to update an Input file (image) in vueJS and Django rest?
Good morning, I'm currently working to the edit page for a blog using VueJS and Django Rest Framework. When I try to upload a photo I receive an error "the sended datas are not a file" and I' not currently able to select the current image (the default image is Null). The questions are how to make a working changing photo form and how to start with the image already charged in the JSon file. Thanks for all answers. Right now I have not made the admin system. VueJS <template> <h1>ARTICOLO</h1> <form @submit="onSubmit"> <input type="text" name="title" placeholder="Titolo" v-model="form.title"> <input type="text" name="desc" placeholder="Descrizione" v-model="form.desc"> <input type="text" name="category" v-model="form.category"> <input type="file" name="image" @change="EditImage" > <input type="text" name="author" v-model="form.author"> <input type="text" name="author" v-model="form.slug"> <textarea name="text" v-model="form.text"></textarea> <button type="submit" @click= "editPost">Edit</button> </form> </template> <script> import axios from 'axios'; import { getAPI } from '../api' export default { data () { return{ Postslug: this.$route.params.Postslug, form: { title:"", desc:"", text:"", category:"", date:"", author:"", image:"", slug:"", }, selectedFile: null } }, methods: { // Form method onSubmit(event){ event.preventDefault(); axios.put(`http://127.0.0.1:8000/blog/api/edit/${this.Postslug}`, this.form).then(response => { this.form.title = response.data.title this.form.desc = response.data.desc this.form.text = response.data.text this.form.image = response.data.image this.form.category = response.data.category this.form.author = response.data.author this.form.slug = response.data.slug alert('Ok') }) .catch(err => … -
Display Database entry as option in a Django Form
I am trying to create an inventory app and one reservation app. I am trying to take entries from the inventory model and one can reserve it with the help of reservation app. What I am trying to achieve : The reservation app should take the entry of serial number from the inventory app serial number. It should either with the help of a drop down , which will show only the entry of specific serial number, so that random serial number should not be entered. ( I tried the concept of foreign key and many to many but I was unable to achieve it on the html page UI , but I achieved it on admin panel) Can you suggest what changes will be required ? For now, I am creating a form like this : But it is very poor method, because form is not getting validated, I am redirecting user to other web page where there are serial numbers present. I am trying to see how can we make the serial numbers available there itself as a drop down so that user can select which serial number to select. I am trying to add the slot field … -
Data getting printed in Network Response and not in HTML table in Django
I have a UI with two tables , so the second table is populated based on selection of checkbox from first table , but currently only first table data gets populated in UI and second table only in Network Console . I am new to this django concept and i don really know why this is happening . Currently on UI am able to retrieve data for First Table and in Network console , both table data's So the above is network console and printed is second table values , but this values are not getting printed in UI / HTML template . So here is my code : <div class="preview"> <table id="example" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th></th> <th>ServerName</th> </tr> </thead> <tbody> {% for datas in customerserver %} <tr> <td> <div class="form-check form-switch"> <form method="post">{% csrf_token %} <input class="form-check-input" name="Servers" value="{{datas.ServerName}}" type="checkbox" id="flexSwitchCheckDefault"> <label class="form-check-label" for="flexSwitchCheckDefault"> </form> </div> </td> <td>{{datas.ServerName}}</td> </tr> {% endfor %} </tbody> </table> <table id="exampleSecond" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th></th> <th>ServerName</th> <th>Component</th> <th>PID</th> <th>State</th> </tr> </thead> <tbody> {% for datasno in ResultofRetrieve %} <tr> <td> <div class="form-check form-switch"> <form method="post">{% csrf_token %} <input class="form-check-input services" name="Services1[]" value="{{serv.ServerName}}" type="checkbox" id="flexSwitchCheckDefault"> <label class="form-check-label services" for="flexSwitchCheckDefault"> … -
Use Python Django inbuilt auth username as foreign key for separate app tables and cascade
I am creating a new separate user information table in Django. I want to use the inbuilt auth model. For that I need to have Foreign Key relation with username column in auth_user table. I want to use the Django inbuilt auth management; use auth_user's 'username' char column as foreign key in my apps new tables. Then whenever a user is deleted from Django's auth module, I want to cascade the changes and delete all records in the other tables. I think the foreign key relation is denoted here as OneToOneField. How do I design this model and relationship? mysql> show tables; +----------------------------+ | Tables_in_MYAPP_sqldb | +----------------------------+ | auth_group | | auth_group_permissions | | auth_permission | | auth_user | | auth_user_groups | | auth_user_user_permissions | | django_admin_log | | django_content_type | | django_migrations | | django_session | +----------------------------+ 10 rows in set (0.00 sec) mysql> describe auth_user; +--------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | password | varchar(128) | NO | | NULL | | | last_login | datetime(6) | YES | | NULL | | | is_superuser | … -
How to get column from DRF modal in get method?
How can I get the column in get method and return after doing some operation in DRF ? My model class is : class MQTTFeed(models.Model): sensor = models.ForeignKey( 'core.SensorDevice', on_delete=models.SET_NULL, null=True ) feed = models.TextField() created_at = models.DateTimeField(auto_now_add=True) And my view class is : class MQTTFeedListAPIViewWithMinValue(generics.ListAPIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated, permissions.IsAdminUser,) serializer_class = serializers.MQTTFeedSerializer filter_backends = (SearchFilter, DjangoFilterBackend, OrderingFilter,) filter_class = filters.MQTTFeedFilter search_fields = ('feed',) #queryset = models.MQTTFeed.objects.all() I have implemented something like that but I am getting error in views.py: def get_queryset(self): return self.queryset def get_object(self): feed = self.kwargs['feed'] print(feed) return feed How can I get the feed values in list so that i can manipulate and return value. -
I have installed pipenv and set the path variable to C:\~~Scripts also however ..when I run "docker build ." I get error at step 6 as follows:
Step 6/7 : RUN pip install pipenv | pipenv install --system ---> Running in 85fbae58695b pipenv : The term 'pipenv' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:97 ... sPreference = 'SilentlyContinue'; pip install pipenv | pipenv install ... CategoryInfo : ObjectNotFound: (pipenv:String) [], ParentContai nsErrorRecordException FullyQualifiedErrorId : CommandNotFoundException The command 'powershell -Command $ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; pip install pipenv | pipenv install --system' returned a non-zero code: 1 -
Django django.db.utils.IntegrityError: NOT NULL constraint failed: new__users_profile.location
I have the following model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") image = models.ImageField(default='default.jpg', upload_to='profile_pics') location = models.CharField(default=None, max_length=5) def __str__(self): return f'{self.user.username} Profile' I was testing some things out and put null=True for location. Then I changed it to default=None. After that when I tried to run makemigrations followed by migrate. I got the following error Full Traceback Traceback (most recent call last): File "C:\Users\uddin\project\trade\manage.py", line 22, in <module> main() File "C:\Users\uddin\project\trade\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\uddin\Envs\web\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\uddin\Envs\web\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\uddin\Envs\web\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\uddin\Envs\web\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\uddin\Envs\web\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\uddin\Envs\web\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\Users\uddin\Envs\web\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\uddin\Envs\web\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\uddin\Envs\web\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\uddin\Envs\web\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 "C:\Users\uddin\Envs\web\lib\site-packages\django\db\migrations\operations\fields.py", line 236, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Users\uddin\Envs\web\lib\site-packages\django\db\backends\sqlite3\schema.py", line 138, in alter_field super().alter_field(model, old_field, new_field, strict=strict) File "C:\Users\uddin\Envs\web\lib\site-packages\django\db\backends\base\schema.py", line 571, in alter_field … -
Trying to work on a project, python mysql not working on m1 chip?
I am trying to run a django project on M1chip with python 3.8, I got below at one point and it has been a road blocker for me how to tackle it. I tried to search for the problem but still not clear about the cause of issue. I checked for different answers online but nothing seems helping. Traceback (most recent call last): File "/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so Expected in: flat namespace in /usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so During handling of the above exception, another exception occurred: Traceback (most recent call last): File "src/gevent/greenlet.py", line 906, in gevent._gevent_cgreenlet.Greenlet.run File "/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Caskroom/miniforge/base/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in … -
How do I preview a pdf file before saving it in Django?
How do I preview a pdf file before saving it in Django? I am trying to preview a pdf file before the user uploads it using the "pip install preview-generator" Link: https://pypi.org/project/preview-generator/ However the pdf file isn't loading up properly. I am not really sure what is pdf_or_odt_to_preview_path as the documentation wasn't clear. As such, I tried to use JS and jquery to send information from the front end to views.py, and subsequently use the tag to hold the pdf file. First Attempt which didnt work as the file didnt show: views.py @login_required def preview(request): if request.method == 'POST': body = json.loads(request.body) embedPDF = body['PDF'] print(PDF) cache_path = '/tmp/preview_cache' pdf_or_odt_to_preview_path = f'{PDF}' manager = PreviewManager(cache_path, create_folder= True) path_to_preview_image = manager.get_jpeg_preview(pdf_or_odt_to_preview_path) return JsonResponse({'status':200}) javascript: $('#testing-nia').on('change', function () { const file = this.files[0] reader = new FileReader(); reader.readAsDataURL(file); $(reader).on('load', function() { PDF = this.result var request = new Request( "{% url 'preview' %}", {headers: {'X-CSRFToken': '{{csrf_token}}'}} ) fetch(request, { method: 'POST', mode: 'same-origin', body: JSON.stringify({'PDF' : PDF, }) }) .then(response => response.json()) .then(data => console.log('finished if false')) }) }) 2nd Attempt which rendered a header i dont want: javascript: else if (file.name.endsWith('pdf')) { reader = new FileReader(); reader.readAsDataURL(file); $(reader).on('load', function () { … -
"School with ID “601664bd3c7d8d38768c43b9” doesn’t exist. Perhaps it was deleted?" Error when migrated using mongorestore
I want to migrate the data from a Mongodb database running with a Nodejs+mongoose platform into a Django+djongo platform. I created the data backup using mongodump and got me a .bson file which I used for migration. data shown in source database is as follows. { "_id" : ObjectId("5c03c9f4a836690d6c540835"), "title" : "School A", "location" : "Location A", "postTime" : "1543752160981", "createdAt" : ISODate("2021-10-23T16:47:43Z"), "verified" : true, "__v" : 0, "image" : "http://21.441.45.80:3002/images/1543752161789-file.jpg", "thumbnail" : "http://21.441.45.80:3002/images/thumnail-1543752161789-file.jpg" } I created the destination database with similar fields avoiding "__v". I imported the source data into destination database using following command. mongorestore --db school_db --collection school_schoolmodel ../path/to/school.bson I got message that 1169 document(s) restored successfully. 0 document(s) failed to restore. Then I opened the django admin panel, and clicked one of the item. Then I got following error? School with ID “601664bd3c7d8d38768c43b9” doesn’t exist. Perhaps it was deleted? What is the issue here? I'm putting code here. Please comment if any additional details required. I'm not allowed to change the configuration of source database. models.py class NewsModel(models.Model): _id = models.CharField(max_length=20, primary_key=True, serialize=False, verbose_name='Company Code') title = models.CharField(max_length=60, blank=True) location = models.TextField(blank=True) postTime = models.IntegerField(blank=True) createdAt = models.DateTimeField(blank=True) verified = models.BooleanField(default=False, blank=True) image = models.ImageField(upload_to=image_upload_to, … -
how to render data from 1 view in 2 different htmls in the same page
My django web application has the following structure main.html <body> <div id="mn" class="mainw"> <div id="message" class="message"> <b>{{context.title}}</b> </div> <div class="sidenav"> <ul> <li class="li"><a href="acctlkpview" target="iframe1">Billing Account Lookup</a></li> <li class="li"><a href="acctlkpnoresell" target="iframe1">Billing Account Lookup No-Resell</a></li> </ul> </div> <div class="frame"> <iframe width="100%" height="100%" name="iframe1" > </iframe> </div> </body> i have another side navigation bar side nav which populates a iframe iframe1 inside the main.html Now the iframe is populated by views which returns data for the iframe when the unordered links in sidenav are clicked. For each view i load a different html page inside the frame, I return a value called title in the context, from the view context={"title":message,'role':role,'email':email} return render(request,'billingacct/view2.html',{"context":context}) Now I want this title to be set as the title attribute in the main.html {{context.title}}. But the view will only render attributes for view2.html which is displayed inside the iframe in the main.html. Can anyone please tell me how to achieve this? Thanks -
Django Forms not showing
I am trying to use Django provided forms instead of manually creating them with HTML. When I do this, however, they do not appear. The questions/answers I have found on this site have so far been unable to solve my issue. (unless I am reading them wrong.) forms.py from django import forms class KeywordForm(forms.Form): input_keywords = forms.CharField(label="Keywords", max_length='100') class LocationForm(forms.Form): input_location = forms.CharField(label="Location", max_length="250") views.py from django.shortcuts import render from .forms import KeywordForm, LocationForm def search_view(request): keyword_form = KeywordForm() location_form = LocationForm() return render(request, 'search_results.html', {'keyword_form': keyword_form, 'location_form': location_form}) urls.py from django.urls import path from . import views urlpatterns = [ ... path('search/', views.search_view, name='search'), ] base.html {% block search %} <div class="card"> <div class="card-body"> <form class="row align-items-center"> <form action="search" method="GET"> <div class="col-sm-2"> {{ keyword_form }} </div> <div class="col-sm-2"> {{ location_form }} </div> <!-- <label for="inputKeywords" class="form-label">Keywords</label>--> <!-- <input class="form-control" id="inputKeywords" type="text" name="inputKeywords" placeholder="Enter Keywords...">--> <!-- </div>--> <!-- <div class="col-sm-2">--> <!-- <label for="inputLocation" class="form-label">Location</label>--> <!-- <input type="Text" class="form-control" id="inputLocation" name="inputLocation" placeholder="Enter location...">--> <!-- </div>--> <div class="col"> <input class="btn btn-primary" type="submit" value="Search"> </div> </form> </form> </div> </div> {% endblock %} -
ImportError: No module named backends when uising python-social-auth when upgrading to Django 1.9
I am upgrading my project from Django 1.8 to Django 1.9 and when I run my server using python manage.py runserver i am getting error in my views like Traceback (most recent call last): File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 10, in check_url_config return check_resolver(resolver) File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 19, in check_resolver for pattern in resolver.url_patterns: File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/projectfolder/project/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/projectfolder/projectrespos/dev-1.8/mcam/server/mcam/mcam/urls.py", line 10, in <module> from crm.views import * File "/home/projectfolder/projectrespos/dev-1.8/mcam/server/mcam/crm/views.py", line 63, in <module> from core.views import (CustomAuthMixin, CustomAdminMixin, JSONResponseMixin, File "/home/projectfolder/projectrespos/dev-1.8/mcam/server/mcam/core/views.py", line 477, in <module> from social.apps.backends import get_backends ImportError: No module named backends core/views.py from social.apps.backends import get_backends def get_auth_backends(): backends = get_backends() return [(name, title, backends.get(name)) for name, title in settings.SOCIAL_AUTH_ACTIVE_BACKENDS.items() if name in backends] In my settings.py folder INSTALLED_APPS = [ . . … -
Efective way to develop django project
i'm an intern and currently developing a simple dashboard to display visualization of school database, using Django. There are two scenarios of how am i gonna develop this, First, I connect django models to mysql database where the data stored. I fetch the models into table and graphics then display it in the html page, but the page consuming some time to load the data. Honestly, i don't really know how to processing the models in the views.py like i'm processing data usually in python using pandas. This scenario interact with only one database. Second, i connect mysql database directly in views.py and process it using pandas. When one executive want to know a graphic/chart from spesific row and column, they can request in the page. If it takes some time to load, it's okay, but the result have to be stored in django models. So, when the other executive want to know the same result, we just have to fetch the result from django database. This scenario interact with two database. I need some advice from you regarding what scenario that's better to used and some other tips to develop web dashboard using Django, considering this is my first … -
How to direct Http protocol to Https protocol in Django using mod_wsgi and SSL?
I'm using mod_wsgi to run my Django API but it's running on HTTP protocol. I want it to run in HTTPS protocol but I don't know how to install/configure SSL in the Dockerfile. I have searched for implementing SSL for my Django API but I couldn't find any example that uses dockerized Django application using mod_wsgi. Dockerfile: FROM python:3 RUN echo 'en_US.UTF-8 UTF-8' >> /etc/locale.gen && locale-gen ENV LANG=en_US.UTF-8 LC_ALL=en_US.UTF- COPY ./requirements.txt /requirements.txt RUN pip install --no-cache-dir -r /requirements.txt WORKDIR /opt/app-root COPY . /opt/app-root EXPOSE 80 CMD ["mod_wsgi-express", "start-server", "--port", "80", "--threads","20","--processes","5","--user","www-data", "--group", "www-data", "--log-to-terminal", "/opt/app-root/mysite/wsgi.py"] This site describes the implementation of OpenSSL in mod_wsgi but I don't know how to use this in Dockerfile. Please help me with this -
Django PasswordResetConfirmView
When using Django3.0 internal PasswordResetConfirmView and tampering with the token generated it raises a form "is_bound" error. It doesn't redirect to some failure url. Internal Server Error: /account/password/reset/MQ/akbdyj-e5f18868fas35e748160dd6ef006803a5/ Traceback (most recent call last): File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\response.py", line 108, in render self.content = self.rendered_content File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\response.py", line 86, in rendered_content return template.render(context, self._request) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\loader_tags.py", line 62, in render result = block.nodelist.render(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\crispy_forms\templatetags\crispy_forms_tags.py", line 203, in render c = self.get_render(context).flatten() File "C:\Users\JoyStick\.virtualenvs\django-template-2StZ7f6a\lib\site-packages\crispy_forms\templatetags\crispy_forms_tags.py", line 112, in get_render node_context.update({"is_bound": actual_form.is_bound}) AttributeError: 'NoneType' object has no attribute 'is_bound' I have tried passing the failure template … -
How to seralize cart?
I got this error when I added product in the basket type object 'Cart' has no attribute '_meta'. Views Django class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: #Save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart self.coupon_id = self.session.get('coupon_id') Form from django import forms from django.core.validators import MinValueValidator, MaxValueValidator class CartProductForm(forms.Form): quantity = forms.IntegerField(initial=1) update_qt = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) HTML Form Code <form action="{% url "..." %}" method="post" data-id="{{ ... }}" class="form-order" id="form"> {{ cart_product_form }} {% csrf_token %} <a data-id="{{ ... }}" class="buy-product"><button>BUY</button></a> </form> HTML Span <ul class="navbar-nav ml-auto d-block d-md-none"> <li class="nav-item"> <a class="btn btn-link" href="#"><i class="bx bxs-cart icon-single"></i> <span class="badge badge-danger" id="cartval">{{ cart | length }}</span></a> </li> </ul> -
What is the best way to write Django for user interaction using button which updates values in the model
I am trying to write Django code for below: A user presses a button in the frontend. Multiple button options to decrement value by 10, 20, 30 etc. When the user presses the button, value for a Django model attribute in the backend will decrement accordingly. For example in the code below I set the intial value to 107. When the user presses the "Subtract 10" button in the html template, I want 10 subtracted from 107, so that the value then becomes 97. User is not entering any data. I unsuccessfully tried to use Django modelForm and "POST" and that did not work. Any suggestions appreciated. Below is the code I had that did not work. models.py class Balance(models.Model): userBalance = models.DecimalField(max_digits=10, decimal_places=2, null=True) forms.py class BalanceForm(forms.ModelForm): class Meta: model = Balance fields = ['userBalance'] views.py def balance(request): form = BalanceForm(initial={"userBalance":107}) if form.is_valid(): if request.method == "POST" and "form10" in request.POST: formValue = form.cleaned_data.get('userBalance') form2 = formValue - 10 return render(request, "econlabs/balance.html", {'form2': form2}) return render(request, "econlabs/balance.html", {'form': form}) -
Django no context data
I try to show data on template. But context data ois empty on html page. views.py from .models import DataS def index(request): list_z = DataS.objects.all().count() context = {'list_z:': list_z} return render(request, 'index.html', context=context) index.html <!DOCTYPE html> <html> <head>Page</head> <body> <ul> <li>{{ list_z }}</li> </ul> </body> </html> -
Can't reference Django database with dj_database_url
I have a Django application using decouple and dj_database_url (it is not on Heroku). If I put my connection information in settings.ini (DB_NAME, DB_USER, DB_PASSWORD, DB_HOST, and DB_PORT) and set up my database connection in settings.py like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST'), 'PORT': 'DB_PORT', } } It works fine. However, if I put this in my settings.ini: DATABASE_URL=postgres://johndoe:mypassword@123.456.789.000:5000/blog_db and reference it like this in my settings.py: DATABASES = {"default": dj_database_url.config(default=config("DATABASE_URL"))} It doesn't work. I just get a 500 when I try to run my server. I presume there is something wrong with my syntax. Can anyone point out what I'm doing wrong? Thanks!