Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i have problem with one to one extends user model
hi friends i want extends user model with fields from other table (structure) as foreignkey .. i will show you my models and the error after creation of super user from django.db import models from django.contrib.auth.models import User from immob.models import structure from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): User = models.OneToOneField(User, on_delete=models.CASCADE) structure_id = models.ForeignKey(structure, on_delete=models.CASCADE, default=0) @receiver(post_save, sender=User) def create_user_utilisateur(sender, instance, created, **kwargs): if created: Profile.objects.create(User=instance) @receiver(post_save, sender=User) def save_user_utilisateur(sender, instance, **kwargs): instance.profile.save() Error message: [p-amc-dgps-er@192-168-150-254 Invest_App]$ python3 manage.py createsuperuser Username (leave blank to use 'p-amc-dgps-er'): admin Email address: admin@admin.dz Password: Password (again): Error: Your passwords didn't match. Password: Password (again): Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/django/db/backends/base/base.py", line 239, in _commit return self.connection.commit() psycopg2.errors.ForeignKeyViolation: ERREUR: une instruction insert ou update sur la table �� compte_profile �� viole la contrainte de cl�� ��trang��re �� compte_utilisateur_structure_id_id_df7f99e8_fk_immob_str �� DETAIL: La cl�� (structure_id_id)=(0) n'est pas pr��sente dans la table �� immob_structure ��. -
How to save a django "with" template tag value and reuse it in other templates?
I have a template tag that reads values from the URL. For example the searched term is cancer. After searching, the next page that appears would have a with Searched terms: Cancer. And I would like the value cancer to appear in all of my webpages until the user does a new search. Pages I have work this way: Search.html > display.html > explore.html Search.html is where the user enters what they want to search for. I have a searchedterms.html which is included into all 3 templates and contains the Javascript code to read from the URL. By using a JavaScript code, I managed to display searched terms: cancer in display.html but in explore.html the value is empty. I want to be able to save "cancer" to the tag and use it in other templates. ?conditions=cancer in search.html: <input required="" type="text" name="conditions"> in display.html: {% with searched_terms='searchedterms.html' %} {% include searched_terms %} {% endwith %} in explore.html: {% with searched_terms='searchedterms.html' %} {% include searched_terms %} {% endwith %} in searchedterms.html: <div id="searched" class="container"></div> <script type="text/javascript"> var urlParams = new URLSearchParams(window.location.search); function getUrlParameter(name) { name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]'); var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'); var results = … -
How to solve AJAX cross-domain problems with csrftoken
I want to use the csrf_token to solve the Cross-domain problem about ajax, but I have some problems here is my json : {"id": 1, "distribution_box_id": "abc123", "timestamp": "2019-07-11T07:00:00", "lock1": 0, "lock2": 0, "temperature": 26.0, "humidity": 10.0, "latitude": 35.15409152643205, "longitude": 109.45553839575084, "smoke_detector": 0} $.ajax({ url: 'http://localhost/app1/distributionboxdata/1', method: 'post', headers: { 'Csrf-Token': '@play.filters.csrf.CSRF.getToken.map(_.value)' }, data: { name: '@name' }, success: function (data, textStatus, jqXHR) { location.reload(); },//I don't know what to put here error: function (jqXHR, textStatus, errorThrown) { debugger; } }); -
Django rest framework bulk: Correct URL syntax for bulk operations?
I'm attempting to carry out bulk DELETEs/PUTs on my Django API, mymodel inherits from the BulkModelViewSet In my urls.py file I define the URL used to interact with my model: router.register(r"v1/mymodels", mymodels_views_v1.MyModelViewSet) this allows me to GET, POST, PUT and DELETE on the URL (works perfectly at present): www.my-api.com/v1/mymodels/{{mymodel_id}} Can I use this same URL for bulk operations? If so, what is the correct syntax? eg: www.my-api.com/v1/mymodels/[{{mymodel_id1}},{{mymodel_id2}}] If not, what changes should I make? Thanks -
Cannot import python library on django server hosted on docker
I am running a django server on docker. I have added numpy and pandas in the requirements.txt file. Next I run docker-compose build . Both the libraries show as installed correctly. But now when I start the server and then run a python script that imports these libraries, the script fails to execute and I get no output. I tried executing the same script without importing those 2 libraries, and it executes properly giving out the expected print statement. What could have gone wrong here? -
table row order not changing after ajax call in django
The problem is i want to update the table row with drag and drop .using Jquery Ui for it.. i have an map_order field in model for swquence. but when i call ajax for that the changing is only happening in browser not in database i have tried to save the map_order but its not working HTML <tbody id="#layerTable"> {% for layer in layers %} <tr data-pk="{{ layer.id }}" class="ui-state-default"> <td><input type="checkbox" name="ids" value="{{ layer.id }}" /></td> <td> <a href="{% url 'mapport.maps.layers.one' map.id layer.id %}">{{ layer.name }}</a> </td> <td>{{ layer.heading }}</td> <td>{{ layer.class_group }}</td> <td> <span class="glyphicon glyphicon-resize-vertical"></span> {{ layer.map_order }}</td> <td>{{ layer.map_server }} </td> <td> {% if layer.sql_schema %}{{ layer.sql_schema }}.{{ layer.sql_table }}{% endif %} </td> </tr> JS <script type="text/javascript" charset="utf-8"> $(document).ready(function() { $("tbody").sortable({ stop: function(event, ui) { sort = {}; window.CSRF_TOKEN = "{{ csrf_token }}"; $("tbody").children().each(function(){ sort[$(this).data('pk')] = $(this).index(); }); {#var csrftoken = $('input[name="csrfmiddlewaretoken"]').val();#} $.ajax({ url: "{% url "mapport.maps.layers.all" map.id %}", type: "post", data:{sort, csrfmiddlewaretoken: window.CSRF_TOKEN, }, }); console.log(sort) }, }).disableSelection(); }); </script> Views.py class LayerView(BaseView) @csrf_exempt def sort(self): for index, layer_pk in enumerate(self.request.POST.getlist('layer[]')): self.layers.get_object_or_404(Layer, pk=int(str(layer_pk))) self.layers.map_order = index self.layers.save() Output is show the layer.id and index but not saving the layer.map_order {531: 15, 822: 14, 886: 20, … -
Django: Missing component after deployment
Django: Missing component after deployment. Missing app-component "accounts" after deployment on production-server. Symptoms: Changes to the model had no effect. Dropping the database deleted the UserProfile Model. Server: nginx, gunincorn on digitalocean Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, tweets Running migrations: No migrations to apply. :/home/django/django_project# tree ├── accounts │ ├── __init__.py │ ├── __init__.pyc │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ ├── __init__.cpython-37.pyc │ │ ├── admin.cpython-36.pyc │ │ ├── admin.cpython-37.pyc │ │ ├── forms.cpython-36.pyc │ │ ├── forms.cpython-37.pyc │ │ ├── models.cpython-36.pyc │ │ ├── models.cpython-37.pyc │ │ ├── urls.cpython-36.pyc │ │ ├── urls.cpython-37.pyc │ │ ├── views.cpython-36.pyc │ │ └── views.cpython-37.pyc │ ├── admin.py │ ├── admin.pyc │ ├── api │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── __init__.cpython-37.pyc │ │ │ ├── serializers.cpython-36.pyc │ │ │ ├── serializers.cpython-37.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ └── urls.cpython-37.pyc │ │ ├── serializers.py │ │ ├── serializers.pyc │ │ ├── urls.py │ │ └── urls.pyc │ ├── apps.py │ ├── forms.py │ ├── forms.pyc │ ├── models.py │ ├── models.pyc │ ├── templates │ │ ├── accounts │ … -
Displaying file's uploading percentage (a variable) on sweetalert
How do we actually create a variable which is the file's uploading percentage on sweetalert? I'm using PyCharm as a platform and Django as a GUI framework. I've actually look at several types of questions pertaining to Ajax, PHP and sweetalert (can't find a specific problem related to mine), and tried some of the to mix and match some of the solutions, unfortunately, none of them work. As stated below is my curent code: In html: <form id='upload' method="post" enctype="multipart/form-data" onsubmit="myFunction()"> {% csrf_token %} <input name="datas" type="file" id="datas"/> <input type="submit" value="Submit" name="btnform3" style="height:6%; width:75%"/> </form> <script> function myFunction() { Swal.fire({ title: 'Status:', text: 'Files Uploading...', imageUrl:'static/widget-loader-lg-en.gif', html: '<h3 id="status"></h3>', showConfirmButton: false, allowOutsideClick: false, }) } function _(el) { return document.getElementById(el); } function uploadFile() { var file = _("datas").files[0]; var formdata = new FormData(); formdata.append("datas", file); var ajax = new XMLHttpRequest(); ajax.upload.addEventListener("progress", progressHandler, false); ajax.addEventListener("load", completeHandler, false); ajax.open("POST","static/upload.php"); ajax.send(formdata); } function progressHandler(event) { var percent = (event.loaded / event.total) * 100; _("status").innerHTML = Math.round(percent) + "% uploaded... please wait"; } function completeHandler(event) { _("status").innerHTML = event.target.responseText; } In upload.php: <?php $fileName = $_FILES["datas"]["name"]; // The file name $fileTmpLoc = $_FILES["datas"]["tmp_name"]; // File in the PHP tmp folder $fileType = $_FILES["datas"]["type"]; // … -
How to pass a keyword with an API request on a local server?
I need to send a string with the API request and store it in a variable which is oid here. How do i pass it with the url???? p.s. I am very new to Django and thus the basic doubt. -
enable html form in django rest ui
I need no enable 'html form' button in django rest api user interface. How to enable this option ? -
Problem to save data from a form to the session
I am trying to save the data from a form to the session but it seems that it's not the right datatype. I have tried model_to_dict and cleaned as it is working fine for my other form that takes similar data in entry but it didn't work. class ActivitiesForm(forms.Form): activity = forms.ModelChoiceField(label='Select your activities', queryset=Activity.objects.all()) target_group = forms.ChoiceField(label='Who is the report destined to?', choices=OutputOutcomeImpact.TARGETGROUP) class Activities(TemplateView): template_name = 'blog/activities.html' context = {'title': 'Activities selection page'} def get(self, request): form_act = ActivitiesForm() form_act.fields['activity'].queryset = Activity.objects.filter(categories__sectors__name=request.session['sector']['name']) self.context['form_act']=form_act return render(request,self.template_name, self.context) def post(self,request): form_act = ActivitiesForm(request.POST) if form_act.is_valid(): print(form_act.is_valid(),form_act.cleaned_data['activity'],type(form_act.cleaned_data['activity']),type(model_to_dict(form_act.cleaned_data['activity'])),form_act['activity']) request.session['activity'] = model_to_dict(form_act.cleaned_data['activity']) request.session['target_group'] = model_to_dict(form_act.cleaned_data['target_group']) return redirect('/about', self.context) Here's the type of data that I get from the print and the error: True Municipal waste incineration <class 'blog.models.Activity'> <class 'dict'> <select name="activity" required id="id_activity"> <option value="">---------</option> <option value="Municipal waste incineration" selected>Municipal waste incineration</option> <option value="Plastic upcycling">Plastic upcycling</option> </select> Internal Server Error: /activities/ . . . AttributeError: 'str' object has no attribute '_meta' Hope it helps. Thanks. -
django cannot find module named XX when importing with absolute path
I have a django project with following structure project folder |- mysite |- mysite |- __init__.py |- settings.py |- ... |- myapp |- __init__.py |- abc.py |- ... |- __init__.py |- manage.py When i use relative imports, it all works fine. But when I change to absolute imports, it raise error "No module named 'mysite.myapp'. I started my script in project/mysite folder, so I thought it should search all subdirectories and found myapp module, but clearly it didn't. And I did add myapp/apps.py class into INSTALL_APPS in the settings files. So what's wrong with my codes and settings thanks -
gunicorn ImportError: No module named flask
I have an anaconda virtual environment and I have already install flask in the virtual environment using pip when I run my app using $ python app.py then it's working correctly, But when I run it with gunicorn I't showing that no module flask app.py from flask import Flask app = Flask(__name__) @app.route('/') def index(): return "Hello World" if __name__ == '__main__': app.run(debug=True) wsgi.py from app import app if __name__ == "__main__": app.run() $ gunicorn --bind 0.0.0.0:8000 wsgi [2019-07-23 12:39:24 +0000] [25612] [INFO] Starting gunicorn 19.9.0 [2019-07-23 12:39:24 +0000] [25612] [INFO] Listening at: http://0.0.0.0:8000 (25612) [2019-07-23 12:39:24 +0000] [25612] [INFO] Using worker: sync [2019-07-23 12:39:24 +0000] [25616] [INFO] Booting worker with pid: 25616 [2019-07-23 12:39:24 +0000] [25616] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/rahul/.local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/home/rahul/.local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/home/rahul/.local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/home/rahul/.local/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/rahul/.local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/home/rahul/.local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/home/rahul/.local/lib/python2.7/site-packages/gunicorn/util.py", line 350, in import_app __import__(module) File "/home/rahul/test_folder/wsgi.py", line 1, in <module> from app import app File "/home/rahul/test_folder/app.py", line 1, in <module> from flask … -
Processing classes for each request vs one POST method for them?
I am migrating a project from PHP to Django. In my PHP app, the admin panel has a table, and in each row there are multiple options that it looks for and processes each one differently. So for each request in those rows, I have made a processing class for it which handles it and redirects back to the admin panel. For example, "Approve" button pressed by a user from "manager" group works differently than a user from "superadmin". Right now I have a TemplateView like this: class ProcessLeaveRequest(TemplateView): template_name = 'process_leave_request.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) My question is, should I make a POST method in this class for each request that will be coming from process_leave_request.html, or should I make a separate class for each of those requests? What is the best practice for handling multiple requests from a single page which all do different tasks? -
how to make update without updating all fields in the form
i have a django website where it include an update function that filter the data based on the selected ID and return all the related values of the requested record. where the user is allow to edit data. and fields can't be empty. the update is done only if all the fields are edited my question is how to done the update even if just one field is edit views.py def update(request,pk): #deny anonymouse user to enter the create page if not request.user.is_authenticated: return redirect("login") else: dbEntry = suspect.objects.get(pk =pk) print( "db entry : ",dbEntry) if request.method == 'POST': first_name = request.POST['fname'] last_name = request.POST['lname'] fatherName = request.POST['fatherName'] motherName = request.POST['motherName'] gender = request.POST['gender'] content = request.POST['content'] dbEntry = suspect.objects.filter(pk = pk).first() if dbEntry: dbEntry.suspect_name = first_name dbEntry.suspect_last_name = last_name dbEntry.suspect_father_name = fatherName dbEntry.suspect_mother_name = motherName dbEntry.gender = gender dbEntry.content = content dbEntry.save() return redirect("list") print( "db entry after update: ",dbEntry) else: raise Http404('Id not found') return render(request,'blog/update.html', {"dbEntry":dbEntry}) update.html {% extends "base.html" %} {% load static %} {% block body %} <head> <link rel="stylesheet" type="text/css" href="{% static '/css/linesAnimation.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/input-lineBorderBlue.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/dropDown.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/home.css' … -
How to convert Mongodb models to Django Models
I would like to know how I would represent this Mongodb model in Django. I have little familiarity with Nosql group.js const GroupSchema = mongoose.Schema({ name: String, address: String, amount: Number, admin: { type: Schema.Types.ObjectId, ref: 'User' }, scheduleType: String, ScheduleCount: Number, cycleStart: Date, code: String, members: [{ type: Schema.Types.ObjectId, ref: 'User' }], paymentSchedule : [{ recipient: {type: Schema.Types.ObjectId, ref: 'User'}, date: Date, details: [{ member: {type: Schema.Types.ObjectId, ref: 'User'}, paid: Boolean }] }] }, { timestamps: true }); user.js const UserSchema = mongoose.Schema({ firstName: String, lastName: String, phone: String, username: String, email: String, password: String, creditScore: Number, bvn: String, paid: Boolean }, { timestamps: true }); schedule.js const ScheduleSchema = mongoose.Schema({ recipient: { type: Schema.Types.ObjectId, ref: 'User' }, date: Date, }, { timestamps: true }); cycle.js const CycleSchema = mongoose.Schema({ member: { type: Schema.Types.ObjectId, ref: 'User' }, datePaid: Date, paid: Boolean }, { timestamps: true }); I would like to get representation in Django so as to be able to build my own model -
How to sum conditional expression with argument repeated in Django
I have a Queryset. How can I sum 'output' that have value jam=('16-17','17-18','18-19') develop_queryset = InputCutSew.objects.filter(publish='2019-07-30').exclude(cell_name__isnull=True).exclude(cell_name__exact='').order_by('cell_name', 'jam').values('cell_name','model','jam').annotate\ (total_output_ot=Sum(Case(When(jam='16-17', jam='17-18', jam='18-19', then='output')))).exclude(total_output_ot__isnull=True) result: SyntaxError: keyword argument repeated -
How to write api test case for generic class based views in django rest framework?
Here i am writing some api test case for some create,update views and i tried like this.But this is giving me error.What i might be doing wrong?Is there any solution for this? self.assertEqual(response.status_code,status.HTTP_200_OK) AssertionError: 403 != 200 ---------------------------------------------------------------------- Ran 2 tests in 0.031s FAILED (failures=2) Destroying test database for alias 'default'... urls.py app_name = 'product' urlpatterns = [ path('create/', ProductCreateAPIView.as_view(), name='create-product'), path('list/', ProductListAPIView.as_view(), name='list-product'), path('detail/<int:pk>/', ProductDetailAPIView.as_view(), name='detail-product'), ] views.py class ProductCreateAPIView(generics.CreateAPIView): serializer_class = ProductSerializer permission_classes = [IsAdminUser] class ProductListAPIView(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [IsAdminUser] filter_backends = [DjangoFilterBackend] filterset_fields = ['name', 'description', 'category'] class ProductDetailAPIView(generics.RetrieveUpdateDestroyAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [IsAdminUser] tests.py CREATE_PRODUCT_URL = reverse('product:create-product') LIST_PRODUCT_URL = reverse('product:list-product') class CreateProductTest(APITestCase): def setUp(self): self.client = Client() def test_details(self): response = self.client.post(CREATE_PRODUCT_URL,format='json') print(response.status_code) self.assertEqual(response.status_code,status.HTTP_201_CREATED) class ListProductTest(APITestCase): def setUp(self): self.client = Client() def test_details(self): response = self.client.get(LIST_PRODUCT_URL,format='json') print(response.status_code) self.assertEqual(response.status_code,status.HTTP_200_OK) -
Calls to API Always Return “Authentication Credentials Were Not Provided” when accessed from Apple Shortcuts, but not from Postman
I’ve recently been developing a Django Application to auto-generate some schedules for me in TaskPaper form. I’ve been using django-rest-framework to automate a lot of the details of this but now I’ve come up against a problem I can’t fathom with authentication. I’m using django-rest-framework-simplejwt and the application is deployed on Heroku. When I test my app on my own machine I get the expected results, I can request the token and then using that I can request the data I want, all this is done using Postman. When I deploy the application to Heroku, and still use Postman again it all works as expected. However when I try and use Apple Shortcuts to request the data, getting the token is fine but when I try and GET the data using that token I get the error “Authentication Credentials Were Not Provided”. I looked through all the accepted answers and tried all the solutions there to no avail, so any help would be greatly appreciated and I can post any code snippets that might be required. -
Appending a col div with jQuery in a for loop only gives me results on the first row
I am retrieving an AJAX dump from a Django python Function. Then, I am trying to reflect the data on a bootstrap row + column table. However, when using append() in an array list, I only seem to get the first row of the dump. When I remove the 2nd for loop, the dump works fine, just does not give me the rows of the months that I need. I have more than one row worth of data, definitely. What could be causing this? //html code <div id="category_filtered_list"> <div class="row report_row mockup" id="category_mockup"> <div class="col-md-1 name"></div> <div class="col-md-1 code"></div> <div class="col-md-1 forecasted"></div> <div class="col-md-1 running_total"></div> <div class="monthsRows" id="monthsRows"></div> </div> </div> //Ajax JS function $.post( "", { "getcategories": true, 'date-from': date_from, 'date-to': date_to }, function(response) { $("#category_filtered_list .report_row.product").remove() data = JSON.parse(response); for (var i=0; i<data.length;i++){ obj = data[i] var mockup = $('#category_mockup') var temp_mockup = $(mockup).clone() $("#category_filtered_list").append(temp_mockup) $(mockup).attr('id',"temp_product"); var temp_prod = $("#temp_product") $(temp_prod).find('.name').html(obj.category_name) $(temp_prod).find('.code').html(obj.category_code) $(temp_prod).find('.minor').html(obj.category_minor) $(temp_prod).find('.parent').html(obj.category_parent) $(temp_prod).find('.forecasted').html(obj.category_forecasted) $(temp_prod).find('.running_total').html(obj.products_count) //this for loop is causing the issue ******* when removed, the rest of the code works fine. Please note that obj.prods_num_per_month is an array for (i=0; i<=obj.prods_num_per_month.length; i++){ $(temp_prod).find('.monthsRows').append( $('<div class="col-xs-1">').html(obj.prods_num_per_month[i]) ); } $(temp_prod).removeClass('mockup'); $(temp_prod).addClass('product'); $(temp_prod).attr('id','') } } ).done(function(){ $("#filtering .message_loading").html("Completed! <i class='far … -
How to send emails with Django for Password Reset?
I am trying to send password change link to an email address which a user will type. I typed my email but it is not sending me any link. How to resolve this issue? urls urlpatterns = [ path('password_reset/',auth_views.PasswordResetView.as_view (template_name='users/password_reset.html'), name='password_reset'), path('password_reset_done/',auth_views.PasswordResetDoneView.as_view (template_name='users/password_reset_done.html'), name='password_reset_done'), path('password_reset_confirm/',auth_views.PasswordResetConfirmView.as_view (template_name='users/password_reset_confirm.html'), name='password_reset_confirm')] settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') -
why the update function return int where it must return string?
i have a django website where it include an update function where the user is allow to edit data. the update is done and the data in the database is changed but the problem is that the system crash. and when i tried to print the result of the query the system return int where it should return string and it display the error below : dbEntry.save() #to save into DB AttributeError: 'int' object has no attribute 'save' views.py def update(request,pk): #deny anonymouse user to enter the create page if not request.user.is_authenticated: return redirect("login") else: dbEntry = suspect.objects.get(pk =pk) print( "db entry : ",dbEntry) if request.method == 'POST': first_name = request.POST['fname'] print("first_name : ", first_name) dbEntry = suspect.objects.filter(pk = pk).update(suspect_name = first_name) print( "db entry after update: ",dbEntry) dbEntry.save() #to save into DB return render(request,'blog/update.html', {"dbEntry":dbEntry}) update.html {% extends "base.html" %} {% load static %} {% block body %} <head> <link rel="stylesheet" type="text/css" href="{% static '/css/linesAnimation.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/input-lineBorderBlue.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/dropDown.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/home.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/meta-Input.css' %}"> <meta name= "viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript" src="{% static '/js/jquery-3.1.1.min.js'%}"></script> <title>Welcome</title> </head> <body> <div class="lines"> … -
How to use parameters defined in a triple quoted string(using eval()) outside the string in the method?
I am using triple quoted string, have if-else conditions inside the string, and defining the value of variable as per the conditions, and I am not able to use the variable outside the the string. I tried writing whole class inside of triple quoted string, and it works, I am able to use the variable outside the triple quoted string. It Works when whole class is inside the triple quote, it prints the variable 'a': import pystache codeBlock = ''' class GetData(): def foo(): a = 0 if({{c}} == 5): a = {{d}} * 5; elif({{c}} >= 5 and {{c}} < 10): a = {{d}} * 4; elif({{c}}<5): a = {{d}} * 10; return a ''' codeBlock1 = pystache.render(codeBlock, {'c': 3,'d':10}) compiledCodeBlock = compile(codeBlock1, '<string>', 'exec') eval(compiledCodeBlock) print(GetData.foo()) output: >python a.py runserver >100 And what I want is, the variable 'a' to be printed when the code block does not contain the whole class itself in the following case: (I am not sure if that's possible or not) import pystache class GetData(): def foo(): a = 0 codeBlock = ''' if({{c}} == 5): print('one'); a = {{d}} * 5; elif({{c}} >= 5 and {{c}} < 10): print('two'); a = {{d}} … -
How to implement autocomplete in django 2.2? I have tried existing one's but no support for django 2.2
I want to use autocomplete feature instead of select for my foreign key table value I have tried everything but its got compatibility issues. I need to display data in autocomplete field, rather than select field. I'm using django 2.2. -
show/hide django admin form field based on selection in another field
I am trying to have a Django admin form field to be hidden until I select a specific value from a drop-down I have tried everything including Jquery, the Jquery files load properly so my static root is pointing to the right file but when the admin site load and I change the values on the drop-down nothing happens. I am using the latest Django and python 3.7 also I am using Django-jet as a customize admin template models.py class Incident(models.Model): Incident_Type =models.ForeignKey(IncidentType,on_delete=models.DO_NOTHING, null=True, blank=False) DEM_REASON_CHOICES = (("Payments", "Payments"), ("Policies", "Policies"), ("Legal Issues", "Legal Issues"), ("Deactivation", "Deactivation")) demonstration_reason = models.CharField(max_length=200, choices=DEM_REASON_CHOICES, null=True, blank=True) admin.py @admin.register(IncidentType) class IncidentTypeAdmin(admin.ModelAdmin): @admin.register(Incident) class IncidentAdmin(admin.ModelAdmin): form = IncidentAdminForm forms.py from django import forms from .models import Incident class IncidentAdminForm(forms.ModelForm): class Meta: model = Incident widgets = { 'demonstration_reason': forms.SelectMultiple, } fields = "__all__" class Media: js = ('jet/showhide.js',) My Jquery script (function($) { $(function() { var selectField = $('#id_Incident_Type'), verified = $('#id_demonstration_reason'); function toggleVerified(value) { if (value === 'Demonstration') { verified.show(); } else { verified.hide(); } } // show/hide on load based on pervious value of selectField toggleVerified(selectField.val()); // show/hide on change selectField.change(function() { toggleVerified($(this).val()); }); }); })(django.jQuery); I am loading the script in my …