Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM - filter method with some arithmetic calculation
I have this query 'SELECT * FROM products WHERE discontinued = 0 AND ((unitsinstock + unitsonorder) < reorderlevel)' which is giving me some results from DB, how can I do the same in django ORM I tried as below but this is erroring out. -
Return null instead of id or nested serialized data on json API response
So here is the code models.py class Client(models.Model): name = models.CharField(max_length=255, unique=True) company_reg_num = models.CharField(max_length=255, blank=True, null=True, unique=True) date_registerd_internal = models.DateField(auto_now_add=True) date_registerd_external = models.DateField() location = models.ManyToManyField(Location, null=True, blank=True, related_name='location') class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) time_created = models.DateTimeField(auto_now_add=True) image = models.ImageField(default='default.png', upload_to='profile_imgs', null=True, blank=True) date_of_birth = models.DateField(blank=True, null=True) gender = models.CharField(choices=GENDER, max_length=12, default='Male') place_of_birth = models.CharField(max_length=255, blank=True, null=True) employer = models.ForeignKey(Client, on_delete=models.CASCADE, blank=True, null=True, related_name='employer') class Shift(model.Models): # --snip-- expense = models.ForeignKey(Expense, on_delete=models.CASCADE, null=True, blank=True, related_name='expense') time_added = models.DateTimeField(auto_now_add=True) employee_assigned = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True, related_name='employee_assigned') location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True, blank=True) client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True, blank=True, related_name='client') And here is my serializer.py file class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' class ClientSerializer(serializers.ModelSerializer): location = LocationSerializer(read_only=True, many=True) class Meta: model = Client fields = '__all__' class ShiftSerializer(serializers.ModelSerializer): #permission_classes = [permissions.IsAuthenticatedOrReadOnly] location = LocationSerializer(read_only=True, many=False) employee_assigned = ProfileSerializer(many=False, read_only=True) client = ClientSerializer(many=False, read_only=True) class Meta: model = Shift fields = '__all__' I am using function based views for my api views and they are as follows: @api_view(['GET', 'POST', 'PATCH']) @csrf_exempt @permission_classes((IsAuthenticated,)) def shift_api(request): if request.method == 'GET': if request.user.is_superuser and request.user.is_staff: shifts = Shift.objects.all() serializer = ShiftSerializer(shifts, many=True) return Response(serializer.data, status=status.HTTP_200_OK) else: return Response({"error": … -
Django, Tailwind, and heroku collectstatic cannot find npm
I am trying to set up a small web project using Django and tailwind and deploying it on Heroku. In Heroku, I am installing the heroku/nodejs and heroku/python Buildpacks. I am going through the following guide to set it up: https://www.khanna.law/blog/deploying-django-tailwind-to-heroku When I try to deploy my application to Heroku I am getting the following error: -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/tailwind/npm.py", line 23, in command subprocess.run([self.npm_bin_path] + list(args), cwd=self.cwd) File "/app/.heroku/python/lib/python3.10/subprocess.py", line 501, in run with Popen(*popenargs, **kwargs) as process: File "/app/.heroku/python/lib/python3.10/subprocess.py", line 966, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/app/.heroku/python/lib/python3.10/subprocess.py", line 1842, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: '/usr/local/bin/npm' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/tailwind/management/commands/tailwind.py", line 119, in npm_command self.npm.command(*args) File "/app/.heroku/python/lib/python3.10/site-packages/tailwind/npm.py", line 26, in command raise NPMException( tailwind.npm.NPMException: It looks like node.js and/or npm is not installed or cannot be found. Visit https://nodejs.org to download and install node.js for your system. If you have npm installed and still getting this error message, set NPM_BIN_PATH variable in settings.py to match path of NPM executable in your system. Example: NPM_BIN_PATH = "/usr/local/bin/npm" During … -
How to solve 'POST 401 Ajax Error' in the console of a deployed django website
I keep on getting an error like below in the chrome console whenever I click my "Place Order" button in my website. I have struggled with this for hours. Here is my error: POST https://{{mywebsitedomain}}/order/create_ajax/ 401 jquery-3.5.1.min.js:2 I have no idea why this error suddenly shows up after I uploaded my website on a hosting provider online. This is because I did not get this error when I was in dev mode on my pc. Here is my template: {% block script %} <script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script type="text/javascript"> csrf_token = '{{csrf_token}}'; order_create_url = '{% url "orders:order_create_ajax" %}'; order_checkout_url = '{% url "orders:order_checkout" %}'; order_validation_url = '{% url "orders:order_validation" %}'; order_complete_url = '{% url "orders:order_complete" %}'; </script> <script src="https://cdn.iamport.kr/js/iamport.payment-1.1.8.js" type="text/javascript"></script> {% load static %} <script src="{% static 'js/checkout.js' %}" type="text/javascript"></script> {% endblock %} {% block content %} <section class="max-w-xl mx-auto pt-10 text-gray-600 body-font"> <div class="container mx-auto flex flex-wrap"> <div class="w-full flex justify-between items-center border-b border-gray-500"> <div class="mb-1"> <a class="text-md text-blue-500 hover:text-blue-300" href="{% url 'lesson-options-list' current_product.class_type.pk %}">돌아가기</a> </div> </div> </div> </section> <div class="mt-5 max-w-xl mx-auto"> <div class="row"> <div class="col"> <div class="p-4"> <div class="flex rounded-lg h-full bg-gray-100 p-8 flex-col"> <div class="flex items-center mb-3"> <div class="w-8 h-8 mr-3 inline-flex items-center … -
filling the document Django python-docx
it is necessary to fill in the document template Word through the rest api. I load the template through the admin panel and assign the names of the fields whose values I want to receive through the api. I don’t know how to continue to be def post(self, request): data = request.data # берем данные из post запроса document = Documentt.objects.filter(id=data["doc_id"]) # ищем нужный пример документа open_doc = Document(document[0].location) # открываем его filename = ((str(document[0].location)).split('/')[-1]).split('.')[0] # создаем имя файла fields = DocumentField.objects.filter(id=data["doc_id"]) # получаем поля для данного документа # обрабатываем поля##### context = {} for field in fields: # получаем имя поля field_name = Field.objects.filter(name=str(field.field_id)) # добавляем строку в файл##### context= { f"{field_name}: {(data['field'][field_name])}" } open_doc.render(context) if os.path.exists(f"user_files/{str(data['customer_id'])}"): # проверяем существует ли папка с id пользов. pass else: os.mkdir(f"user_files/{str(data['customer_id'])}") # если не существует то создаем open_doc.save('user_files/' + str(data['customer_id']) + '/' + filename + '.docx') # сохраняем файл # проверяем наличие файла в бд if len(DocumentResult.objects.filter(title=filename)) == 0: cust = Customer.objects.get(id=data["customer_id"]) # получаем объект кастомера res_doc = DocumentResult.objects.create( title=filename, customer=cust, location='user_files/' + str(data['customer_id']) + '/' + filename + '.docx' ) # добавляем в бд return Response({'status': 'Success!', 'link': res_doc.location}) # возвращаем успешный ответ return Response({'status': 'Success!'}) -
Cannot deploy django app to strato hosting [closed]
Has anybody successfully deployed django app to strato (strato.de) web server? After some struggle I was able to install all dependencies as wall as npm and node. Basically I noticed that using strato with ssh is very limited. I am running gunicorn on my default wsgi file but when I try to reach my website from domain address, nothing happens. I noticed that there is apache installed on the machine but installing mod_wsgi via pip fails. -
django runscript error: no (valid) module for script 'main' found
I wrote some code to run ... but i had a error while running my code. So I tested some simple code like this... but it still doesn't work. def run(): print("test") error seems like enter image description here which says no (valid) module for script 'main' found. How can I fix it? -
Call Sync function outside consumer (Django Channels)
There are 2 kinds of django web server running, gunicorn(WSGI) and channels(ASGI) respectively. WSGI server is responsible for handling HTTP request and channels is responsible for websocket connections. There is an API on WSGI server that would run a SQL query, and then trigger sending message to a particular user via websocket. I called async_to_sync to wrap the channel_layer.group_send, but sometimes error occurrs. Here's the code def some_view(request): # database operations # ... channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( group_name, { 'type': 'send_function', 'data': data }, ) Most of the time it works fine, however, sometimes RuntimeError "You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly." occurred. This happened because there is a running event loop in current thread. I think it's probably that django is reusing threads and each request would initialize an event loop. My first solution is to create event_loop for each request and then call loop.run_until_complete, but it cause another RuntimeError "Cannot run the event loop while another loop is running" Then I tried to check if there is running event loop before call create event loop, if an event loop is running, get the running loop … -
Django 400 Bad Request when run in production with gunicorn
I am getting a 400 error on all my pages when I moved my django app from one hosting service to another, the hosting service I moved to is Scalingo. My settings.py file: DEBUG = os.getenv("DEBUG") == "True" ALLOWED_HOSTS = [x.strip() for x in os.getenv("ALLOWED_HOSTS").split(",")] My env variables ALLOWED_HOSTS="my-app.osc-fr.scalingo.fr,.localhost,127.0.0.1,[::1]" DEBUG="False" I contacted customer support who have advised me that it must be a configuration issue with my app. All existing answers here I have found have advised to make sure the ALLOWED_HOSTS variable is correct, and I have already checked that it includes the required addresses according to the hosting platform's django-specific docs. -
502 Bad Gateway with nginx and gunicorn 111: Connection refused
before getting into the problem i want to specify that i'm stuck with this 502 page two days, need help please i had my app running perfectly on a digital ocean droplet sisn i dicided to add another app to it and now no one is running (502 error ) i deleted the second app but the first didn't restart commands i run and the result sudo systemctl status nginx -> Active: active (running) ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2022-01-12 09:57:21 UTC; 35min ago TriggeredBy: ● gunicorn.socket Main PID: 1031544 (gunicorn) Tasks: 4 (limit: 1136) Memory: 168.5M CGroup: /system.slice/gunicorn.service ├─1031544 /home/taki/kahraba/venv/bin/python3 /home/taki/kahraba/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock config.wsgi:application ├─1031556 /home/taki/kahraba/venv/bin/python3 /home/taki/kahraba/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock config.wsgi:application ├─1031557 /home/taki/kahraba/venv/bin/python3 /home/taki/kahraba/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock config.wsgi:application └─1031558 /home/taki/kahraba/venv/bin/python3 /home/taki/kahraba/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock config.wsgi:application sudo nginx -t -> syntax is ok the only error i get is when running sudo tail -100 /var/log/nginx/error.log connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: xx-xx-xx-xx server : xx-xx-xx-xx , upstream: "http://unix:/run/gunicorn.sock:/" when i allow port:8000 with sudo ufw allow 8000 and i … -
How to write Django views (JSON apis) with statically typed arguments and responses?
In Java Spring, I can write down (simplified): List<Apple> fetchApples(Orange request) { ... } class Orange { int a; double b; String c; ... } class Apple { int d; double e; String f; ... } By doing this, I can be very sure that users of the API will only pass in some data like {a: 42, b: 1.2, c: "hello"}, instead of {a: "wtf", z: [1,2,3]}. However, in Django, I do not find any method to hint this. I have to use a = int(request['a']) to manually convert that parameter into type int and so on. This is even more troublesome when dealing with more complicated structs. Thus, how can I do something similar to Java Spring? I know Django/Python is not statically typed, but a type hint is better than nothing. Why I need this: Firstly, more typing is better for the code (more errors can be found at lint time). Secondly, and most importantly, I want to run code generator but that definitely requires some static typing hinting. For example, generate Dart/Flutter client of the Django server. -
My index page used to extend a base_generic templage not showing while the extended template works perfectly
i extends a base_generic page through an index page in django,but the index page insn't showing any content,while the base_generic page works perfectly.I have tried removing all parents template from the index page,still not working. Pls help -
How do I set a wildcard for CSRF_TRUSTED_ORIGINS in Django?
After updating from Django 2 to Django 4.0.1 I am getting CSRF errors on all POST requests. The logs show: "WARNING:django.security.csrf:Forbidden (Origin checking failed - https://127.0.0.1 does not match any trusted origins.): /activate/" I can't figure out how to set a wildcard for CSRF_TRUSTED_ORIGINS? I have a server shipped to customers who host it on their own domain so there is no way for me to no the origin before hand. I have tried the following with no luck: CSRF_TRUSTED_ORIGINS = ["https://\*", "http://\*"] and CSRF_TRUSTED_ORIGINS = ["*"] Explicitly setting "https://127.0.0.1" in the CSRF_TRUSTED_ORIGINS works but won't work in my customer's production deployment which will get another hostname. -
Django Model Calculated field as Database level?
I have the simplified model below : class Product(models.Model): name = models.CharField(max_length=50) price = models.FloatField() class Invoice(models.Model): product = models.ForeignKey(Product,on_delete=models.PROTECT) quantity = models.FloatField() @property def total(self): return self.quantity * self.product.price I would like to be able to process data analysis on my Invoices data. If i load my queryset to a list, the total property is missing : Invoice.object.all().values_list() Is there a way with django to calculate the property field as a database level ? So it would be easy to analyse from queryset (ideally i would like to load in dataframe) Thanks for the tips ! -
Problems with PIL Image on django post_save
I'm trying to create a thumbnail from the image uploaded. I don't want to create a field in the Model. I just want to create some thumbnails in the same folder where the original picture is uploaded. @receiver(post_save, sender=Categoria) def wallpapers_thumbnail(sender, instance, **kwargs): file = instance.wallpaper ext = os.path.splitext(file.path)[-1] thumbnail = ( f"{settings.MEDIA_ROOT}/wallpapers/categorie/{instance.id}/thumbnail-600{ext}" ) try: im = Image.open(file.path) print("open file") im.thumbnail((600, 600)) print("create thumbnail") im.save(thumbnail) print("save thumbnail") except IOError: print(IOError) Unluckly it throws an error: open file create thumbnail <class 'OSError'> What is wrong? -
How to separate lines in django text_Field model?
I have written the following code in my models.py file: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) genere = models.CharField(max_length=50, default='') def __str__(self): return f'{self.title} by {self.author}' In my views.py file I have written: from django.shortcuts import render from .models import Post from django.views.generic import ListView class PostListView(ListView): model = Post template_name = "blog/index.html" context_object_name = "posts" ordering = ["-date_posted"] In my index.html I have written: {% extends "blog/base.html" %} {% load static %} {% block content %} {% for post in posts %} <article class="col-12 col-md-6 tm-post"> <hr class="tm-hr-primary"> <a href="{% url 'blog-detail' post.id %}" class="effect-lily tm-post-link tm-pt-60"> <div class="tm-post-link-inner"> <img src="{% static 'img/img-01.jpg' %}" alt="Image" class="img-fluid"> </div> <span class="position-absolute tm-new-badge">New</span> <h2 class="tm-pt-30 tm-color-primary tm-post-title">{{ post.title }}</h2> </a> <p class="tm-pt-30"> {{ post.content|safe|truncatewords:"30"|linebreaks }} </p> <div class="d-flex justify-content-between tm-pt-45"> <span class="tm-color-primary">{{ post.genere }}</span> <span class="tm-color-primary">{{ post.date_posted|date:'N j,Y' }}</span> </div> <hr> <div class="d-flex justify-content-between"> <span>36 comments</span> <span>by {{ post.author }}</span> </div> </article> {% endfor %} {% endblock %} Suppose if I add the following things in my post.content: laborum deserunt do excepteur … -
ModuleNotFoundError: "projectname" DJANGO + UWSGI + NGINX (UBUNTU 20.04)
I want to deploy my django project but uwsgi gives me an error: File "/root/eva/lawyer/lawyer/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/root/eva/venv/lib/python3.8/site-packages/django/core/wsgi.py", line 1> django.setup(set_prefix=False) File "/root/eva/venv/lib/python3.8/site-packages/django/__init__.py", line 19> configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/root/eva/venv/lib/python3.8/site-packages/django/conf/__init__.py", li> self._setup(name) File "/root/eva/venv/lib/python3.8/site-packages/django/conf/__init__.py", li> self._wrapped = Settings(settings_module) File "/root/eva/venv/lib/python3.8/site-packages/django/conf/__init__.py", li> mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named ' lawyer' my project is called a lawyer. it has a standard structure. The configuration files and wsgi are located in the folder of the same name - lawyer. lawyer/lawyer/settings.py, lawyer/lawyer/wsgi.py "lawyer" is not a python module, but the name of the project and the project directory where I store the settings and the wsgi file Please help me to run my project my uwsgi ini file: [uwsgi] chdir = /root/eva/lawyer env = DJANGO_SETTINGS_MODULE= lawyer.settings wsgi-file = /root/eva/lawyer/lawyer/wsgi.py #module = lawyer.uwsgi:application workers = 1 max-requests = 5000 #plugins-dir=/usr/lib/uwsgi/plugins/ … -
best way to create example project in a django plugin test suite
This may be a simple question, but I can't wrap my head around it. Given I make a Django plugin app, lets name it foo, which adds some database features, that other apps can use (e.g. models that must be inherited), and I want to add tests for that app. Structure: foo/ apps.py models.py tests/ test_foo_basic.py test_bar.py ... setup.py README.md ... The project is no full Django application, as it is an plugin app for others. So I need to create a fake Django project within the testing directory, with at least one app, which defines some models that inherit from foo.models.<some_model> and test it, right? Is that the only way? It seems a but much for me. If so, it's ok for me to give me the answer "it is so". And I'll accept ;-) If not, please tell me I am complicated and show me something easier, a pytest plugin etc.? For testing, I need a -
Markdown.convert() missing 2 required positional arguments: 'self' and 'text'
Markdowner = Markdown.convert() [image ling] Trying to convert markdown into HTML using Python's Markdown2 library, However I keep getting the error -Markdown.convert() missing 2 required positional arguments: 'self' and 'text'- -
unable to install with pip after creating virtual environment
(django-env) C:\Users\Username\dev> pip install django Unable to create process using 'C:\Users\UsernameT\AppData\Local\Programs\Python\Python310\python.exe "C:\Users\UsernameT\dev\django-env\Scripts\pip.exe" install django' installed virtualenv using : pip install virtualenv; virtualenv django-env; django-env\scripts\activate -
DRF & Next.js: Cookies are not stored in the browser only in the production environment
I'm working on a web app with DRF in the back and Next.js in the front. For some reason, only in the production environment, the JWT cookie from authentication is not saved in the browser. For DRF authentication, we use dj-rest-auth and djangorestframework-simplejwt. We are using axios to fetch from Next.js and have withCredentials: true enabled. Everything works fine in the local environment, but why aren't cookies being saved in the production environment? The only difference between local and production is the difference in the domain of both (domain.com, sub.domain.com) and SSL. # settings.py CORS_ORIGIN_WHITELIST = 'https://sub.domain.com' CORS_ALLOW_CREDENTIALS = True REST_SESSION_LOGIN = False REST_USE_JWT = True SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=60), "REFRESH_TOKEN_LIFETIME": timedelta(days=7), "ROTATE_REFRESH_TOKENS": True, "BLACKLIST_AFTER_ROTATION": True, "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", } if not DEBUG: JWT_AUTH_SECURE = True set-cookie: jwt-token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjQxOTgxMzIwLCJpYXQiOjE2NDE5Nzc3MjAsImp0aSI6ImJlMDY5NGExMjcyZTQ4NWE5ODQ2ZjRlZGE0NTZjZGQ4IiwidXNlcl9pZCI6Ijg5ODFjZTQ2LTVjYTgtNDM5Ni04YjE3LWM0NWRkNTg3ZWI3YiJ9.FonD-pv8hvB3J3XmCDE0kFBF7HHEPim6IJ7KTrbyIf0; expires=Wed, 12 Jan 2022 09:55:20 GMT; HttpOnly; Max-Age=3600; Path=/; SameSite=Lax; Secure set-cookie: refresh-token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY0MjU4MjUyMCwiaWF0IjoxNjQxOTc3NzIwLCJqdGkiOiIzNDJiZGYxMzM4ZjU0MTA4YTA5M2MyYzM0Nzk1ZmM3ZSIsInVzZXJfaWQiOiI4OTgxY2U0Ni01Y2E4LTQzOTYtOGIxNy1jNDVkZDU4N2ViN2IifQ.D6FQZAZ54wYlGXt_g2ycu4-J-Gq6g7v4S1rb_Nc4IoM; expires=Wed, 19 Jan 2022 08:55:20 GMT; HttpOnly; Max-Age=604800; Path=/; SameSite=Lax; Secure -
How to format negative numbers in django-tables2?
I am looking for nice solution to make a simple subclassed NumericColumn for my tables, based on django-tables2. I started with that: class NumericColumn(Column): def render(self, value): return '{:0,.2f}'.format(value) It works great until I decided to make negative values red: class NumericColumn(Column): attrs = { 'td': { 'class': lambda value: 'text-danger' if value < 0 else '' } } def render(self, value): return '{:0,.2f}'.format(value) Code periodically fails with TypeError: '<' not supported between instances of 'str' and 'int', and it seems that lambda function receives already formatted value. I don't see a way to get an original value in record via accessor, and I don't think that it is nice to make a reverse conversion to Decimal for such comparison. Ok, I can test first character for '-', but it is too ugly. Please help. -
TwiML response body too large error - python django
I am getting error "TwiML response body too large". I am trying to create own opt-out list. When user press 0 to opt out via outbound call, I want to store his phone number to the database. How do I create my own opt-out list? Is there any other way to create own opt-out list. I am new to Twilio. Please help. Thanks. def handle_user_response(request): digits = request.data.get('Digits', '') phone=request.data.get('To','') resp = VoiceResponse() if digits == '0': resp.say("Your phone number is opted out.") OptOutList.objects.create(phoneNumber=phone) else: resp.say("Sorry, I don't understand that choice.") return HttpResponse(str(resp)) Here is my model in django. class OptOutList(models.Model): phoneNumber=models.CharField(max_length=20) def __str__(self): return self.phoneNumber -
How to get all fields of related object Django
I have two models: class Checklist(models.Model): author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) client_name = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='details') filedA = models.CharField(max_length=25, blank=True, null=True) filedA_Check= models.BooleanField(default=False) filedB = models.CharField(max_length=25, blank=True, null=True) filedB_Check= models.BooleanField(default=False) class Client(models.Model): client_filedA = models.CharField(max_length=25) client_filedB = models.CharField(max_length=25) client_filedC = models.CharField(max_length=25) Now I trying to change Client instance fields values via Checklist using following code: @login_required def create_order(request, pk): instance = get_object_or_404(CheckList, id=pk) form = myForm(request.POST or None, instance=instance) if form.is_valid(): form.save() messages.success(request, 'Test message') return get_PDF_order(request, pk) return render(request, 'templates/create_order.html', {'form': form}) And it's works but only once. Data saved and I get a pdf file with this data, but subsequent attempts do not change anything. The field value still the same. I'm guessing that it is because I working with the Checklist instance but not Client. So, my questions are: 1) How I can get an access to all Client fields (a queryset of all fileds) via Checklist? 2) Although my code is incorrect - why does it work (once)? I mean why does it save first time? Thank you all in advance! -
Django forms validating but not showing errors added on clean
I want to get my validation errors printed right after my form. When it comes to validate, it does the work right so if i put a date before today it just doesn´t save the form. Inside this validation I have an error adding line if it doesn´t pass validation like this: class PostVacation(forms.ModelForm): class Meta: model = Vacation fields = ( 'fecha_inicio', 'fecha_fin', ) fecha_inicio = forms.DateField(widget = forms.DateInput(format='%d/%m/%Y',attrs={'type':'date','class': 'form-control'})) fecha_fin = forms.DateField(widget = forms.DateInput(format='%d/%m/%Y',attrs={'type':'date','class': 'form-control'})) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def clean_fecha_inicio(self): data = self.cleaned_data['fecha_inicio'] if data < timezone.now().date(): print(type(data)) self.add_error(None,"La fecha de inicio no puede ser anterior a hoy") return data Inside my template I try this: <div class="col-md-4 listados"> <form method="POST">{% csrf_token %} <div class="form-group"> {{ form.as_p }} {{ form.non_field_errors }} <p>Los campos marcados con * son obligatorios</p> <button type="submit" class="btn boton_generico">Guardar</button> </div> </form> </div> But it just returns empty Any help welcome