Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Deploy Django app with ChannelNameRouter
I am using django-private-chat in one of my application. it starts the chatserver on running command python manage.py run_chat_server please help me deploying it on production server to run the chat server automatically. i have tried adding the ChannelnameRouter class in routing.py of my project application = ProtocolTypeRouter({ "websocket": AuthMiddlewareStack( URLRouter([ # path("notification_u/", UserNotificationConsumer), ]) ), "chat-channel":MessageRouter(), }) -
Unable to call custom template tag
In a html page, I'm trying to call django custom template tag but it seems to me that its never reaching that template tag function. home.html page {% load custom_tags %} {% if has_profile %} <p> Creator </p> {% else %} <li><a href="{% url 'update_profile' %}" class="btn btn-simple">Become a Creator</a></li> {% endif %} custom_tags.py from django import template from users.models import Profile register = template.Library() @register.simple_tag def has_profile(): return 1 Please let me know if you need any information. Thanks! -
Django All_auth/rest_auth e-mail address validation using HTTP GET request
I use Django all_auth and rest_auth for a backend service of a mobile app. I integrated the registration and login API and all works fine. Now I have to integrate the e-mail address validation logic. After the registration (without social), I have to send an e-mail with the link that the user will use to validate your account. I added this configurations into my Django settings: ACCOUNT_EMAIL_VERIFICATION = 'mandatory' SOCIALACCOUNT_EMAIL_VERIFICATION = 'none' Also this works fine. I'm able to receive the e-mail after the registration of a new account. In the received e-mail I have the link to validate the account also. I would like to have the validation of the e-mail when the user simply will click on the link. So, I would like to use only the GET HTTP method. I added, as suggested into the documentation, this setting also: ACCOUNT_CONFIRM_EMAIL_ON_GET = True I use this url linked to the all_auth views. But, if I try to click on the link from the received mail, I obtain this error: KeyError at /account-confirm-email/NzU:1hjl8A:z5Riy8Bjv_h0zJQtoYKuTkKvRLk/ 'key' /allauth/account/views.py in get self.object = self.get_object() ... ▶ Local vars /allauth/account/views.py in get_object key = self.kwargs['key'] ... ▶ Local vars This seams that setting is … -
DJANGO Queryset filter according to inner calculations on nested model
I have a model with the following fields: required_visits : a positive integer person - another model with: name,age,curr_week_visits I would like to filter all the rows in which the following calculation is true: required_visits__minus__person__curr_week_visits__gt=0 in words: the model's required visits minus the person's current weeks visits is bigger than 0 What is the right way to write this filter queryset? -
How can you make a django model which can be displayed on the main page and not on admin page
i'm just doing some studying regarding django and finished a crashcourse on django, in the crashcourse he only showed how to display a Model on the admin page but what if I want a user to use the model and not specifically a admin? E.g what if I want anyone that visits /todo/ to be able to add a todo and not make the todo only be addable by the admin panel. -
Event listener works in on context but not another - code identical, and no errors observed. Possible causes?
I'm bamboozled. I use a select2 widget on a web page, implemented by django-autocomplete-light, and I attach an event listener to the it as follows: const game_selector = $("#"+id_prefix+"game"); game_selector.on("change", switchGame); Works a charm. I select a new game in the select box and the switchGame function is called. That is running on Django development server with manage.py runserver. And I can see how groovy this is in Chrome's debugger: There it is, switchGame(event) is the handler. And it all works too. No drama. But I publish the code to my webserver and suddenly it doesn't work. The event listener never fires. switchGame is never called. It's serving the self same code, looks the same in the client and in Chrome's debugger. All fine. I can even see the event listener is attached, albeit the order is different: Severed by the development server there there is a select2 handler above switchGame in the list and served from the production server the same select2 handler is listed below the switchGame handler. Can the order matter? And why would the order differ? In the end I am looking at the same binding code above, and I can set a breakpoint inside switchGame … -
I want to include Email in signup.html so that users can request to reset password in password_reset_form.html
I was creating a Login Page using Django through a tutorial. While signing up first time through "py manage.py createsuperuser" it asked for email. Than i created the password reset page, and the signup.html page. When i reset a password it sends email to the registered email of my email. When i created a user in the signup.html, it did not ask for email. How would i code it to ask for email so that we can use the password reset option for every user. -
How to create temporary array hotel Check-In list in Django?
I am trying to create a temporary table of people who are Checked-In in Hotel, is there any way of creating a temporary array of elements in Django? -
Do websockets send and receive full messages?
I am new to web development and I am trying to write a simple web game using python and django for my server with some javascript for the front end graphics. I am using the channels package to use websockets for the communication and I have a little question about websockets. In python, I know that when we use sockets, the message isn't guaranteed to be sent fully. For example, if I use socket.send in python, I may not send the entire message and in that case I need to resend what is left, and on the receiving side, I am not guaranteed to get the full message using socket.recv (assuming the bufsize argument is big enough for the full message), so I have to keep calling recv until I get the entire message. My question is: Is it the same with websockets or not? I tried looking for this in the MDN docummentation and in google, but I couldn't find any information on this. In addition, every example I have seen online didn't take this into account, so it seems like what I send with socket.send (in javascript) is exactly what I get on the other end and vice … -
How to filter in DRF ListAPIView using django_filters FilterSet on JSONField field
i want to make an API request in Django Restframework like http://localhost:8000/apis/services/?page=1&name=2 The model from django.contrib.postgres.fields import JSONField class Service(models.Model): name = JSONField(default=dict) The APIView class DashboardServicesAPIView(ListAPIView): queryset = Service.objects.none() serializer_class = ServiceSerializer permission_classes = (AllowAny,) filter_class = ServiceFilter def get_queryset(self): return Service.objects.all() The FilterSet class ServiceFilter(django_filters.rest_framework.FilterSet): name = django_filters.CharFilter(field_name="name", lookup_expr='icontains') class Meta: model = Service fields = [ "name"] querying with filter querystring is not working the same result is always returned. Any help on what i missed dealing with JSON? -
Change subprocess Popen from file to `Django InMemoryUploadedFile`
I have a function that require filename as an input argument and return list of str. import subprocess def get_length(filename: str) -> typing.List[str]: result = subprocess.Popen(["ffprobe", filename], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return [x.decode('utf-8') for x in result.stdout.readlines() if "Duration" in str(x)] In the Django application. I use it with InMemoryUploadedFile. My quick solution is write down a file to disk and read it to the function. Question: Is it possible to let my get_length() read from the InMemoryUploadedFile rather than physical file`? -
Django rest "this field is requiered" on a many to many field when blank=True
I have an object I would like to be able to make via django-rest-api UI. This object has a manytomany field that holds other objects on it. Even though that field is blank param is set to True, I get a response that "this field is requiered". class Post(models.Model): title = models.CharField(max_length=100) slug = models.CharField(max_length=200, null=True) description = models.CharField(max_length=200, null=True) content = HTMLField('Content', null=True) black_listed = models.ManyToManyField('profile_app.Profile', related_name='black_listed_posts', blank=True) score = models.PositiveIntegerField(null=True, default=0, validators=[MaxValueValidator(100)]) serializers.py: class PostSerializer(serializers.HyperlinkedModelSerializer): black_listed = ProfileSerializer(many=True) read_only = ('id',) def create(self, validated_data): self.black_listed = [] class Meta: model = Post fields = ('id', 'title', 'slug', 'description', 'content', 'black_listed', 'score') views.py: class PostViewSet(ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() lookup_field = "slug" def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.black_listed = [] if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) As you can see, i tried overriding the create() method on both serializer and viewset, but that didnt work and still gave me that the black_list field is requiered. What i expected that if the field is not required in the db, then the serializer can set it to None on the creation what am i missing here? -
While giving the command - python manage.py runserver, it shows the given error
Error while executing python manage.py runserver enter code here Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\hp\appdata\local\programs\python\python37\Lib\threading.py", line 917, in _bootstrap_inner self.run() File "c:\users\hp\appdata\local\programs\python\python37\Lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\rest_framework_filters\__init__.py", line 3, in <module> from .filterset import FilterSet File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\rest_framework_filters\filterset.py", line 10, in <module> from django_filters import filterset, rest_framework File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django_filters\__init__.py", line 7, in <module> from .filterset import FilterSet File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django_filters\filterset.py", line 15, in <module> from .filters import ( File "C:\Users\HP\Desktop\iam_orm_layer\env\lib\site-packages\django_filters\filters.py", line 10, in … -
Why are files uploaded from phone processed slower then files uploaded from pc on a webpage by django/nginx?
I have a webpage running on django+gunicorn+nginx, it has a file input and a post button. If i send a file using this webpage from pc, it is processed in a few seconds, but if i send the same file using this webpage from my iphone it takes more then two minutes. Why? How can i make it faster? <h2>Main page</h2> <form method='post' enctype="multipart/form-data"> {% csrf_token %} <input type="file" name='img_file'> <button type='submit'>Send</button> </form> {% if answers%} {% for answer in answers%} {{answer| safe}} {% endfor %} {% endif %} {% if file_extension %} {{ file_extension }} {% endif %} def main(request): user_session = request.session.session_key content = {} if not user_session: request.session.create() user_session = request.session.session_key if request.method == "POST": myfile = request.FILES.get('img_file') print(myfile) fs = FileSystemStorage() file_prefix, file_extension = os.path.splitext(myfile.name) filename = fs.save(user_session + file_extension, myfile) answer_list = image_to_answer(MEDIA_ROOT + '/' + filename)# takes most time to process uploaded_file_url = fs.url(filename) content = {'ufu': uploaded_file_url, 'answers': answer_list, 'file_extension': file_extension} return render(request, 'mainapp/index.html', content) input: posted xxx.jpeg file output: html code (for example: 'answer1'blue'') that will be part of template for returned page (answers in index.html) -
Page not found error while deploying django app on centos7 using nginx and uwsgi
I'm trying to deploy my django app on a centOS7 server using VPS with nginx and uwsgi, following this tutorial https://www.youtube.com/watch?v=c_17jALtLbQ&feature=youtu.be. The server is up and running i.e., the homepage (welcome to nginx) is working but when I navigate to a different page it tells me "page not found". Previously, I also tried using Apache following this https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-centos-7. But it tells me "you don't have permission to access /url/". Following is the code for /etc/nginx/sites-available/sitename: server{ listen 80; server_name localhost; location / { uwsgi_pass unix:///tmp/main.sock; include uwsgi_params; } location /static/ { alias /var/www/supplychain/Supply_Chain_Proj/static/; } } And this is my /etc/uwsgi/apps-available/sitename.ini file: [uwsgi] vhost = true plugins = python socket = /tmp/main.sock master = true enable-threads = true processes = 4 wsgi-file = /var/www/supplychain/Supply_Chain_Proj/supply_chain/wsgi.py virtualenv = /var/www/venv/site chdir = /var/www/supplychain/Supply_Chain_Proj touch-reload = /var/www/supplychain/Supply_Chain_Proj/reload env = DJANGO_ENV=production env = ALLOWED_HOSTS=* -
Carousel is not loading properly
I have made carousel in my home page which lists the products the user wishes to purchase in a card view split by category. Earlier it was working fine and 3 cards per each category were displayed. However, now the carousel doesn't load properly. My HTML code looks like this: <div class="container-fluid ml-5"> {% for product, range, nSlides in allProds %} <h5>{{product.0.category}}</h5> <div class="row"> <div id="myCarousel{{forloop.counter}}" class="col carousel slide mt-3 mr-3 ml-1" data-ride="carousel" data-interval="false"> <ol class="carousel-indicators"> <li data-target="#myCarousel{{forloop.counter}}" data-slide-to="0" class="active"></li> {% for i in range %} <li data-target="#myCarousel{{forloop.parentloop.counter}}" data-slide-to="{{i}}"></li> {% endfor %} </ol> <!-- Slideshow starts here(1.1) --> <div class="container carousel-innner row w-100 mx-auto"> <div class="carousel-item active mr-3"> <!--Slides --> {% for i in product %} <div class="col-xs-3 col-sm-3 col-md-3 col-lg-3 mr-3"> <div class="card align-items-center mt-3 mr-3" style="width: 18rem;"> <img src="/media/{{i.image}}" class="card-img-top" alt="..."> <div class="card-body text-center"> <h6 class="card-title" id="namepr{{i.id}}">{{i.product_name}}</h6> <h6 class="card-title"><b>Price: ₹ <span id="pricepr{{i.id}}">{{i.price}}</span></b></h6> <h6 class="card-title"><b>Stock:<span id="stockpr{{i.id}}">{{i.stock}}</span></b></h6> <!-- <p class="card-text">{{i.description|slice:"0:70"}}...</p> --> <span id="divpr{{i.id}}" class="divpr"> <button id="pr{{i.id}}" class="btn btn-primary cart">Add to Cart</button> </span> <a href="/shop/products/{{i.id}}"><button id="qv{{i.id}} " href="#" class="btn btn-primary cart">Quick View</button></a> </div> </div> </div> {% if forloop.counter|divisibleby:3 and forloop.counter > 0 and not forloop.last %} </div> <div class="carousel-item"> {% endif %} {% endfor %} </div> </div> </div> <!-- Left Right … -
Dynamic updates in real time to a django template
I'm building a django app that will provide real time data. I'm fairly new to Django, and now i'm focusing on how to update my data in real time, without having to reload the whole page. Some clarification: the real time data should be update regularly, not only through a user input. View def home(request): symbol = "BTCUSDT" tst = client.get_ticker(symbol=symbol) test = tst['lastPrice'] context={"test":test} return render(request, "main/home.html", context ) Template <h3> var: {{test}} </h3> I already asked this question, but i'm having some doubts: I've been told to use Ajax, and that's ok, but is Ajax good for this case, where i will have a page loaded with data updated in real time every x seconds? I have also been told to use DRF (Django Rest Framework). I've been digging through it a lot, but what it's not clear to me is how does it work with this particular case. -
Python-Django [SSL: WRONG_VERSION_NUMBER] Error
While I'm trying to connect to my localhost, I get [SSL: WRONG_VERSION_NUMBER] error. I'm using '8080' port by default. Previously, I was getting ProxyError, then I changed my url from 'http' to 'https' and now I get SSLError. I've checked some solutions, which prompts to change the port number. Does it have to do anything with the port number, or something else? views.py: endpoint = 'https://****:8080/MyApp/services/DBConnection/callLoginProcedure' def index(request): post = request.POST if request.POST.get('login_button'): qd = QueryDict(mutable=True) qd.update( inputPhoneNumber=request.POST.get('phone_num'), inputPassword=request.POST.get('password') ) response = requests.post('{}?{}'.format(endpoint, qd.urlencode()), verify=False) result = response.json() messages.info(request, result) return render(request, 'login/index.html') The error is as follows stacktrace: Django Version: 2.2.3 Python Version: 3.7.3 Installed Applications: ['login', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware'] Traceback: File "C:\Program Files\Python37\lib\site-packages\urllib3\connectionpool.py" in urlopen 603. chunked=chunked) File "C:\Program Files\Python37\lib\site-packages\urllib3\connectionpool.py" in _make_request 344. self._validate_conn(conn) File "C:\Program Files\Python37\lib\site-packages\urllib3\connectionpool.py" in _validate_conn 843. conn.connect() File "C:\Program Files\Python37\lib\site-packages\urllib3\connection.py" in connect 370. ssl_context=context) File "C:\Program Files\Python37\lib\site-packages\urllib3\util\ssl_.py" in ssl_wrap_socket 368. return context.wrap_socket(sock) File "C:\Program Files\Python37\lib\ssl.py" in wrap_socket 412. session=session File "C:\Program Files\Python37\lib\ssl.py" in _create 853. self.do_handshake() File "C:\Program Files\Python37\lib\ssl.py" in do_handshake 1117. self._sslobj.do_handshake() During handling of the above exception ([SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056)), another exception occurred: File "C:\Program Files\Python37\lib\site-packages\requests\adapters.py" in send 449. … -
What is it the max_length in the password of Django User?
My problem is that I don't feel sure because I don't understand how work the password field in Django, that is to say, I think that this field hasn't got any max_length and it can be attacked with a buffer overflow. Is this possible? I am using de default Django User. -
AttributeError:'Student' object has no attribute 'check_password'
I user Custom User Model named Student which inherits Django User Model. I have problem in its logon when I want to use check_password. The error is that Student which is a custom user model has not such attribute. I wanna login students with the registered information by them. and the fields to login is identity_no and student_no. views.py: class StudentLoginSerializer(serializers.ModelSerializer): user = CustomUserSerializerForLogin() class Meta: model = Student fields = [ "user", "student_no", ] def validate(self, data): # validated_data user_data = data.pop('user', None) identity_no = user_data.get('identity_no') print("identity_no", identity_no) student_no = data.get("student_no") user = Student.objects.filter( Q(user__identity_no=identity_no) | Q(student_no=student_no) ).distinct() # user = user.exclude(user__identity_no__isnull=True).exclude(user__identity_no__iexact='') if user.exists() and user.count() == 1: user_obj = user.first() else: raise ValidationError("This username or student_no is not existed") if user_obj: if not user_obj.check_password(student_no): # Return a boolean of whether the raw_password was correct. raise ValidationError("Incorrect Credential please try again") return user_obj I print(dir(user_obj)) and the output is: ['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', '_check_column_name_clashes', '_check_field_name_clashes', '_check_fields', '_check_id_field', '_check_index_together', '_check_local_fields', '_check_long_column_names', '_check_m2m_through_same_relationship', '_check_managers', '_check_model', '_check_model_name_db_lookup_clashes', '_check_ordering', '_check_swappable', '_check_unique_together', '_do_insert', '_do_update', '_get_FIELD_display', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', … -
Get value from ChoiceField and returns filtered result
How do I get the value from a ChoiceField dropdown list and returns a list of filtered result back to frontend? Currently I can only show the values in the dropdown list but I failed to return back the selected result views.py def index(request): rest_list = Restaurant.objects.order_by('-restname') query_results = Restaurant.objects.all() region_list = regionChoiceField() if request.method == "POST": selected_region = request.POST.get("region") query_results = query_results.filter(region=selected_region) context = { 'rest_list': rest_list, 'query_results': query_results, 'region_list': region_list, } return render(request, 'index.html', context) index.html <body> <form method="post" name="dropdown">{% csrf_token %} {{ region_list }} </form> <table> {% for rest in query_results %} <tr> <td>{{ rest.restname }}</td> </tr> {% endfor %} </table> </body> models.py class Restaurant(models.Model): restname = models.CharField(max_length=200) # Field name made lowercase. phone = models.IntegerField() address = models.CharField(max_length=200) cuisine = models.CharField(max_length=200) region = models.CharField(max_length=200) last_modify_date = models.DateTimeField() created = models.DateTimeField() def __str__(self): return self.restname -
Django filter list of card types only the latest
I have a Django model of some different card types How can I get only the latest of each type in the filter? cards.filter(card_type__in=[1,2]) -
Django + Docker best practice: use runserver or wsgi.py?
I've been reading a lot of blog posts (like this one) on how to deploy Django in a containerized Docker environment. They all use the runserver command in the docker-compose.yml. Even the Docker documentation does this. This suprises me, since using the Django web server is not recommended for production! What is recommended is pointing the webserver to wsgi.py. However, none of the articles I've found on Django and Docker explain why they use runserver instead of pointing apache or nginx to wsgi.py. Why would all these articles use the built-in Django development webserver to handle requests, instead of a full blown webserver like apache or nginx? Isn't the point of using containers in development, to keep that environment as close to production as possible? Then why build a not-production-ready environment? -
Forcing sql_mode to "STRICT_TRANS_TABLES" still got warning Django
I'm using Django 2.1.3 ,pymysql 0.9.2, mysql 5.7, python3.5 sql_mode in mysql: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION db setting in django: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', ..., 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", 'charset': 'utf8mb4' }, } And I always get warning like this: /venv3.5/lib/python3.5/site-packages/pymysql/cursors.py:170: Warning: (3135, "'NO_ZERO_DATE', 'NO_ZERO_IN_DATE' and 'ERROR_FOR_DIVISION_BY_ZERO' sql modes should be used with strict mode. They will be merged with strict mode in a future release.") result = self._query(query) /venv3.5/lib/python3.5/site-packages/pymysql/cursors.py:170: Warning: (3090, "Changing sql mode 'NO_AUTO_CREATE_USER' is deprecated. It will be removed in a future release.") result = self._query(query) Why I got the warning like above? Any commentary is very welcome. great thanks. -
How can I get return value from a web-service with django/python
I am posting some parameters to a web-service as follows: requests.post("http://**.***.**.**:****/MyLogin/services/DBConnection/callLoginProcedure?inputPhoneNumber=" + phone + "&inputPassword=" + password) The "callLoginProcedure" returns an integer value but I couldn't manage to get that value. How can I get this return value? views.py: def index(request): post = request.POST.copy() if post.get('login_button'): phone = post.get('phone_num') password = post.get('password') requests.post("http://68.183.75.84:8080/Calculator/services/DBConnection/callLoginProcedure? inputPhoneNumber=" + phone + "&inputPassword=" + password) r = request.GET.get("return", "-1") # if r == 1: # messages.info(request, 'successful!') # else: # messages.info(request, 'unsuccessful!') messages.info(request, r) return render(request, 'login/index.html') urls.py: urlpatterns = [ url(r'^$', views.index, name = 'index'), path(r'^$', views.index, name = 'script'), ]