Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Json Post from Django to Camunda
Further to my earlier post yesterday: Post request to external Rest Service using Django - use returned json to update model I have managed to post data to camunda using Django - request.post. Using the following script: payload = "{\n \"businessKey\": \"SomeValue\",\n \"variables\": {\n \"Organisation_ID\": {\n \"value\": \"SOmeUUID\",\n \"type\": \"String\"\n },\n \"UserID\": {\n \"value\":\"Some User ID\",\n \"type\": \"String\"\n }\n }\n}" However when I start to use variables from the form and format my payload using class StartProcessView(View): template_name = 'startdeliveryphase.html' def get(self,request, *args, **kwargs): form = IntStartDeliveryPhase return render(request, self.template_name,{'form':form}) def post(self,request, *args, **kwargs): form = IntStartDeliveryPhase(request.POST or None) if form.is_valid(): data = form.cleaned_data OrganisationID = data['Form_Field_OrganisationID'] UserID = data['Form_Field_User_ID'] BusinessKey = data['Form_Field_Business_Key'] url = "http://localhost:8080/engine-rest/process-definition/key/Process_B_PerProject/start" payload = {"businessKey":BusinessKey,"variables":[{"Organisation":[{"value":OrganisationID, "type":"String"}]},[{"Startedby":[{"value":UserID,"type":"String"}]}]]} headers = { 'Content-Type': 'application/json' } response = requests.request("POST", url, headers=headers, data = payload) #print(repsonse.errors) print(response.text.encode('utf8')) return render(request) else: return render(request,self.template_name,{'form':form}) I get an error from the camunda engine:- b'{"type":"JsonParseException","message":"Unrecognized token \'businessKey\': was expecting (\'true\', \'false\' or \'null\')\\n at [Source: (org.camunda.bpm.engine.rest.filter.EmptyBodyFilter$1$1); line: 1, column: 13]"}' the local vars shows the following: ▼ Local vars Variable Value BusinessKey '1qaz' OrganisationID <Organisation: Some Local Authoristy> UserID <Actor_User: me@me.com> args () data {'Form_Field_Business_Key': '1qaz', 'Form_Field_CamundaInstanceID': 'sss', 'Form_Field_Camunda_HRef': 'ss', 'Form_Field_Camunda_TenantID': '22', 'Form_Field_DateCreated': datetime.datetime(2020, 4, … -
How can I retrieve an up-to-date reference to a many-to-many field in an object's save() method in django?
I have a model: class Camera(models.Model): users_allowed_to_view = models.ManyToManyField(User, ...) def save(self, *args, **kwargs): print(self.users_allowed_to_view.all()) super().save(*args, **kwargs) If I use Django Admin to modify a Camera, changing which list of users is allowed to view my camera, and hit Submit, the print statement above returns an old list of users (before the save currently in progress). Even if I move the print statement after super(), I still get an old list of users. Is there a way to get the new list of users that's about to be saved? Also, a related question - I'm pretty sure the .all() above does a DB query. Can I just get a list of IDs referenced by the field without doing a DB query, like you can for a ForeignKey field (by doing foreignkeyfield_id)? -
Django model testing
I want to create some tests in my app, but all the time i got some errors. Now i have information errors Creating test database for alias 'default'... System check identified no issues (0 silenced). ..E ====================================================================== ERROR: setUpClass (comments.tests.test_models.ReplyCommentModelTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\madas\OneDrive\Pulpit\Code\git-projects\django_tutek\djangoenv\lib\site-packages\django\test\testcases.py", line 1137, in setUpClass cls.setUpTestData() ....... raise TypeError( TypeError: Tried to update field comments.ReplyComment.author_reply with a model instance, <User: >. Use a value compatible with CharField. ---------------------------------------------------------------------- Ran 2 tests in 0.170s FAILED (errors=1) Tests from django.test import TestCase from django.contrib.auth.models import User from blog.models import Post, get_default_user from comments.models import Comment, ReplyComment class CommentModelTest(TestCase): @classmethod def setUpTestData(cls): cls.user = User(first_name='adam', is_staff=True, is_active=True, is_superuser=True) cls.user.save() cls.post = Post.objects.create(field='Python', title='Pierwszy post', slug='pierwszy-post', status=1) cls.post.save() cls.comment = Comment.objects.create(post=Post.objects.get(title='Pierwszy post'), author='robot', text='ok') cls.comment.save() def setUp(self): self.post = Post.objects.get(title='Pierwszy post') self.comment = Comment.objects.get(id=1) def test_str(self): self.assertEqual(self.comment.text, 'ok') def test_approve(self): self.assertFalse(self.comment.is_approved) self.comment.is_approved = True self.assertTrue(self.comment.is_approved) class ReplyCommentModelTest(TestCase): @classmethod def setUpTestData(cls): cls.user = User(first_name='adam', is_staff=True, is_active=True, is_superuser=True) cls.user.save() cls.post = Post.objects.create(field='Python', title='Pierwszy post', slug='pierwszy-post', status=1) cls.post.save() cls.comment = Comment.objects.create(post=Post.objects.get(title='Pierwszy post'), author='robot', text='ok') cls.comment.save() cls.reply_comment = ReplyComment.objects.create(comment_reply=Comment.objects.get(author='robot'), text_reply='not_ok') cls.reply_comment.save() def setUp(self): self.post = Post.objects.get(title='Pierwszy post') self.comment = Comment.objects.get(id=1) self.reply = ReplyComment.objects.get(id=1) def test_str(self): self.assertEqual(self.reply.text_reply, 'not ok') Models from django.db … -
Using Django to Query a SQL database
I am very new to Django, but just ran into an issue at work that hopefully we can use Django to resolve. Currently we have a outdated ticketing system that is using sql for the database. We are working on updating the ticketing system. When trying to import the data into the new system (same manufacture just newer system) it does not work. There Tech stated it is something with the way we set up our active directory. They said we can go forth with not updating it and start from scratch or call Microsoft on the issue. Would there be a way I can use Django to quary the ticketing systems database and pull the information to where I can display it using Django? -
Function 'doclist' has no 'filter' memberpylint(no-member)
It gives an error that Function 'doclist' has no 'filter' memberpylint(no-member) and please give suggestion if my code is correct related to search This Is My Model.py file class Document(models.Model): name = models.CharField(max_length=200) url = models.URLField(max_length=250) types = models.CharField(max_length=200) category = models.CharField(max_length=200) desc = models.TextField() upload = models.FileField(upload_to='documents') objects = models.Manager() class Meta: verbose_name_plural = "documents" def __str__(self): return self.name This is my View.py File def doclist(request): documents = Document.objects.filter() search_query = request.GET.get('q') if search_query : doclist = doclist.filter( Q(name__icontains = search_query) ) print(search_query) return render(request, 'doclist.html', { 'documents' : documents }) This is my Search Form <form method="GET" action="/doclist/"> {% csrf_token %} <div class="search-box"> <input type="text" class="search-txt" placeholder="Search Here" name="q" value="{{request.GET.q}}"> <button class="search-btn" type="submit" name="action"><i class="fas fa-search"></i></button> </form> -
Djano checking multiple variables in the view or the template?
I have site that the user selects a drop down menu item, inputs some JSON and then clicks "Parse". Then the JSON data is checked against certain properties based on the drop down menu item. Basically I have a list that looks like this.. myList = [{'Prop1': ['asdf', 'wefef']}, {'prop3': ['ss']}, {'prop2': ['d']}] This is all the data I am checking against. It is the property name and then a list of expected values for that property name. Then in the JSON I have to compare those properties against the JSON properties in the list above. Right now I am not sure where the best way to go about checking these. Should I do it in my views.py or should I do it in the page.html? Basically I will need to look through myList and check if that property is in the JSON. If so then I need to check it against the expected property. And then I need to print things in a row so that you can view the info like.. Property Excepted Value Actual Value P/F prop1 asdf, wefef apple F prop2 d d P prop3 ss sd F My issue is, this will be a bunch … -
How can I call a Django app from another Python app?
In the standard setup, Django applications are called by a WSGI server (like gunicorn and mod_wsgi) to answer HTTP requests, the entrypoint at user-level is the django View. Can I make a custom calling convention to call Django apps (a new entrypoint)? If so, How I properly load a Django app? -
Django, NoReverseMatch. What should I write in this code?
I have a problem: NoReverseMatch at /update-orders/12 Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) tried: ['update\-orders/(?P[0-9]+)$'] Request Method: GET Request URL: http://192.168.0.249:8000/update-orders/12 Django Version: 3.0.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) tried: ['update\-orders/(?P[0-9]+)$'] Exception Location: /root/.local/share/virtualenvs/myp4-4l8n6HJk/lib/python3.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677 Python Executable: /root/.local/share/virtualenvs/myp4-4l8n6HJk/bin/python Python Version: 3.7.3 Python Path: ['/var/workspace/myp4/webprint', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/root/.local/share/virtualenvs/myp4-4l8n6HJk/lib/python3.7/site-packages'] Why do I have this Error during template rendering? detail_order.html {% extends 'index.html' %} {% block content %} <p><a href="{% url 'orders' %}">Back</a></p> <h1>Заказ {{get_order.number_order}}</h1> <h2><a href="{% url 'update_order' get_order.id %}">Update</a></h2> views.py class UpdateOrderView(CustomSuccessMessageMixin, UpdateView): model = Order template_name = 'detail_order.html' form_class = OrderForm success_url = reverse_lazy('detail_order') success_msg = 'Ok' def get_context_data(self, **kwargs): kwargs['update'] = True return super().get_context_data(**kwargs) urls.py from django.contrib import admin from django.urls import path, include from .views import * from print import views urlpatterns = [ path('', views.home_page, name='index'), path('orders', views.OrderCreateView.as_view(), name='orders'), path('update-orders/<int:pk>', views.UpdateOrderView.as_view(), name='update_order'), # THIS PATH path('delete-orders/<int:pk>', views.DeleteOrderView.as_view(), name='delete_order'), path('detail-order/<int:pk>', views.DetailOrderView.as_view(), name='detail_order'), path('login', views.MyprojectLoginView.as_view(), name='login_page'), path('register', views.RegisterUserView.as_view(), name='register_page'), path('logout', views.MyprojectLogout.as_view(), name='logout_page'), ] -
Django REST framework TokenAuthentication - Unauthorized 401
I'm using axios to get data from Django server. getQuestionsPage(page) { return axios.get(`${API_URL}/questions/?page=${page}`, c.getHeaders).then(response => response.data); } getQuestionsURL(url) { return axios.get(url, c.getHeaders()).then(response => response.data); } Both URLs are the same, but when I getQuestionsPage(page) is called, the request is unauthorized. [23/Apr/2020 17:59:41] "GET /questions/?page=2 HTTP/1.1" 401 58 [23/Apr/2020 17:59:41] "GET /questions/?page=2 HTTP/1.1" 200 3489 How can I solve this problem? -
ChartJS : It's not showing in html on Django
I will plot horizontal bar chart in html but it's not showing. I send 2 variable from views.py are {{top5StockCode}} and {{top5TotalSales}}. The values of {{top5StockCode}} that views.py sent is ['23166', '21108', '85123A', '48185', '22470'] and {{top5TotalSales}} is [2671740, 227322, 171770, 158120, 143808]. This is my code in html file. <div class="top5"> <p class="topicTop5">Top 5 Selling Products</p> <canvas id="top5"></canvas> </div> <script> var top5 = document.getElementById('top5').getContext('2d'); var chart = new Chart(top5, { type: 'horizontalBar', data: { labels: {{top5StockCode}}, datasets: [{ label: 'Top 5 selling products ', backgroundColor: '#CE3B21', borderColor: 'rgb(255, 99, 132)', data: {{top5TotalSales}} }] }, options: { legend: { display: false }, responsive: true, maintainAspectRatio: false, scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); </script> I'm so confused why it's not showing graph. Please help me. Thank -
I'm getting django.db.utils.IntegrityError: FOREIGN KEY constraint failed in cmd
I copied a json file from online. I'm using it for django project in sublime text 3. I entered the following lines in cmd - >>> import json >>> from blog.models import Post >>> with open('posts.json') as f: ... posts_json=json.load(f) ... >>> for post in posts_json: ... post = Post(title=post['title'], content=post['content'], author_id=post[' user_id']) ... post.save() ... And the error I got was - Traceback (most recent call last): File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 3, in <module> File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\base.py", line 745, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\base.py", line 782, in save_base updated = self._save_table( File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\base.py", line 887, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields , raw) File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\base.py", line 924, in _do_insert return manager._insert( File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\query.py", line 1204, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\sql\compiler.py", line 1391, in execute_sql cursor.execute(sql, params) File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang … -
CORS_ORIGIN_WHITELIST inside a environment file in django
I need to configure the whitelist for the CORS policy inside my django app. Instead of hardcode the urls inside settings.py, I'd like to put them inside a separate file, like the .env file from django-environ. This is my code: .env DEBUG=on SECRET_KEY='xxx' DATABASE_URL=psql://xxx CORS_ORIGIN_WHITELIST=http://127.0.0.1:4200 settings.py (MIDDLEWARE and INSTALLED_APPS are fine) ... environ.Env.read_env() ... CORS_ORIGIN_WHITELIST = env('CORS_ORIGIN_WHITELIST') I get the following error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/david/errepiu-project/backend/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/david/errepiu-project/backend/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/david/errepiu-project/backend/venv/lib/python3.7/site-packages/django/core/management/base.py", line 441, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (corsheaders.E013) Origin '.' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '.' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '.' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '/' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. … -
Importing CSV file to MySQL table made in Django Models.py
I'm attempting to import a CSV file into a table in MySQL, the table being made in a Django models.py file and then migrated over. I am able to import CSV files into tables made in MySQL but when I attempt to import into the models.py made tables I get "0 records imported". Could someone help enlighten me to my mistakes? Relevant code and process screenshots below Models.py from django.db import models # Create your models here. class StudentDetails(models.Model): firstname = models.CharField(max_length=500) lastname = models.CharField(max_length=500) major = models.CharField(max_length=500) year = models.CharField(max_length=50) GPA = models.DecimalField(max_digits=3, decimal_places=3) class CourseDetails(models.Model): courseID = models.IntegerField() coursetitle = models.CharField(max_length=500, default="class") coursename = models.CharField(max_length=500) coursesectioncode = models.IntegerField(default="101") coursedept = models.CharField(max_length=500, default="college") courseinstructor = models.CharField(max_length=500, default="professor") Import process -
Django test does not add coverage with AssertRaises
There two lines that are not being executed by django tests when they are called as self.assertRaises. I am using: Python 3.6.9, Django 3, Coverage. I have this class: class AverageWeatherService: subclasses = WeatherService.__subclasses__() valid_services = { subclass.service_key: subclass for subclass in subclasses } @classmethod def _check_service(cls, one_service): if one_service not in cls.valid_services: logger.exception("Not valid service sent") raise NotValidWeatherFormException("Not valid service sent") And I have a local API that is up in my pc. Then I wrote this test: def test_integration_average_temp_services_error(self): self.assertRaises ( NotValidWeatherFormException, AverageWeatherService()._check_service, "MyFakeService", ) And although the test is successful with assert raises properly used this test is not adding coverage but If I call this method in a wrong way like this one: def test_integration_average_temp_services_error2(self): self.assertRaises ( NotValidWeatherFormException, AverageWeatherService()._check_service("MyFakeService") ) Then of course I get an error running the test because the exception is raised and not properly catched by assertRaises BUT It adds coverage. If I run this test wrongly I have my code 100% covered. If I use assertRaises as the first way these two lines are not being covered (According to coverage html). logger.exception("Not valid service sent") raise NotValidWeatherFormException("Not valid service sent") Also If I execute the method as the first way, the … -
after login through django social all_auth after redirect to webpage again webpage is refereshing when clicking on to it
i have used social django all_auth for login through gmail and it redirects to the page where i want but i am facing a problem after login through gmail it again refereshing the webpage and i want to perform two operations through textarea first it redirect me to gmail login after login when it returns back to the same page it takes input to it but whenever i click it refereshes the webpage and input not shows just bacause of that refereshing. here is myhtml code" <form id="new_user_form"> <a href="{% provider_login_url 'google'%}"> <textarea style=" width: 500px; border: 2px solid #333; padding: 15px 10px;"placeholder="Add Your Comment"></textarea></a> -
how to make edit functionality edit by using django form
I work on this project and i reached at a point where i am suppose to make edit functionality,I have two models child and *parent * models and these two models have relationship to each other and also in a template where i want to edit parent details i pass a child id, here is my child model from django.db import models class Child_detail(models.Model): Firstname = models.CharField(max_length = 50) Lastname = models.CharField(max_length = 50) def __str__(self): return self.Firstname here is my parent model class Parent(models.Model): child = models.ForeignKey(Child_detail,on_delete=models.CASCADE) Parent_firstname = models.CharField(max_length = 100) Parent_lastname = models.CharField(max_length = 100) Current_address = models.CharField(max_length = 100) def __str__(self): return str(self.Parent_firstname) here is views.py file for editing parent details def edit_parent(request,pk): child=get_object_or_404(Child_detail,pk=pk) form=ParentForm(request.POST) if form.is_valid(): form.instance.child=child form.save() return redirect('more_details',pk=pk) else: form=ParentForm() context={ 'form':form, 'child':child } return render(request,'functionality/parents/edit.html',context) here is form.py file class ParentForm(forms.ModelForm): class Meta: model=Parent fields=['Parent_firstname','Parent_lastname','Current_address','Phone_number','Parent_job', 'Life_status','Other_parent_name','Other_parrent_phone_number'] labels={ 'Parent_firstname':'Parent Firstname','Parent_lastname':'Parent Lastname', 'Other_parent_name':'Other Parent Name', 'Current_address':'Current Address','Phone_number':'Phone Number', 'Other_parrent_phone_number':'Other Parent Phone Number', } -
Django Variable Number of ChoiceFields
I am making a form in Django where the user reads a paragraph, then is asked a variable number of questions about the paragraph (the content of the paragraphs and the number of questions per paragraph is is stored in Django models). For each question, I need to display a ChoiceField (the same one for each question). What is the best way to display the ChoiceFields and then read the data (i.e namespacing each separate question). I have already looked into FormSet which I do not think will work for my purposes. Any help is appreciated! -
Problem getting "first_name" and "last_name" from User model
I'm creating the Client model like this: from django.db import models from django.contrib.auth.models import User from platforms.models import Platform class Client(models.Model): """Model definition for Client.""" user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.CharField(("Compañía"), max_length=50) platforms = models.ManyToManyField(Platform, verbose_name=("Plataformas")) class Meta: """Meta definition for Client.""" verbose_name = 'Cliente' verbose_name_plural = 'Clientes' def __str__(self): """Representación de cliente.""" company = "Sin empresa" if self.company: company = self.company string = "{} {} ({})".format(self.user.first_name, self.user.last_name, company) return string But in this part, when I try to get the first_name and user_name I get an error: string = "{} {} ({})".format(self.user.first_name, self.user.last_name, company) This is the error: Instance of 'OneToOneField' has no 'first_name' member Why does this happen? "User" model should have first_name and last_name right? Thank you? -
Django filter my admin list for another field
In my django project i have this model: class as_clienti(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True ) id_ag = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ag_user",null=True, blank=True ) Codice = models.IntegerField() Nome = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.Nome well i would in my django admin when i open the as_clienti link to see the list containing data filtered for logged user but on column id_ag So in my admin.py i do: class as_clientiAdmin(FilterUserAdmin): def get_queryset(self, request): qs = super(as_clientiAdmin, self).get_queryset(request) return qs.filter(id_ag_id=request.user.id) but my django admin page remain blank with 0 rows returned message. Where am i wrong in my code? So many thanks in advance -
Using nested loop in django template
Hi i have a template where i used nested loop like fetching data from two table. html file <div class="content"> <ul class="dashboard-box-list"> {% for form in user.userselecttest_set.all %} <li> <div class="invoice-list-item"> <strong>{{ form.testselected }}</strong> <ul> {% for ut in user.usertest_set.all %} <li>{{ ut.totalprice }}</li> </ul> </div> </li> {% endfor %} {% endfor %} i have two table in models name "UserSelectTest" and "UserTest". So from "UserSelectTest" i retrieve items and "UserTest" thier price i am achieving in displaying the item but in price i get all values for example: Item Price A 120,70 B 120,70 but i want: Item Price A 120 B 70 I am getting confused in nested for loop hope i am making sense i know i am making some silly mistake , Please help. -
Django ASGI Deployment on Heroku
I want clear cut explanation of how should I deploy django 3.x and channels 2.x on heroku. my asgi.py file import os import django from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mainProj.settings') django.setup() application = get_default_application() -
Overriding admin template works in local not in server
I have project like this structure /-myapp-templates-admin-myapp-myModel-change_list_result.html -change_list.html -base_site.html -base.html -myapp-index.html -base.html When I edit change_list_result.html the edited admin page works on python manager.py runserver. However not on server apache. I guess somehow change_list_result.html is not over-rided on apache server. Does anyone know the reason?? -
Javascript with Crispy Forms
I am using django-crispy-forms but would like to add some super simple JS to change the value of the submit button depending on if a checkbox is checked or not. Here's the generate HTML for the checkbox <div class="form-group"> <div id="div_id_draft" class="custom-control custom-checkbox"> <input type="checkbox" name="draft" class="checkboxinput custom-control-input" id="id_draft"> <label for="id_draft" class="custom-control-label"> Draft </label> </div> </div> <input type="submit" name="submit" value="Post" class="btn btn-primary" id="submit-id-submit"> Here is the JS I am trying to use: function draftbox() { var checkBox = document.getElementById('id_draft') var button = document.getElementById('submit-id-submit') if (checkBox.checked == true){ button.value = 'Save'; } else { button.value = 'Post'; } } Currently, when I click the checkbox, I get no changes in the submit button, but I would like for the "Post" in the submit button to change to "Save" when the checkbox is checked. -
mitmproxy 5.1.1 always crashed
I encountered mitmproxy crash issue with Windows 10 64-bit build 19041.207 Following are my crash logs Mitmproxy: 5.1.1 build pypi_0 from pypi Python: 3.7.6 from conda-forge OpenSSL: 1.1.1g build he774522_0 from conda-forge pyopenssl: 19.1.0 build py_1 from conda-forge cryptography: 2.9.2 build pypi_0 from pypi ================== D:\Dev\Anaconda3\envs\WXC_prj\python.exe D:/Dev/Anaconda3/envs/WXC_prj/src/main.py 2020-04-23 22:40:16.216 | INFO | web_server::32 - Gevent server mode 2020-04-23 22:40:19.039 | INFO | web_server::32 - Gevent server mode `Proxy server listening at http://*:8080 192.168.1.17:58307: clientconnect 192.168.1.17:58309: clientconnect 192.168.1.17:58307: Traceback (most recent call last): File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\server.py", line 121, in handle root_layer() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\modes\http_proxy.py", line 9, in call layer() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\tls.py", line 285, in call layer() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\http1.py", line 83, in call layer() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\http.py", line 190, in call if not self._process_flow(flow): File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\http.py", line 262, in _process_flow return self.handle_regular_connect(f) File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\http.py", line 208, in handle_regular_connect layer() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\tls.py", line 278, in call self._establish_tls_with_client_and_server() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\tls.py", line 358, in _establish_tls_with_client_and_server self._establish_tls_with_server() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\tls.py", line 448, in _establish_tls_with_server **args File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\connections.py", line 292, in establish_tls self.convert_to_tls(cert=client_cert, sni=sni, **kwargs) File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\net\tcp.py", line 386, in convert_to_tls **sslctx_kwargs File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\net\tls.py", line 285, in create_client_context param = SSL._lib.SSL_CTX_get0_param(context._context) AttributeError: module 'lib' has no attribute 'SSL_CTX_get0_param' Traceback (most recent call last): File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\server.py", line 121, in handle root_layer() File … -
Django clean() function for form validation doesn't work
I created this simple form, but the function clean() doesn't work when I intentionally pass invalid data. here is the code: from django import forms SELECT_GENDER = ( ('M', 'Male'), ('F', 'Female'), ) SUBSCRIPTION = ( ('Pro', 'Professional'), ('Premium', 'Premium'), ('trial', '14 Days Trial') ) class FormsProject(forms.Form): fullname = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control mb-3', 'placeholder': 'Basir Payenda'})) django = forms.BooleanField( widget=forms.CheckboxInput(), required=False) flask = forms.BooleanField( widget=forms.CheckboxInput(), required=False) gender = forms.ChoiceField( widget=forms.RadioSelect(), choices=SELECT_GENDER) comments = forms.CharField(widget=forms.Textarea(attrs={ 'class': 'form-control mb-2', 'rows': 4, }), help_text='Write here your message!') subscription_plan = forms.ChoiceField( choices=SUBSCRIPTION, widget=forms.Select(attrs={ 'class': 'form-control mb-3' })) def clean(self): super(FormsProject, self).clean() fullname = self.cleaned_data.get('fullname') if len(fullname) < 5: raise forms.ValidationError("ERRRRRRRRROR") return self.cleaned_data The form is rendered in template without any issue. The only thing is that it don't show validation error. Thanks