Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What's the relationship between csrfmiddlewaretoken and csrftoken?
I was working with Django to create a website and got some questions about CSRF. I use django.middleware.csrf.CsrfViewMiddleware and add <form action="" method="post">{% csrf_token %} in my POST form. And when I test the website: GET / HTTP/1.1 Host: 123.207.137.168:8000 Then, I got cookies Set-Cookie:csrftoken=Ev8veOH89vFDnG3a0GJUsMXA1oGZXxqXRw2nFWiKrvZ9UE10niTlZCiOxdnoKfTv; expires=Thu, 27-Dec-2018 06:37:41 GMT; Max-Age=31449600; Path=/ But in the html: <input type='hidden' name='csrfmiddlewaretoken' value='JswHLk4fNpxHkh0OObD1uKiOxSDUzkMDWtqzcsFR5pRdRfYEbNNs1AD23Hkjm2fb' /> So I was wondering why the csrftoken and csrfmiddlewaretoken is different and how did the server use these two value to valid if the request is from the users or hackers? -
nginx 502 bad gateway gunicorn
I am tried to load a page with django formset, I clearly see in the logs that the backend logic is executed well within 1 second, I have a logger printing right before return render() and it is very clear that the backend process is almost done. The point here is,it is taking way too much time to render the template and nginx throwing bad gateway at me. What should I do? -
How can I add a 'is_logged_in' condition along with another if statement in django python?
This is my views.py for search. @csrf_exempt def search(request): if request.method == 'POST': name = request.POST.get('name') loc = request.POST.get('location') bussinessName = request.POST.get('bussinessName') d = { 'name': name, 'loc': loc, 'bussinessName': bussinessName, } return render(request, "search.html", d); else: # do the thing you want to do in GET method return render(request,"search.html",{}); I need to add a session to get the id. This is how I am getting the id for my success page def success(request): if('is_logged_in' in request.session): id = request.session['authToken']; return render(request,"success.html",{'uid':id}); else: return render(request,"success.html",{}); HOW CAN I able to add this session in search. I am a beginner in Django and I do not have much idea about the same. Please help me to have a session for my search too.. -
How to upload multiple files individually with additional data
I am using blueimp's fileupload. The data is sendable if I do not try to send an additional input on submit. I am trying to upload files with a title following this pattern: user clicks a "select HHs" button to select files After the files are selected and opened, user sees every file listed in rows with a "title" input box and a "submit" button. User types in value for the "title" box and hits "submit" button to send to backend. After #3, I keep getting a 403 sent back a "Forbidden (CSRF token missing or incorrect.)" on the server side (django). Why am I getting this error message and how do I solve this issue? I've replaced data.formData with a simple object to test what I'm trying to accomplish below. upload.js file: $('#fileupload').fileupload({ formData: {title: 'test'}, dataType: 'json', ... add: function (e, data) { var convertElem = $('<input type="submit"/>').click(function() { data.formData = {"title":"test"}; data.submit(); }); ... data.context = $(outerElem) ... } }); upload.html: <button>Select</button> <form id="fileupload" data-url="{% url 'file-upload' %}" enctype="multipart/form-data" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'> <input id="fileupload-files" type="file" name="file" multiple> </form> -
Django detailView an duplicates from foreign key relationship
Really hoping someone can point me in the right direction here. I'm new to Django and about ready to move back to CakePHP since I can't seem to find an answer anywhere. I'm most likely looking in the wrong direction so any guidance would be hugely appreciated. Models class active_customer(models.Model): custno = models.IntegerField(primary_key=True) company = models.CharField(max_length=256) cust_firstname = models.CharField(max_length=50) address = models.CharField(max_length=100) address2 = models.CharField(max_length=100) suburb = models.CharField(max_length=200) state = models.CharField(max_length=3) postcode = models.IntegerField() contact_phone = models.CharField(max_length=20) contact_mobile = models.CharField(max_length=20) contact_fax = models.CharField(max_length=20) contact_email = models.CharField(max_length=200) contact_firstname = models.CharField(max_length=200) contact_surname = models.CharField(max_length=200) def __str__(self): #string used to identify the model object return self.company class active_service(models.Model): customer_name = models.CharField(max_length=50) service_number = models.CharField(primary_key=True, max_length=100) customer = models.ForeignKey('active_customer', db_column='customer') service_id = models.CharField(max_length=6) service_type = models.CharField(max_length=50) sub_address_type = models.CharField(max_length=50) sub_address_no = models.CharField(max_length=10) street_no = models.CharField(max_length=50) street_name = models.CharField(max_length=200) street_type = models.CharField(max_length=50) suburb = models.CharField(max_length=100) postcode = models.CharField(max_length=4, null=True) state = models.CharField(max_length=3, null=True) def __str__(self): #string used to identify the model object return self.service_number URLS urlpatterns = [ url(r'^customer-profile/(?P<pk>\d+)$', views.CustomerDetailView.as_view(), name='active_customer_profile'),] View class CustomerDetailView(generic.DetailView): model = active_customer context_object_name = "active_customer_profile" template_name = "nbn/active_customer_profile.html" Template <h4>Customer Addresses</h4> {% for active_service in active_customer_profile.active_service_set.all %} <li>{{ active_service.suburb }}</li> {% empty %} <li>No addresses found, contact IT.</li> {% endfor … -
Wagtail can't access images on S3 - I/O operation on closed file
I'm trying to get Wagtail to store and serve images from an AWS S3 bucket. I have followed the instructions and have it working great in a test environment, however when I switch to the Production Database and Bucket, I run into problems using the Admin and occasionally the frontend too. I have: boto3==1.4.8 botocore==1.8.1 wagtail==1.10c1 python 2.7 What I do: I go to /admin/, browse Images, it shows a list of image thumbnails (so far so good) I click on one of them and I get a Django error: ValueError at /admin/images/4236/ I/O operation on closed file The exception says: /usr/lib/python2.7/StringIO.py in tell _complain_ifclosed(self.closed) ... /usr/lib/python2.7/StringIO.py in _complain_ifclosed raise ValueError, "I/O operation on closed file" ... But, like I said, it works in a new test environment with only a few images. The issue seems to be a time out. We have about 4,000 original images (and then results in about 18,000 resized images). They are all in the one collection. Is there any way to increase the time out on this operation so that it doesn't time out? I can see the database has values for width, height, file_size columns; why is Wagtail trying to read this info … -
Django rest framework with djoser customise token authentication response
As i am using a third party package called djoser to handle the token authentication. i want to customise the response. But after trying to change it, the result is not what i wanted. Here is the link to djoser: https://github.com/sunscrapers/djoser Here is my code : models.py class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) gender = models.CharField(max_length=6, blank=True, null=True) nric = models.CharField(max_length=9, blank=True, null=True) birthday = models.DateField(blank=True, null=True) birthTime = models.TimeField(blank=True, null=True) ethnicGroup = models.CharField(max_length=30, blank=True, null=True) def __str__(self): return self.username serializer.py class TokenCreateSerializer(serializers.Serializer): password = serializers.CharField( required=False, style={'input_type': 'password'} ) default_error_messages = { 'invalid_credentials': constants.INVALID_CREDENTIALS_ERROR, 'inactive_account': constants.INACTIVE_ACCOUNT_ERROR, } def __init__(self, *args, **kwargs): super(TokenCreateSerializer, self).__init__(*args, **kwargs) self.user = None self.fields[User.USERNAME_FIELD] = serializers.CharField( required=False ) def validate(self, attrs): self.user = authenticate( username=attrs.get(User.USERNAME_FIELD), password=attrs.get('password') ) self._validate_user_exists(self.user) self._validate_user_is_active(self.user) return attrs def _validate_user_exists(self, user): if not user: self.fail('invalid_credentials') def _validate_user_is_active(self, user): if not user.is_active: self.fail('inactive_account') views.py class TokenCreateView(utils.ActionViewMixin, generics.GenericAPIView): """ Use this endpoint to obtain user authentication token. """ serializer_class = settings.SERIALIZERS.token_create permission_classes = [permissions.AllowAny] def _action(self, serializer): token = utils.login_user(self.request, serializer.user) token_serializer_class = settings.SERIALIZERS.token return Response( data=token_serializer_class(token).data, status=status.HTTP_200_OK, ) my custom serializer.py class TokenCreateSerializer(serializers.Serializer): password = serializers.CharField( required=False, style={'input_type': 'password'} ) class Meta: model = MyUser def __init__(self, *args, **kwargs): super(TokenCreateSerializer, self).__init__(*args, **kwargs) self.user = … -
python-docx Table column position and order
I used python-docx module to create Tables. I have a dabase table named data, and I get it by django queryset. The python-docx Table values' code like below: heading_cells = table.rows[0].cells keys = data[0].keys() keys = list(keys) for r in range(len(keys)): heading_cells[r].text = keys[r] values = list(data[i].values()) for r in range(len(keys)): device_table.cell(i + 1, r).text = str(values[r]) I got the Table in my .doc successfully. My problem is: I want to add a column Leftmost, how to do it? and I want to modify every columns position like the first column is id ,the second is name...... how to do it? Thanks! -
Django queryset list that have expanded relational model data
In my Django webapp, I have Function Based API that display a list for with pagination. The problem is I want each row in the list to have expanded output of relational field. This is my model for attendance: class Attendance(models.Model): CHECKIN = 1 CHECKOUT = 2 ATTENDANCE_TYPE_CHOICES = ( (CHECKIN, "Check In"), (CHECKOUT, "Check Out"), ) employee = models.ForeignKey(Employee) company = models.ForeignKey(Company) activity_type = models.IntegerField(choices = ATTENDANCE_TYPE_CHOICES, default=CHECKIN) This is part of my list API where I define what fields I want to display and is paginated. employee_list = Employee.objects.filter(company = auth_employee.employee.company.id).values("id","employee","company","activity_type").order_by('id') page = request.GET.get('page', request.POST['page']) paginator = Paginator(employee_list, request.POST['page_limit']) try: employees = paginator.page(page) except PageNotAnInteger: employees = paginator.page(request.POST['page']) except EmptyPage: employees = paginator.page(paginator.num_pages) return Response(list(employees), status=status.HTTP_200_OK) The output is a list like this but without employee detail. [ { "id": 14, "employee": 15, "company": 15, "activity_type": 1, }, { "id": 15, "employee": 15, "company": 15, "activity_type": 2, } ] My expected output, how do I get something like this ? [ { "id": 14, "employee": { "id":"2", "name":"Michael" }, "company": 15, "activity_type": 1, }, { "id": 15, "employee": { "id":"2", "name":"Jeniffer" }, "company": 15, "activity_type": 2, } ] How can I produce a list that shows the relational … -
Sort and set REST API data into a new list
I'm trying to create a report table based from an API, but the API currently is not sorted as I wanted it to be and I'm not sure how to rearrange it. Here's an example of how the API that look like this : [ { "task": { "id": 2, "name": "Texturing", }, "assign_to": { "id": 1, "official_name": "Roy Harper", }, "duration": 3.0, }, { "task": { "id": 4, "name": "Lighting", }, "assign_to": { "id": 3, "official_name": "Donna Troy", }, "duration": 4.0, }, { "task": { "id": 8, "name": "Rendering", }, "assign_to": { "id": 1, "official_name": "Roy Harper", }, "duration": 7.0, }, { "task": { "id": 11, "name": "Coloring", }, "assign_to": { "id": 3, "official_name": "Donna Troy", }, "duration": 5.0, }, { ] What i trying to achieve now, is an API list that centralize on the assign_to field and also set the list so it only populate the same person once. here's how the desired output that I trying to achieve : [ { "assign_to": { "id": 1, "official_name": "Roy Harper", }, "total_task"[ "task":{ "id": 4, "name": "Lighting", }, "duration": 3.0, "task":{ "id": 8, "name": "Rendering", }, "duration": 7.0, ], }, { "assign_to": { "id": 3, "official_name": "Donna Troy", … -
How do I handle multiple choice using Django?
Suppose I have a model with a multiple choice field and 4 options. This would be passed to the template and rendered on the HTML page. I want the user to select an option, and then process the option and return either "Correct" or "incorrect". I'm not too sure how to go on about starting this, any help is so much appreciated. -
Django cannot import models into commands
I have an app with the following folder structure: - project - dashboard - consumption - management - commands - command.py - models.py - dashboard - data And what I'm trying to do is import models.py into command.py with following import: from dashboard.consumption.models import * But I get the following error: ModuleNotFoundError: No module named 'dashboard.consumption' Despite my installed apps in settings.py being: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'consumption', ] Any idea why the import isn't working? -
Cannot login with Django custom login
So i do not want to use the inbuilt login in Django .Going about a custom login is very important to my project. So i created a custom login using function base view ,but when i try to log in ,i can not login , but instead i get a display message stating, "the user already exist". As if i am trying to create an account . Bellow is my lfunction base view code to login user . # Login account def login_view(request): if request.method == 'POST': form= UserLoginForm(request.POST) if form.is_valid(): username=form.cleaned_data['username'] password=form.cleaned_data['password'] user = authenticate(username=username,password=password) if user is not None: if user.is_active: login(request,user) return rederict('gbiz1990:businesshub') else: print("invalid login details" + username +""+password) form=UserLoginForm() return render(request,'gbiz1990/user_account/login.html',{'form':form}) else: form=UserLoginForm() return render(request,'gbiz1990/user_account/login.html',{'form':form}) form.py class UserLoginForm(forms.ModelForm): class Meta: exclude=['first_name','last_name','email'] widgets={ 'password':forms.PasswordInput(attrs={'class':'password'}), 'username':forms.TextInput(attrs={'class':'name'}), } model =User fields=['username','password'] So please help me to find out ,where i am my going wrong with my code .Thanks in advance -
Unable to save response data to instance's fields; other data in same block is saved correctly (Django/Celery)
I'm running a task to create an account on a third-party service and save relevant data from that service's response to my profile object. The data is getting returned correctly but not being properly saved on the object. Relevant code: # payload is generated in helper method. if that was the point of # failure, i'd see an error result = self.third_party_client.post(self.creation_endpoint, payload) json_result = result.json() if json_result.get('Error') != 'SUCCESS': # Account Creation Failed. error is handled. else: # Currently I log this on our staging server to make sure # the data's coming back properly; it is returned as expected self.logger.error('CoreCard Account Created. Data: {}'.format(json_result)) profile = user.profile profile.account_number = json_result.get('AccountNumber') profile.card_number_last_four = int(json_result.get('CardNumber')[12:]) profile.customer_id = json_result.get('CustomerID') profile.account_creation_datetime = datetime.datetime.utcnow() profile.save() So if I then query this profile instance, it has the account_creation_datetime value as expected, but the other fields are blank. I've checked the logs and the json_result values are all correct. Now here's where it's a bit weird. Where I think it's actually failing is the celery task that calls the utility that runs this bit of code. If I run this utility manually, the fields are saved properly. If I run it as part of our … -
Django raising ValueError: invalid literal for int() with base 10 on POST
Django is consistently throwing a ValueError on every POST request to the server. From cruising around forms and SE, it seems like this an issue with my Django models. However, I'm not sure why the models would throw this error or why they would be called by Django since this is thrown in a POST event. View in question: def channel(request, channel): user_form = weblog_userForm(request.POST or None) if request.method == 'POST' and user_form.is_valid(): nickname = user_form.cleaned_data['nickname'] message = user_form.cleaned_data['message'] password = user_form.cleaned_data['password'] postDetails = {} ... process request and eventually ... return HttpResponse(json.dumps(postDetails), content_type="application/json") My application models: class Line(models.Model): message = models.TextField(blank=True, default="") nick = models.CharField(max_length=50) hostname = models.CharField(max_length=300) channel = models.CharField(max_length=200) timestamp = models.DateTimeField(auto_now_add=True) LINE_TYPES = ( ('PMSG', 'PRIVMSG'), ('SMSG', 'SOCKETMSG'), ('WMSG', 'WEBMSG'), ('NTCE', 'NOTICE'), ('ACTN', 'ACTION'), ('JOIN', 'JOIN'), ('PART', 'PART'), ('QUIT', 'QUIT'), ('NICK', 'NICK'), ('TPIC', 'TOPIC'), ) msgType = models.CharField(max_length=4, choices=LINE_TYPES, default='PRIVMSG') def __str__(self): return self.message class banned_ips(models.Model): bannedIp = models.GenericIPAddressField() Traceback: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/django/weblogs/log/views.py", line 96, in channel json_data = serializers.serialize("json", list(reversed(Line.objects.filter(id__gt=latest_line_id, channel=channel).order_by('-id')[:100]))) … -
Django gunicorn Can't connect to socket as user
Gunicorn shows me socket failed to connect when run as user, but when run as root it worked flawlessly. Below is the command. cd /home/myuser/web/myproject source /home/myuser/myvenv/bin/activate /home/myuser/myvenv/bin/gunicorn myproject.wsgi:application --name myproject --workers 3 --user=myuser --group=www-data --bind=unix:/home/myuser/myvenv/run/gunicorn.sock where Django project path: /home/myuser/web/myproject (which contains manage.py) Python virtualenv path: /home/myuser/myvenv When run as root: [2017-12-27 23:25:43 +0000] [24336] [INFO] Starting gunicorn 19.7.1 [2017-12-27 23:25:43 +0000] [24336] [INFO] Listening at: unix:/home/myuser/myvenv/run/gunicorn.sock (24336) [2017-12-27 23:25:43 +0000] [24336] [INFO] Using worker: sync [2017-12-27 23:25:43 +0000] [24339] [INFO] Booting worker with pid: 24339 [2017-12-27 23:25:43 +0000] [24340] [INFO] Booting worker with pid: 24340 [2017-12-27 23:25:44 +0000] [24377] [INFO] Booting worker with pid: 24377 I killed the process, and made sure it does not exist in ps -A | grep gunicorn. Then I tried to run same command as myuser. Below is the error when I run the command. [2017-12-27 23:21:30 +0000] [23965] [INFO] Starting gunicorn 19.7.1 [2017-12-27 23:21:30 +0000] [23965] [ERROR] Retrying in 1 second. [2017-12-27 23:21:31 +0000] [23965] [ERROR] Retrying in 1 second. [2017-12-27 23:21:32 +0000] [23965] [ERROR] Retrying in 1 second. [2017-12-27 23:21:33 +0000] [23965] [ERROR] Retrying in 1 second. [2017-12-27 23:21:34 +0000] [23965] [ERROR] Retrying in 1 second. [2017-12-27 23:21:35 +0000] [23965] [ERROR] … -
How to login using django & mongodb
I have coding challenge must use technologies: - Python/Django - Backend : Django - Frontend : Angular - Database : MongoDB I found some problems in login, in django how i can login using database mongodb views def auth_login(request, on_success='/', on_fail='/account/login'): user = authenticate(username=request.POST['email'], password=request.POST['password']) if user is not None: login(request, user) return redirect(on_success) else: return redirect(on_fail) Error : settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. -
How can I implement EAV in Django?
Can Django implement EAV? If so, how would you go about doing so? I am new to Django so I am trying to learn this early on so I do not waste time attempting it on my own. -
Django REST Framework custom headers in request object
I have a problem viewing incoming custom headers from requests when I'm creating a new API view via the @api_view decorator. My custom API view looks like this: @api_view(['GET']) def TestView(request): print(request.META) return Response({'message': 'test'}) What I'm expecting is doing something like curl --request GET \ --url http://localhost:8000/test \ --header 'custom: test' I'd see my custom header called custom to appear in the output. Instead, it's not there at all. From the documentation, it says the following for the request.META field: A dictionary containing all available HTTP headers. Available headers depend on the client and server, but here are some examples: Whereas, they don't appear at all in my output. Am I missing something here? If it's relevant, I register my URL as such: urlpatterns = [url(r'test', views.TestView, name='test'), ...] My end goal is to write a custom permission class that will parse the custom header and do something related to authentication with it, and either allow or deny the request. My POC here is just to show the basic example of what I'm dealing with. I can provide the output of the print(request.META) but it's just a wall of text without my expected header present. -
Recording temporarily before payment
I am working on a workflow to create an order. Here is what I got so far from django.db import models from django.utils.translation import ugettext_lazy as _ from django_fsm import FSMField, transition from ev5.core.models import TimeStampedModel class Order(TimeStampedModel): STATE_CHOICES = ( ('start', _('Start')), ('received', _('Received')), ('completed', _('Completed')), ('approved', _('Approved')), ) date_order = models.DateTimeField(_('Order date')) customer = models.ForeignKey('customers.Customer') state = FSMField(...) def get_id_display(self): return '#{0.8d}'.format(self.pk) def __str__(self): return _('Order {} ({})').format(self.get_id_display(), self.get_state_display()) @transition(field=state, source='start', target='received') def received(self): pass @transition(field=state, source='placed', target='completed') def completed(self): pass @transition(field=state, source='completed', target='approved') def approved(self): pass I need to implement a standard workflow with three linear steps to handle, i.e. Select Plan & Preference, Personal Information, and Review & Payment. Select Plan & Preferences: A client may choose one plan as well as some craft products. Personal Information: A client will fill fields related to where he lives, phone number, first name, last name, email, ... Review & Payment : Create an account if necessary, Review his/her order and make the payment related to the current order. Roughly, an account and an order will be recorded at the end step of the workflow if the payment is accepted. Hence, during the transition, I don't want the information … -
When I center Navbar the text becomes squished
I would like my navbar to be centered and always be shown at the top of the screen however whenever i think I've fixed it something goes wrong this time the text text is mushed. I would like it to be strait across. Also sometimes when I try to fix it the "Home" button and the image overlap. Thank You. How it looks centered How I would like it to look, but not centered <!doctype html> <html lang="en"> <head> <title>The Benjamin Project | Home</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="/static/assets/css/animate.css"> <link rel="icon" href="/static/assets/img/favicon.ico"> <!-- site icon --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="/static/assets/script.js"></script> <style> @font-face { font-family: Panton; src:url("/static/assets/font/Panton-LightCaps.otf"); } body { margin: 0; padding: 0; background-color: #8CD28C; overflow-x: hidden; min-height:75px; line-height:75px; } .navbar { margin: 0; border-radius: 0; background-color: #8CD28C; /*bg color for tabs on navbar*/ color: #606060; /*text color for tabs on navbar*/ padding: 50px 0px 50px 0px; font-size: 2em; font-family:Panton; border: 0; animation-duration: 1.5s; } .navbar-default .navbar-nav .active a, .navbar-default .navbar-nav .active a:focus, .navbar-default .navbar-nav .active a:hover { color: #606060; /*text color for active*/ background-color: #8CD28C; /*bg color for active*/ font-weight: bold; } .selected { text-decoration-line:underline; } .navbar … -
Django Custom instanciation of model with custom form
I'm currently doing my forms for my app that works with the following three model classes: the app manages lobbies, a lobby has a many to many relationship with signatures, and a signature has a one to one relationship with users. I don't want my users to manipulate the signatures, it's just a class that stores other datas and that will execute other pieces of code later. How can I create a form that would propose all the standard lobby fields, but also a choice fields displaying users that I would use in the end to instanciate my signatures procedurally? I hope it's clear enough. Thanks in advance. -
Ansible uri call with Django JWT token
I would like to call django server with ansible: I have called: - name: Check status 200 uri: url: https://{{ rest_server }}/api/users/api-token-auth/ method: POST headers: Content-Type: "application/json" body: '{"username": "username", "password": "password"}' return_content: yes register: token and I get the token. Now I would like to use this token for the next call, but I can't figure out how this is working.... I try - name: Check that LOGIN returns a status 200 uri: url: https://{{ rest_server }}/api/users/auth/ method: POST headers: Content-Type: "application/json" Authorization: "JWT {{ token.content[token] }}" body: '{"username": "user", "password": "pass"}' return_content: yes register: webpage but I get error: "msg": "The task includes an option with an undefined variable. The error was: ansible.utils.unsafe_proxy.AnsibleUnsafeText object has no element {u'cookies': {}, u'vary': u'Accept', u'access_control_allow_headers': u'Access-Control-Allow-Origin, Content-Type, X-CSRFToken, Authorization, Access-Bw, Content-Disposition', u'access_control_allow_methods': u'GET, DELETE, POST, PUT, OPTIONS', u'access_control_allow_credentials': u'true', u'content': u'{\"token\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im1hcmtvLnphZHJhdmVjQHJlc3VsdC5zaSIsImV4cCI6MTUxNTAxNDE1OSwidXNlcl9pZCI6NCwidXNlcm5hbWUiOiJtYXJrby56YWRyYXZlY0ByZXN1bHQuc2kifQ.otlXbiuXnDJPiLrEKdMTKBgBMbvIGApBVH_aPI5mSd4\"}', 'failed': False, u'json': {u'token': u'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im1hcmtvLnphZHJhdmVjQHJlc3VsdC5zaSIsImV4cCI6MTUxNTAxNDE1OSwidXNlcl9pZCI6NCwidXNlcm5hbWUiOiJtYXJrby56YWRyYXZlY0ByZXN1bHQuc2kifQ.otlXbiuXnDJPiLrEKdMTKBgBMbvIGApBVH_aPI5mSd4'},.... What is the right way to do it? -
pgettext in jinja2 django templates
I have configured the Jinja environment with env.install_gettext_translations(translation, newstyle=True) and the jinja2.ext.i18n extension. I can only use the _(), _gettext() and ngettext() functions in my jinja2 templates. I want to use pgettext() (django docs) as well to add a context to the translatable strings. Is there an extension that does so or am I missing something? -
Ensure User Entered Integer
I am new to Django, and I recently created a system where users can look up a record based on a number. It's just a simple search. The system numbers have leading zeros, and I want the system to recognize the numbers with or without the zeros. I have been able to implement this system and I am converting the number the user specifies with the following code: def get_queryset(self): queryset = super(SearchResultsView, self).get_queryset() search_query = int(self.request.GET.get("q")) if search_query: queryset = Book.objects.filter(Q(request_number__icontains=search_query)).distinct() The code above works fine, as long as the user enters a number. If they typo and include letters, I get invalid literal for Base10. I understand the error, a letter is not an INT. I have spent most of the afternoon looking for how to prevent this error and I can't find what I'm looking for. I have tried to do something like: if search_query: try: queryset = Book.objects.filter(Q(request_number__icontains=search_query)).distinct() except ValueError: q = 0000000 return queryset But the letters are still interpreted and then I receive the invalid literal for Base10 error again. How can I prevent the letters from causing a problem with my query based on a number? I have also figured out that if …