Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JSON Decode Error:Expecting value: line 1 column 1 (char 0)
I am running a admin website using Django. Trying to login my admin site and i am getting JSON Decode error.The response i am getting is 404 server error. Can anyone help to get out of this? Here is my views.py: def user_login(request): datas= {'log':False} if request.method == "POST": usern=request.POST.get('Username') print(usern) passw=request.POST.get('password') print(passw) response = requests.post(url='http://www.onebookingsystem.com/productionApi/API/Admin/login.php',data={"Username":usern,"password":passw}) print(response) json_data = response.json() print(json_data) if json_data['status'] == 1: user=authenticate(Username=usern,password=passw) login(request,user) range_yearly = 0 range_monthly = 0 respo = requests.get(url='http://www.onebookingsystem.com/productionApi/API/Admin/admin_dashboard.php') data_dash = json.loads(respo.text) The error i am getting is: <Response [404]> Internal Server Error: / Traceback (most recent call last): File "C:\Users\Android V\Anaconda3\envs\djangoenv\lib\site-packages\django\cor e\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Android V\Anaconda3\envs\djangoenv\lib\site-packages\django\cor e\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Android V\Anaconda3\envs\djangoenv\lib\site-packages\django\cor e\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Android V\admin\obs_app\views.py", line 20, in user_login json_data = response.json() File "C:\Users\Android V\Anaconda3\envs\djangoenv\lib\site-packages\requests\m odels.py", line 897, in json return complexjson.loads(self.text, **kwargs) File "C:\Users\Android V\Anaconda3\envs\djangoenv\lib\json\__init__.py", line 354, in loads return _default_decoder.decode(s) File "C:\Users\Android V\Anaconda3\envs\djangoenv\lib\json\decoder.py", line 3 39, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\Android V\Anaconda3\envs\djangoenv\lib\json\decoder.py", line 3 57, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) … -
Ensure that urlpatterns is list of path() and/or re_path() instances
(urls.E004) Your URL pattern [.*)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances Why i am getting this error.. My url pattern list is as if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT), -
Django Changes Type of Variable on Override Save Function Call
Django seems to be changing the type of my variable after calling the resizeUplaodedImage method from type str to type Project while overriding the save method. I previously had this method working properly, but then I moved the logic outside of the save method and into another one that is called inside of save. I did this so I could do multiple things before saving but it seems now when I call the resizeUploadedImage method the variable I pass is being changed from a str to a Project. def save(self, *args, **kwargs): if self.image: url = self.image.url surl = url.split('/') fname = surl[-1] print('\t TRYING TO RESIZE IMAGE') print('filename',fname) print('top type', type(fname)) self.resizeUploadedImage(self, fname) # the additional function I wanted to add # self.createThumbnail(self, fname) super(Project, self).save(*args, **kwargs) def resizeUploadedImage(self, fname, *args): '''Resize the image being uploaded.''' print('resize top type', type(fname)) try: im = Image.open(self.image) print(im.size) if im.size > IMAGE_SIZE: im_sized = im.resize(IMAGE_SIZE, Image.ANTIALIAS) image_io = BytesIO() im_sized.save(image_io, im.format) print('resize type', type(fname)) self.image.save(fname, ContentFile(image_io.getvalue(), False)) except IOError as e: print("Could not resize image for", self.image) print(e) When I run this inside the Django shell, it works properly and resizes the image however when I run my tests I get TypeError: … -
How to prevent duplicate data entries in my model after reloading a get request in django
I am trying to load data from an external api into my django model. How can I prevent the data being duplicated each time it is pulled. It is a restaurant POS API and so as a customer orders new items they will get added to the bill JSON Object Example: After ordering drinks the waiter inputs the order to the POS and the API endpoint looks like this: [ { "pk": 1, "Description": "Coca Cola", "Price": "5.95" }, { "pk": 2, "Description": "Water", "Price": "3.50" } ] Then the waiter comes back to take the customers food order and inputs it to the POS, then the api endpoint looks like this: [ { "pk": 1, "Description": "Coca Cola", "Price": "5.95" }, { "pk": 2, "Description": "Water", "Price": "3.50" }, { "pk": 3, "Description": "Pizza", "Price": "12.00" }, { "pk": 4, "Description": "Pasta", "Price": "11.50" } ] I have these tables in my models.py class Restaurant(models.Model): Name Address class Table(models.Model): Restaurant_ID -> (ForeignKey From Restaurant) Table_Number API_Endpoint class Bill(models.Model): Table_ID -> (ForeignKey from Table) Bill_Status -> Binary field Can be 'Open' or 'Closed' Date -> DateTime of bill closed class Bill_Items(models.Model): Bill_Item_ID -> (ForeignKey from Bill) Description Price Payment_Made Date … -
django bootstrap 4 navbar toggler button not working on localhost
I am building a web app with django and bootstrap 4 on localhost. I have loaded the jquery, popper and bootstrap on the end of my body tag on the base.html file. Whiles in mobile screen size, the toggler button doesn't work. It doesn't display my menu or close it. I don't know what the problem is. I have checked other solutions but it still doesn't work. Please help! this is my code ''' {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> {% if title %} <title>Django blog - {{ title }}</title> {% else %} <title>Django blog</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'blog-home' %}">Django Blog</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data- target="#navbarResponsive"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'blog-home' %}">Home</a> <a class="nav-item nav-link" href="{% url 'blog-about' %}">About</a> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> {% if user.is_authenticated %} <a class="nav-item nav-link" href="{% url 'post-create' %}">New Post</a> <a class="nav-item … -
Should I use django-allauth or code my own authorization app?
I'm writing a web app and I notice a lot of people use django-allauth for their user authentication. It seems to be the most popular authentication app out there, but I'm wondering if this is the industry standard to use it or if most people code their own authentication apps. I'm also wondering how easy is it to customize, like change the templates, the url paths or the user models to add functionality. Thanks -
Push live HTML content updates using channels
I am attempting to modify the HTML content on a page for all connected users. Currently, when sending a message using the consumer it only sends it to the instance that initiated the initial message calling for the update (i.e. if a user presses a button that changes HTML content by sending a WebSocket event, only the content of their instance of the page is changed). Here is my current consumer: class ScoreConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected ", event) await self.send({ 'type': 'websocket.accept' }) async def websocket_receive(self, event): print("receive ", event) data = event.get('text', None) print(data) if data: loaded_data = json.loads(data) await self.send({ 'type': 'websocket.send', 'text': loaded_data['message'] }) async def websocket_disconnect(self, event): print("disconnected ", event) and here is the JavaScript (with unnecessary parts omitted) that initiates and handles the messages var loc = window.location; var wsStart = 'ws://' if (loc.protocol == 'https:'){ wsStart = 'wss://'; } var endpoint = wsStart + window.location.host + loc.pathname; var socket = new WebSocket(endpoint); console.log(endpoint); socket.onmessage = function(e){ console.log("Got websocket message " + e.data); var data = e.data; console.log(data); if (data == 'connected') { document.querySelector('#bluescore').innerHTML = "User Connected"; } else { document.querySelector('#redscore').innerHTML = data; } } document.querySelector('#test-button').onclick = function(e) { var message = "Yee"; … -
How to perform batch update in django rest api
table structure cart_id, product_id, quantity,customer_id view class CartUpdateView(generics.UpdateAPIView): queryset = models.Cart.objects.all() serializer_class = CartSerializer def put(self, request, *args, **kwargs): data = request.DATA serializer = CartSerializer(data=data, many=True) if serializer.is_valid(): serializer.save() return Response(status=HTTP_200_OK) else: return Response(status=HTTP_400_BAD_REQUEST) serializers class CartSerializer(serializers.ModelSerializer): class Meta: model = Cart fields = ('cart_id', 'quantity', 'customer_id', 'product_id') model class Cart(models.Model): cart_id = models.IntegerField() product_id = models.IntegerField() quantity = models.IntegerField() customer_id=models.IntegerField() Im trying to update my cart with the data { [cart_id:1, product_id:3, quantity:5,customer_id:2], [cart_id:2, product_id:4, quantity:2,customer_id:2], [cart_id:3, product_id:5, quantity:1,customer_id:2], [cart_id:4, product_id:8, quantity:1,customer_id:2], } So far i did only single row updation. Is there a way to perform bulk update.. Do i need to override any methods..! -
Get Info From Model/Middleware And Pass To A Template
How do I go about passing the reason to banned.html from the UserBanning model from the middleware file? Almost everything works but I can't seem to get the reason from the model to display in the template banned.html and im unsure way so any help will be amazing just got into learning about middleware. Thanks models.py: from django.db import models from django.contrib.auth.models import User from django.conf import settings class UserBanning(models.Model): user = models.ForeignKey(User, verbose_name="Username", help_text="Choose Username", on_delete=models.CASCADE) ban = models.BooleanField(default=True, verbose_name="Ban", help_text="Users Bans") reason = models.CharField(max_length=500, blank=True) class Meta: verbose_name_plural = "User Banning" ordering = ('user',) def __str__(self): return f"{self.user}" middleware.py: from .models import UserBanning from django.shortcuts import render class BanManagement(): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) banned = UserBanning.objects.all() context = { 'banned': banned, } if(banned.filter(ban=True, user_id=request.user.id)): return render(request, "account/banned.html", context) else: return response banned.html: {% extends "base.html" %} {% block content %} <p>Your account has been banned. Reason: {{ banned.reason }}</p> {% endblock content %} -
ModelForm's data attribute returns a tuple in Django shell
Upon reading how to create custom Form widgets, I noticed the documentation details passing widget attributes in the ModelForm constructor. https://docs.djangoproject.com/en/2.2/ref/forms/widgets/#customizing-widget-instances Attempting to emulate this in the Django shell, the form instance's data attribute returns a tuple and not a dictionary. I'm not clear on what is causing this behavior. from django.db import models class Person(models.Model): lastname = models.CharField(verbose_name="Last Name", max_length=20) firstname = models.CharField(verbose_name="First Name", max_length=20) age = models.CharField(verbose_name="Age", max_length=20) from django import forms from .models import Person class PersonForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.fields['firstname'].widget.attrs.update({'placeholder': 'First Name'}) class Meta: model = Person fields = '__all__' #django shell >>> person = PersonForm({'lastname': 'Monster', 'firstname': 'Cookie', 'age': 53}) >>> person.data ({'lastname': 'Monster', 'firstname': 'Cookie', 'age': 53},) -
Chrome Webdriver Options aren't affecting my test at all
So as a newbie in web development, my current topic is TDD, and thus i was tasked to deploy a web to heroku that has Functional Test on it. And so i wrote the code below. When i run test the code, the webdriver still open a Chrome window, even though i already added the argument '--headless' from selenium import webdriver from selenium.webdriver.chrome.options import Options class FunctionalTest(TestCase): def setUp(self): chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-infobars") chrome_options.add_argument("--disable-extensions") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--dns-prefetch-disable") self.browser = webdriver.Chrome(chrome_options=chrome_options) by the way, i put the Chromedriver in Program Files so i don't need to put 'executable_path' argument -
Celery(with django/redis)- Function with api calls works as a normal function, once add .delay() to add it to asynchronous task queue, I get SSL error
I have celery setup fine in that it works for simple tasks like a hello world (calling hello_world.delay() in django views there is no problem). I created another more complicated function that involves making many calls to a an api to retrieve data to update the database. Just calling this function without celery (update_comments()) there is no problem, and the database gets updated(takes around 15 seconds or so...that is why I want to use celery). Currently the function makes dozens of calls to the api to update the model. The problem is once I add .delay() to make it a celery task. I get the below errors (maxretry ssl error). I know I have celery setup correctly for basic tasks as it works fine for a basic hello world function, but not this more complicated function with many api calls. I can't figure out why there is this disparity or if there is any setting I am supposed to change because I have an api call. Currently just running on dev. Tasks @task() def update_comments(): for channel in Channel.objects.all(): search_url='https://www.googleapis.com/youtube/v3/commentThreads' params1={ 'part': 'replies,snippet', 'allThreadsRelatedToChannelId': channel.channel, 'searchTerms': '#vi', 'maxResults': 100, 'order': 'time', 'key' : settings.YOUTUBE_API_DATA_KEY } params2={ 'part': 'replies,snippet', 'allThreadsRelatedToChannelId': channel.channel, … -
TypeError Return on cURL command to Django DRF
When testing my API through cURL I'm getting an TypeError response (500 Internal Server Error) even though my data is saving to the database. When I remove save_task = serializer.save() from the views.py I get a 200 response, but the data is not saved to the database. Any ideas on what could be causing this? cURL Command: curl -kiu root:password -X POST -d "task=Register&creator=POAP Script&owner=Register Microservice&mac=00:00:00:00:00:00&ip=172.16.24.24" http://192.168.1.100/api/task/ cURL Error: HTTP/1.1 500 Internal Server Error Server: nginx/1.14.1 Date: Fri, 01 Nov 2019 22:45:21 GMT Content-Type: text/plain; charset=utf-8 Content-Length: 12593 Connection: keep-alive X-Frame-Options: SAMEORIGIN Vary: Cookie TypeError at /api/task/ 'Task' object is not callable Request Method: POST Request URL: http://192.168.1.100/api/task/ Django Version: 2.2.6 Python Executable: /usr/local/bin/uwsgi Python Version: 3.6.8 Python Path: ['.', '', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/opt/django/lib64/python3.6/site-packages', '/opt/django/lib/python3.6/site-packages'] Server time: Fri, 1 Nov 2019 22:45:21 +0000 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'task', 'rest_framework'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/opt/django/lib64/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/opt/django/lib64/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/opt/django/lib64/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/django/lib64/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/opt/django/lib64/python3.6/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/opt/django/lib64/python3.6/site-packages/rest_framework/views.py" … -
Browser is not loading page
Good day. I am new to django. I just build my Listview and detailview for my app. But when ever i try to run my program on a server, i found the following problems. Please find the images The error am getting on the browser is page not found The current path products/ does not match any of the urls in my app -
verifying users email using django rest auth as a rest API
I am creating a rest API and using Django-rest-auth, and want to verify users' email. Everything works until I click the link to verify the user's email. earlier I got an error, but I eventually got it fixed, the problem was that the fix made it no longer restful. I later found out in the documentation an idea to why I was getting this problem https://django-rest-auth.readthedocs.io/en/latest/faq.html after searching online I found some fixes that worked to some degree, BUT the email still did not verify after clicking the link, although I wasn't getting errors like before. my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', 'users', ] ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_LOGOUT_ON_GET = True ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 # 1 day in seconds ACCOUNT_LOGOUT_REDIRECT_URL ='/accounts/login/' LOGIN_REDIRECT_URL = '/accounts/profile' SOCIALACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'test@gmail.com' EMAIL_HOST_PASSWORD = 'test' DEFAULT_FROM_EMAIL = 'test@gmail.com' DEFAULT_TO_EMAIL = EMAIL_HOST_USER EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/' my urls.py from django.contrib import admin from django.urls import path, re_path from django.conf.urls import … -
How to build database API with Django that connects bridge to local server?
I want to implement a website that serves as an API to a database on one of our servers. The server is secure and can only be accessed on site. So to push data from the server, a bridge computer must be used. I want to set up a site where users can request access, filter a database, and then retrieve files based on their filtering criteria. For example, if a user wants all files for a subject aged 50 years, then a command needs to be executed on the host machine connected to the correct network to retrieve those files (based on an identifier) from the secure server, then send to the user, perhaps after performing a couple of additional operations on the host machine (python and bash scripts). I want to build all of this in python (Django) and mysql (if necessary). Would a set up like this be possible? -
Javascript Fetch - Get data from server when ok = false
I want to make an POST request to my server using the fetch method. If the request was successfully, it returns status code 200 with data. If there was an error, it returns any status code except 200 with a message. Here's my JS code: class Ajax{ static Post(url, data, success, error=null){ const csrftoken = data["csrfmiddlewaretoken"]; delete data["csrfmiddlewaretoken"]; fetch(url, { method: "POST", credentials: 'same-origin', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', "X-CSRFToken": csrftoken }, body: JSON.stringify(data) }) .then(response => { const data = response.json(); if (response.ok){ return data } else { throw {"name": "ResponseNotOkError", "message": data["message"], "status": response.status}; } }) .then(success) .catch(err => { if (error !== null){ error(err.message, err.status); // custom function } else { TinyText.Create(err.message); // Showing error } }); } } For debugging I inserted this into the first line after my ajax function in my Django project: return JsonResponse({ "message": "Blablablabla" }, status=400) I don't know how to access that message. -
heroku logs --tail : gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
I have just deployed my Django app to Heroku but it is not running. I checked the logs and found this error: 2019-11-01T22:07:40.39246+00:00 app[web.1]: Traceback (most recent call last): 2019-11-01T22:07:40.392462+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2019-11-01T22:07:40.392465+00:00 app[web.1]: worker.init_process() 2019-11-01T22:07:40.392467+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process 2019-11-01T22:07:40.392469+00:00 app[web.1]: self.load_wsgi() 2019-11-01T22:07:40.392471+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2019-11-01T22:07:40.392472+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2019-11-01T22:07:40.392475+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2019-11-01T22:07:40.392476+00:00 app[web.1]: self.callable = self.load() 2019-11-01T22:07:40.392478+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load 2019-11-01T22:07:40.39248+00:00 app[web.1]: return self.load_wsgiapp() 2019-11-01T22:07:40.392482+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp 2019-11-01T22:07:40.392484+00:00 app[web.1]: return util.import_app(self.app_uri) 2019-11-01T22:07:40.392486+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app 2019-11-01T22:07:40.392488+00:00 app[web.1]: __import__(module) 2019-11-01T22:07:40.392489+00:00 app[web.1]: File "/app/pur_beurre/pur_beurre/wsgi.py", line 16, in <module> 2019-11-01T22:07:40.392492+00:00 app[web.1]: application = get_wsgi_application() 2019-11-01T22:07:40.392494+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2019-11-01T22:07:40.392495+00:00 app[web.1]: django.setup(set_prefix=False) 2019-11-01T22:07:40.392497+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 19, in setup 2019-11-01T22:07:40.392499+00:00 app[web.1]: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2019-11-01T22:07:40.392502+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 79, in __getattr__ 2019-11-01T22:07:40.392503+00:00 app[web.1]: self._setup(name) 2019-11-01T22:07:40.392505+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 66, in _setup 2019-11-01T22:07:40.392507+00:00 app[web.1]: self._wrapped = Settings(settings_module) 2019-11-01T22:07:40.392509+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 157, in __init__ 2019-11-01T22:07:40.392511+00:00 app[web.1]: mod = importlib.import_module(self.SETTINGS_MODULE) 2019-11-01T22:07:40.392513+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module 2019-11-01T22:07:40.392516+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2019-11-01T22:07:40.392518+00:00 … -
clean_title() missing 1 required positional argument: 'title'
clean_title() missing 1 required positional argument: 'title' I see this problem and i don't know how to solve it. Can you pls help me? Here some parts of my models.py class Post(models.Model): kategori= models.ManyToManyField(Category,related_name='post',verbose_name='Kategoriler',help_text='Başlık giriniz') title= models.CharField(max_length=120,blank=False,verbose_name='Başlık',help_text='Baslik giriniz') slug = models.SlugField(max_length=122,default='', null=False, verbose_name='Slug Alani',editable=True) icerik= models.TextField(verbose_name='icerik',help_text='İcerik giriniz') def __str__(self): return '%s' % (self.title) def get_slug(self): return self.slug def unique_slug(self,new_slug, orijinal_slug, index,): if Post.objects.filter(slug=new_slug): new_slug='%s-%s' %(orijinal_slug,index) index+=1 return self.unique_slug(new_slug=new_slug, orijinal_slug=orijinal_slug, index=index) return new_slug def save(self, *args, **kwargs): if self.slug =='': index = 1 new_slug = slugify(self.title) self.slug = self.unique_slug(new_slug=new_slug , orijinal_slug= new_slug , index=index) #self.slug=slugify(self.title) super(Post, self).save(*args,**kwargs) here view page def post_create(request): post_form= PostForm() if request.method=='POST': post_form= PostForm(request.POST,request.FILES) if post_form.is_valid(): created_post =post_form.save(commit=True) messages.success(request,'Post Oluşturuldu') return HttpResponseRedirect(reverse('posts:post_detail',kwargs={'slug':created_post.get_slug(self='title')})) return render(request,'posts/post_create.html',context={'form':post_form}) TypeError at /posts/create/ clean_title() missing 1 required positional argument: 'title' Request Method: POST Request URL: http://127.0.0.1:8000/posts/create/ Django Version: 2.2.6 Exception Type: TypeError Exception Value: clean_title() missing 1 required positional argument: 'title' Exception Location: C:\Users\EMREKA~1\Desktop\myblog\myenv\lib\site-packages\django\forms\forms.py in _clean_fields, line 402 Python Executable: C:\Users\EMREKA~1\Desktop\myblog\myenv\Scripts\python.exe Python Version: 3.7.5 Python Path: ['C:\Users\EMRE KARACA\Desktop\myblog', 'C:\Users\EMREKA~1\Desktop\myblog\myenv\Scripts\python37.zip', 'C:\Users\EMREKA~1\Desktop\myblog\myenv\DLLs', 'C:\Users\EMREKA~1\Desktop\myblog\myenv\lib', 'C:\Users\EMREKA~1\Desktop\myblog\myenv\Scripts', 'c:\users\emre karaca\appdata\local\programs\python\python37\Lib', 'c:\users\emre karaca\appdata\local\programs\python\python37\DLLs', 'C:\Users\EMREKA~1\Desktop\myblog\myenv', 'C:\Users\EMREKA~1\Desktop\myblog\myenv\lib\site-packages'] -
Celery worker hangs with 100% cpu randomly
I'm in the process of moving a rather large router configuration parser from a nighly cron job to a series of celery tasks ~18000 scheduled through celery beat as part of a Django application. When the code was being ran through a Django management command using a multiprocessing pool we encountered no issues and it would successfully complete each night. When moved into a debian-buster python 3.6.9 container using celery as our task queue, at random celery workers would start spiking to 100% CPU indefinitely and never recover until the process is killed and restarted. When this condition occurs attaching strace to the process gives no output to debug the culprit. I've attached it for up to 30 minutes and never had anything print to the console. This happens completely at random. Targeting a router which previously caused the CPU spike, will successfully complete without issue. The script will log into a router, run a series of commands and collect the output. The output is then parsed, stale data is deleted from the database and replaced with current data. We are parsing interface configurations and multicast route tables from a variety of vendors. The script when ran through celery will … -
Where to handle PDF creation in a Django React site
I have a site that uses Django REST framework for the backend, react for the frontend, and axios to handle requests between them. I want my site to be able to create PDFs for the users. I looked on the web and found that I can create PDFs through both Django and React. I am wondering which one I should use to handle the PDF creation. -
Unknown database engine mysql.connector.django
I'm trying to reset the database on django (python manage.py reset_db) but django complains with CommandError: Unknown database engine mysql.connector.django. I've already run pip install mysql-connector-python and sudo apt install python-mysqldb but no luck. How can I get this error to magically disappear? FYI: My config has the database->default->engine set to "mysql.connector.django". -
Django CheckboxSelectMultiple map to another field to save in model
I have a rather complicated template. It has CheckboxSelectMultiple for three models and I can save them fine without any problems. class DocAideForm(forms.ModelForm): class Meta: model = DocAide fields = ['no_charge', 'doctors_notes', 'scan', 'part_to_xray', 'part_to_scan', 'test', 'drug', 'qty'] widgets = { 'scan': forms.CheckboxSelectMultiple(), 'test': forms.CheckboxSelectMultiple(), 'drug': forms.CheckboxSelectMultiple() } This is the form and in the template I am using them one by one. Like this: {% for form in forms %} {% for fields in form %} <tr><td width="10000"> {{ fields.label }} </td> <td>{% if fields|length < 3 %} {{fields}} {% else %} <table class="table table-hover table-striped table-bordered" align="center"><tr> {% for field in fields %} {% if forloop.counter0|divisibleby:5 %} <tr> {% endif %} <td>{{ forloop.counter }}</td><td>{{ field }} {% if fields.label == "Drug" %} Qty: 1+ {% endif %} </td> {% endfor %}</tr> </tr></table> {% endif %} </td> {% endfor %} {% endfor %} Where the quantity is I would like to have the IntegerField of the Qty. As to how many drugs are going to be described. In views.py I do it like this: if doc_aide_from.cleaned_data['drug']: p = Prescription(patient=patient) p.save() p.drug.add(*list(doc_aide_from.cleaned_data['drug'])) Again this works fine. But with the Qty field now I would like to have it for each … -
Pass Text From Model/Middleware To Template
How do I go about passing the reason to banned.html from the UserBanning model from the middleware? Everything works but I want to display the reason. models.py: from django.db import models from django.contrib.auth.models import User from django.conf import settings class UserBanning(models.Model): user = models.ForeignKey(User, verbose_name="Username", help_text="Choose Username", on_delete=models.CASCADE) ban = models.BooleanField(default=True, verbose_name="Ban", help_text="Users Bans") reason = models.CharField(max_length=500, blank=True) class Meta: verbose_name_plural = "User Banning" ordering = ('user',) def __str__(self): return f"{self.user}" middleware.py: from .models import UserBanning from django.shortcuts import render class BanManagement(): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) banned = UserBanning.objects.all() context = { 'banned': banned, } if(banned.filter(ban=True, user_id=request.user.id)): return render(request, "account/banned.html", context) else: return response banned.html: {% extends "base.html" %} {% block content %} <p>Your account has been banned. Reason: {{ banned.reason }}</p> {% endblock content %} -
Django - Autofill form data when validation error occurs in signup form
In my Django project, I allow a user to signup by completing a form I have created in HTML and not using Django forms . If a user makes an error, I re-render the page and pass an error through in a dictionary. In my template I then perform an If statement checking whether there is an error, and then If so I display that error once the page has been re-rendered. The problem I have is that if the user enters a valid email address and username, and then enters an incorrect password, then all the form data is lost when the page gets re-rendered. What I want is that if the user enter a valid username and email, and an invalid password, vice versa, then re-render the page and also autofill the fields in the form that were valid(e.g in this case the username and email field). Does anybody know how to accomplish this? Thank you.