Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to properly set up Viber bot in Python (Django)
I'm an absolute beginner in Viber bot, and I can't make my bot send a Welcome (or any other) message to the user, even if he has subscribed to my Viber bot account. I have tried all of the tutorials that I have found on the internet, read Viber Bot Python and REST documentation, some tutorials that I've found on github like this and this and every code possibility that has come to my mind - but I still couldn't make it to work. I have a website domain with SSL (Let's Encrypt) and everything should be fine. Also, I have used Postman to set a Webhook and received status 0 (ok), so users now can connect to my bot and message him. Here is what I've got so far views.py (django) from viberbot import Api from viberbot.api.bot_configuration import BotConfiguration from viberbot.api.messages.text_message import TextMessage from viberbot.api.messages.data_types.contact import Contact from viberbot.api.viber_requests import ViberConversationStartedRequest from viberbot.api.viber_requests import ViberFailedRequest from viberbot.api.viber_requests import ViberMessageRequest from viberbot.api.viber_requests import ViberSubscribedRequest from viberbot.api.viber_requests import ViberUnsubscribedRequest from django.views.decorators.csrf import csrf_exempt logger = logging.getLogger() logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) viber = Api(BotConfiguration( name='MyBotName', avatar='https://someavatar.com/avatar.jpg', auth_token='mytoken' )) def hook(request): logger.debug("received … -
how to share user session between subdomains?
i have 1 website on auth.mydomain.com and another as home.mydomain.com i want to use auth.mydomain.com for authentication only and after authentication user will get redirect to home.mydomain.com with auth.mydomain.com session cookie . the whole idea is i want to use auth.mydomain.com to authenticate users from my all subdomains *.mydomain.com in Django documentation i found SESSION_COOKIE_DOMAIN but i am not sure how to use it documentation shows it shares cookie only if its authenticated with base domain like mydomain.com anyone got idea how to solve this ?? -
How to get Images from AJAX and save it to Django
I'm trying to get an image with AJAX and save it to my django model. However, I can not see 'photo' variable that AJAX returns in the terminal although other variables (csrf, name...) are in there. So I can not process with 'photo' field and save it. there is the querydict that I received from AJAX. csrf and name is in there but no 'photo' variable. *** request.POST: <QueryDict: {'csrfmiddlewaretoken': ['krnIBkcYUb1breFjMyoReCwXeH9DLFc1Pvg2x1U2SGZSxPxQSLOwOxs1aSMrvBkf'], 'name': ['fgdfdsfsdf']}> js script var clientCreateForm = document.getElementById('client-create-form') var csrf = document.getElementsByName('csrfmiddlewaretoken') var client_name = document.getElementById('name') var image = document.getElementById('photo') clientCreateForm.addEventListener('submit', e => { e.preventDefault() console.log('submitted') var resim = image.files[0] console.log(resim) var fd = new FormData() fd.append('csrfmiddlewaretoken', csrf[0].value) fd.append('name', client_name.value) fd.append('photo', resim) $.ajax({ type:'POST', url:'/clients/', enctype: 'multipart/form-data', data: fd, contentType: false, processData: false, success: function (response) { window.location.replace(response.instance_url) }, error: function (error) { console.log("An error occurred") } }) }) views.py def post(self, request, *args, **kwargs): if is_ajax(request=request): # if request.method == "POST": print("*** request.POST: ", request.POST) my_name = request.POST.get('name') my_foto = request.POST.get('photo') new_client = models.Client.objects.create(owner=self.request.user, name=my_name, sector=my_sector, foto=my_foto) new_client.save() slug = new_client.slug return JsonResponse({'instance_url': slug}) return redirect('action-listview') -
Is the any possibility of having a Profile model and Customer model in Django e-commerce development?
I wish to know the possibility of having those two models altogether with other models like Order, OrderItem etc. I tried running it like in my models.py class Profile(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=30, null=True, blank=True, help_text="Insert your name") image = models.ImageField(default='default.png', upload_to='profile_pics') class Customer(models.Model): name = models.OneToOneField(Profile, on_delete=models.CASCADE) phone = models.CharField(max_length=11, null=True, blank=True) address = models.CharField(max_length=20, null=True, blank=True) phone = models.CharField(max_length=11, null=True, blank=True) address = models.CharField(max_length=20, null=True, blank=True) class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True) complete = models.BooleanField(default=False, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) transaction_id = models.CharField(max_length=100, null=True) Is it possible having such models like the above? If Yes, How can I present it in the views.py to authenticate a User(Profile) and at the same create a Customer. -
Could not import 'knox.auth.TokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'
I'm new to Django rest and I'm trying to create a very simple application that allows user to login/sign-up using knox. But as I try to run commands like "python manage.py makmigrations" or any other Django related commands, I get this error: ImportError: Could not import 'knox.auth.TokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: cannot import name 'ugettext_lazy' from 'django.utils.trans lation' (C:\Users\user\Desktop\Proj\Server\env\lib\site-packages\django\utils\translation\__init__.py). Here're parts of my settings.py file that I think are related to knox: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'knox', 'corsheaders', 'app',] AUTH_USER_MODEL = 'app.User' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication', ),} -
Filter objects and empty a column, django
I have a queryset like this Entries.objects.filter(some="1") For each object I want to empty a column named "example" like this Entries.objects.filter(some="1").example.empty() Can someone help me to achieve this -
incorrect processing of celery task in loop
I have a loop that calls celery task for each element. for item in my_list: my_task.delay(item) In this task, a long processing of an element takes place, and then the information is stored in the database. @shared_task def my_task(item): with transaction.atomic(): for el in Model_A.objects.filter(some_id=item): if el.some_field: # this part is long data_dict = get_data(el) break for k, v in data_dict.items(): Model_B.objects.update_or_create(some_id=item, field1=k, field2=v) The problem is that data_dict = get_data(el) sometimes return incorrect data. But if I run my_task just for one item - everything works correctly. Thanks for any help. -
module 'django.db.backends.utils' has no attribute 'typecast_decimal'
When I run python manage.py inspectdb --database=sybase_database it ends with error message: Database.register_converter(Database.DT_DECIMAL, util.typecast_decimal) AttributeError: module 'django.db.backends.utils' has no attribute 'typecast_decimal' $ pip freeze certifi==2021.10.8 chardet==3.0.4 defusedxml==0.7.1 Django==2.2.4 django-allauth==0.40.0 django-bootstrap-form==3.4 django-bootstrap3==15.0.0 django-crispy-forms==1.7.2 django-crudbuilder==0.2.7 django-debug-toolbar==1.10.1 django-filter==2.2.0 django-mssql-backend==2.8.1 django-tables2==2.4.1 idna==2.8 importlib-metadata==2.1.1 oauthlib==3.1.1 pyodbc==4.0.32 python-dateutil==2.8.2 python3-openid==3.2.0 pytz==2021.3 requests==2.21.0 requests-oauthlib==1.3.0 six==1.16.0 sqlany-django==1.13 sqlanydb==1.0.11 sqlparse==0.4.2 urllib3==1.24.3 zipp==3.6.0 Ubuntu 18.04 -
django's validate_no_broken_transaction fails for query that works fine in console
I use django 2.2.25 with mysql 8.0.27. From time to time I have such error in my logs: Traceback (most recent call last): File "/home/v/django/django_projects/v/tele/bot.py", line 139, in tmp res = f(bot, update, *args, **kwargs) File "/home/v/django/django_projects/v/tele/bot.py", line 401, in answer_action finalize_game(bot, update, prize, prefix=text) File "/usr/lib/python3.8/contextlib.py", line 75, in inner return func(*args, **kwds) File "<string>", line 2, in finalize_game File "/home/v/.local/lib/python3.8/site-packages/retry/api.py", line 73, in retry_decorator return __retry_internal(partial(f, *args, **kwargs), exceptions, tries, delay, max_delay, backoff, jitter, File "/home/v/.local/lib/python3.8/site-packages/retry/api.py", line 33, in __retry_internal return f() File "/home/v/django/django_projects/v/tele/bot.py", line 341, in finalize_game if len(users) == 0: File "/home/v/.local/lib/python3.8/site-packages/django/db/models/query.py", line 256, in __len__ self._fetch_all() File "/home/v/.local/lib/python3.8/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/v/.local/lib/python3.8/site-packages/django/db/models/query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/v/.local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1142, in execute_sql cursor.execute(sql, params) File "/home/v/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/v/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/v/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 79, in _execute self.db.validate_no_broken_transaction() File "/home/v/.local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 437, in validate_no_broken_transaction raise TransactionManagementError( django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. My code is: @atomic @retry(tries=3, delay=1) def finalize_game(bot, update, prize, prefix=None): state = game_states.get(update.message.chat.id, None) uid … -
Frontend and backend separation **settings** using django rest framework and sveltekit
I am building an app using django rest framework and sveltekit. What should I do so that the frontend can fetch backend api properly? More details: I can 'GET, POST' api properly using PostMan. I can 'GET' api properly using fetch. I Can not 'POST' api properly using fetch: Here is my attempt (More code details in the last.): the very beginning: frontend: fetch('http://127.0.0.1:8000/blogs/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ name, about, cover, }), }) backend: ALLOWED_HOSTS = [] I the this error in my browser console: Access to fetch at 'http://127.0.0.1:8000/blogs/' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. And this log of django: [14/Jan/2022 17:11:46] "OPTIONS /courses/ HTTP/1.1" 200 0 Setting up cors: frontend: fetch('http://127.0.0.1:8000/blogs/', { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ name, about, cover, }), }) I get this error in my browser: POST http://127.0.0.1:8000/blogs/ net::ERR_ABORTED 415 (Unsupported Media Type) change media Type: frontend const data = new FormData(); … -
Using autocomplete feature in Django admin without showing related model in the left sidebar
My main model ObjetArchi has several related models, connected through foreign keys. To avoid loading a long list of values and scrolling infinitely through it, I'm using the autocomplete feature in the ObjetArchi admin interface. Related models have to be registered for the autocomplete to work, but I'd like them not to be shown in the left sidebar. Is there a way to hide them while still being able to edit them through the main model if needed? -
How to get another data from MS AD by attributes - django
I use modul django-python3-ldap for authentication user from Microsoft Active Directory. I need to parse another data from attributes in AD except mail, sAMAccountname, givenName, sm. Do you know how to do this? LDAP_AUTH_USER_FIELDS = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "mail", "telephone": "mobile", # for example this } Thanks. -
webbrowser does not open links in the same window if it's incognito
I'm using Django to open some links in the same window, using webbrowser. I wrote a custom action like this : @admin.action(description='Open') def open(modeladmin, request, queryset): for app in queryset.filter(auto_open=True).reverse(): webbrowser.open(app.link, new=0, autoraise=True) This is what happens when I check which links to open and click on Go : Non Incognito Window : Works fine, links are opened in the same window Incognito Window : Does not work, links are opened in a non incognito window Is this browser specific ? Because I'm using Chrome and I don't know if I have to override settings or not -
how to collect data back to request class in celery Django
i have create function in views.py and in function serializing objects to json after that passing this data to celery task but i have problems with collect data back to request class. That is, I can't collect the data back in json to request class, Because I have to pass this request class to another function by celery task views.py def create(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance, data=request.data) serializer.is_valid(raise_exception=True) request_data = { "crm_id": request.JWT.crm_id, "crm": None, "crmuser": request.JWT.crmuser.id, "crm_users": None } matching_fields = serializer.validated_data['matching_fields'] import_data.delay(request_data, instance.id, matching_fields) task.py @shared_task def import_data(request_data, instance_id, matching_fields): instance = ImportRecord.objects.get(id=instance_id) request_data['crm'] = Crm.objects.get(id=request_data['crm_id']) request_data['crmuser'] = CrmUser.objects.get(id=request_data['crmuser']) request_data['crm_users'] = CrmUser.objects.all().filter(crm_id=request_data['crm_id']) helper = ImportData(matching_fields, instance, request) helper.import_data() how can i back to collect json request_data to request class -
I'm getting Application Error while hosting Django project on Heroku
I get the 'Application Error' After the successfully deployed my project. I don't know why plz help me. It's the first time that I'm hosting my project on Heroku I've never done that before. these are logs details: » Warning: heroku update available from 7.53.0 to 7.59.2. 2022-01-13T19:10:37.632487+00:00 app[web.1]: WARNING:django.request:Bad Request: / 2022-01-13T19:10:37.661207+00:00 heroku[router]: at=info method=GET path="/" host=beautyparlour.herokuapp.com request_id=9c5a41e9-725b-4b83-8bf9-81c074c9dc03 fwd="103.69.113.112" dyno=web.1 connect=0ms service=49ms status=400 bytes=372 protocol=https 2022-01-13T19:10:38.425281+00:00 app[web.1]: ERROR:django.security.DisallowedHost:Invalid HTTP_HOST header: 'beautyparlour.herokuapp.com'. You may need to add 'beautyparlour.herokuapp.com' to ALLOWED_HOSTS. 2022-01-13T19:10:38.425627+00:00 app[web.1]: WARNING:django.request:Bad Request: / 2022-01-13T19:10:38.427129+00:00 heroku[router]: at=info method=GET path="/" host=beautyparlour.herokuapp.com request_id=f3370395-81fe-4094-83b6-599e92fb48a1 fwd="103.69.113.112" dyno=web.1 connect=0ms service=10ms status=400 bytes=372 protocol=https 2022-01-13T19:10:39.113258+00:00 app[web.1]: ERROR:django.security.DisallowedHost:Invalid HTTP_HOST header: 'beautyparlour.herokuapp.com'. You may need to add 'beautyparlour.herokuapp.com' to ALLOWED_HOSTS. 2022-01-13T19:10:39.113745+00:00 app[web.1]: WARNING:django.request:Bad Request: / 2022-01-13T19:10:39.115496+00:00 heroku[router]: at=info method=GET path="/" host=beautyparlour.herokuapp.com request_id=f15ce14d-9758-4dd6-83ec-6cb9f23adf13 fwd="103.69.113.112" dyno=web.1 connect=0ms service=15ms status=400 bytes=372 protocol=https 2022-01-13T19:10:41.921449+00:00 app[web.1]: ERROR:django.security.DisallowedHost:Invalid HTTP_HOST header: 'beautyparlour.herokuapp.com'. You may need to add 'beautyparlour.herokuapp.com' to ALLOWED_HOSTS. 2022-01-13T19:10:41.921960+00:00 app[web.1]: WARNING:django.request:Bad Request: / 2022-01-13T19:10:41.934548+00:00 heroku[router]: at=info method=GET path="/" host=beautyparlour.herokuapp.com request_id=b4c7c6da-8cdc-4c83-abf6-ec654b6c4116 fwd="103.69.113.112" dyno=web.1 connect=0ms service=22ms status=400 bytes=372 protocol=https 2022-01-13T19:26:17.883688+00:00 app[web.1]: ERROR:django.security.DisallowedHost:Invalid HTTP_HOST header: 'beautyparlour.herokuapp.com'. You may need to add 'beautyparlour.herokuapp.com' to ALLOWED_HOSTS. 2022-01-13T19:26:17.883955+00:00 app[web.1]: WARNING:django.request:Bad Request: / 2022-01-13T19:26:17.885404+00:00 heroku[router]: at=info method=GET path="/" host=beautyparlour.herokuapp.com request_id=915ef507-e5cd-41bd-980c-2d1fd73237bb fwd="103.69.113.112" dyno=web.1 connect=0ms service=27ms status=400 bytes=372 protocol=https 2022-01-13T19:26:20.551449+00:00 app[web.1]: … -
AWS UnicodeDecodeError 'utf-8' codec can't decode in position 0: invalid start byte
I have my backend running on an AWS EC2 instance and my storages on S3, wherever there is a ImageFileField the API errors out with the below error. My database is a postgres 12 instance running on RDS. I just migrated from heroku to RDS, but restored data from the dump created on my local machine. It all works fine on heroku and local system, local system is running postgres 13, heroku as well. Any help would be appreciated, thanks! -
Django Rest Frame give 404 not found
When I hit the URL doctor/56b63b2d-11c4-4f0c-be7c-0b0348c487fd/ I get the detail not found I tried every solution but still it' not work error : - "GET /doctor/56b63b2d-11c4-4f0c-be7c-0b0348c487fd/ HTTP/1.1" 404 11332 class DoctorViewSet(ListModelMixin, RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin, GenericViewSet): serializer_class = DoctorDeshboardSerializer def get_queryset(self, *args, **kwargs): doctor = self.kwargs["pk"] queryset = PatientDetails.objects.filter(doctor=doctor) print(queryset) return queryset And I look the get_queryset this has printed the all patient-related to doctor So means My logic is fine and data also exist but router = DefaultRouter() router.register('patient', views.PatientDashboardViewSet, basename='patients') router.register('doctor', views.DoctorViewSet, basename='doctors') urlpatterns = router.urls I also show serializer.py class DoctorDeshboardSerializer(serializers.ModelSerializer): problem_patient = SimpleProblemPatient(many=True) class Meta: model = PatientDetails fields = ['id', 'name', 'problem_patient'] Please Help On urgent basis -
Cannot assign requested address for Django-Docker project
I'm building my first project with Docker. I've created a simple Hello World with Django and PostgreSQL. Below the structure of the project without and with Docker: No Docker With Docker PostgreSQL --> PostgreSQL Django --> Container(Django) Therefore PostgreSQL will not use Docker; in development PostgreSQL runs in localhost and in production will be runs in a dedicated server. When I start Django without Docker I can see the Hello World page, but when I run it inside a container I see this error: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? -
How to use Django Nginx Application with both HTTP and HTTPS requests?
I have a Web Application that uses Django as backend and Nginx along with Gunicorn for the reverse proxy. I have already set up the Nginx configuration and it works perfectly when requests are sent over HTTPS. But it fails when HTTP requests are made. I want the application to work for both HTTP and HTTPS requests. Some of my Django Views contain internal requests that are made over HTTP as they have to be compatible with the Development as well as Production Server class LoginView(APIView): ... http_host = request.META["HTTP_HOST"] url = f"http://{http_host}/o/token/" headers = {'Content-Type': 'application/x-www-form-urlencoded'} data = { 'username': req_data['username'], 'password': req_data['password'], } response = requests.post(url, headers=headers, data=data) ... My nginx configuration is as follows server { listen 8000 ssl; server_name backend.test.com www.backend.test.com; access_log /var/log/nginx/app_backend.access.log; error_log /var/log/nginx/app_backend.error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/testuser/app_backend/app_backend; } location /media/ { root /home/testuser/app_backend/app_backend; } location / { include proxy_params; proxy_pass http://unix:/home/testuser/app_backend/app_backend/app_backend.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/backend.test.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/backend.test.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } I have hosted the VPS on digital ocean. How do … -
DjangoRestFramework ModelSerializer ignores required extra data
I have some ModelSerializer like: class MySerializer(serializers.ModelSerializer): x = serializer.IntegerField(required=True, write_only=True) class Meta: model = MyModel fields = (...some MyModel fields..., 'x') x is not a MyModel field. Problem: when I send request without x in form_data, drf doesn't raise "required" error. Expected: 400 response with message of missed 'x' is required. I am able to write it by myself, but it looks like undefined behavior or I missed something in docs. -
Creating name based user access to certain pages in the nav-bar
I need to create user based access to certain features of my Django web-app . I have figured out how to restrict access to users that are not super users like so : {% if user.is_staff %} <a href="{% url 'creditControlHome' %}">Credit Control</a> {% endif %} Is there a way to do this based on names? For example , " if user.name = George and Bill and Clint " then they can see that part of the nav bar ? -
Login ,Signup in same page django(multiple forms authentication)?I'am able to signup ... Why is it showing invalid credential in meassage while log in
*** VEIWS.PY This is views.py I am able to signin but not able to log in it shows invalid credentials `def login_user(request): if request.method=='POST': if request.POST.get('submit')=='sign_up': username=request.POST.get('name') email=request.POST.get('email') password=request.POST.get('password') if User.objects.filter(email=email).exists(): # Condition for same email id if already exists messages.warning(request,'Email already exists') else: user =User(email=email,password=password,username=username) user.set_password(password) #since raw passwords are not saved therefore needs to set in this method user.save() messages.success(request,'User has been registered successfully') #Dispalys message that user has been registerd return redirect('login') elif request.POST.get('loginsubmit')=='sign_in': email = request.POST['email'] password = request.POST['password'] user = authenticate(request, email=email, password=password) if user is not None: login(request, user) return redirect ('/') else: messages.warning(request,'Invalid credentials') # print(email,password,username) return render (request,'login.html')` LOGIN.html ======= `//<section id="form"><!--form--> <div class="container"> <div class="row"> <div class="col-sm-4 col-sm-offset-1"> <div class="login-form"><!--login form--> <h2>Login to your account</h2> <form method="POST" action="login"> {% csrf_token %} <input type="email" placeholder="Email Address" id="validationDefault01" name="email" required> <input type="password" placeholder="Password" id="validationDefault02" name="password" required> <span> <input type="checkbox" class="checkbox"> Keep me signed in </span> <button type="submit" name='loginsubmit' value='sign_in' class="btn btn-default">Login</button> </form> </div><!--/login form--> </div> <div class="col-sm-1"> <h2 class="or">OR</h2> </div> <div class="col-sm-4"> {% block body %} <body> {% for message in messages %} <section> <div class=" container alert alert-{{message.tags}} alert-dismissible" role="alert"> <strong>Message!</strong> {{message}} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </div> </section> {% … -
Is there a free hosting site for django apps with 800mb+ size?
I have browsed through the net and tried pythonanywhere and heroku to deploy my web app which is a ml prediction model with site predicting the target. Everything is working fine but when I tried pythonanywhere I couldn't deploy it there cause of a size limit of 500. Same goes with heroku there I am getting the following error. Warning: Your slug size (346 MB) exceeds our soft limit (300 MB) which may affect boot time. So my question is, is there a good web hosting site which can deploy my project which is 782 mb large for free? -
Where is the logging in my Django application started by uwsgi?
I use supervisor and uwsgi to start my Django. Here is the conf in supervisor. [program:myapp] directory=/home/users command=uwsgi --ini uwsgi.ini stdout_logfile_maxbytes=50MB stdout_logfile_backups=30 stderr_logfile=/var/log/supervisor/supervisor.log stdout_logfile=/var/log/supervisor/supervisor.log And this is the ini file of uwsgi [uwsgi] http-socket=0.0.0.0:8080 wsgi-file=myapp/wsgi.py logformat=%(ltime) "%(method) %(uri) %(proto)" status=%(status) res-time=%(msecs)ms logto=/var/log/supervisor/uwsgi.log In this way, only method, status and time to reponse etc is listed as follow 14/Jan/2022:13:19:46 +0800 "GET /model/task/?taskid=e69a757974f811ec93e1f58ac6e34980&current=1&pageSize=10000&total=0&model_id=1 HTTP/1.1" status=200 res-time=107ms 14/Jan/2022:13:19:45 +0800 "POST /model/runmodel/ HTTP/1.1" status=200 res-time=3508ms What I want is if I add a logging.info or logging.debug in my application, it can also writes to the log file. From the doc of uwsgi, it seems I cannot accomplish that by the logformat parameter. Anyone knows if it's possible to do it? -
Add new entries to the model incrementing the latest value with three digits
I have a model, with a column named reference. Each reference has values like this: 106739D/4115110 106739D/4115111 106739D/4115112 and so on... From my view, I send a count of previous projects to the template, like this (truncated): def add_new_project(request, pk): context = {} projects = Project.objects.all().filter(project_id=pk).count() context['projects'] = projects Then in my template, I retrieve some value like 106739D/41151 + 1 (from count) = 106739D/411511 Template: <div class="col-sm"> <input type="text" name="reference" class="form-control" value="{{ some_given_value }}{{ projects }}" required> </div> It actually does the job, it increments the value one by one each time I create a new project, but I've been requested to do it with this format 00X: 106739D/4115110 --> 106739D/411511000 106739D/4115111 --> 106739D/411511001 106739D/4115112 --> 106739D/411511002 So basically I need to add 00X instead of X. Is there any efficient - pythonic way to do that?