Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django redirects on posting form using ajax
I'm trying to understand what's actually going on. I have this CreateView based class which I'm using to add new Operation: class OperationCreate(CreateView): model = Operation form_class = OperationForm success_url = reverse_lazy('manage_operations') def form_valid(self, form): (...) form.save() return JsonResponse({'result': 'success'}) def form_invalid(self, form): form.save() return JsonResponse({'result': 'error'}) After getting a form and posting it using ajax I can see following calls logged: [18/Feb/2018 22:52:54] "GET /expenses/new_operation/ HTTP/1.1" 200 1135 [18/Feb/2018 22:53:04] "POST /expenses/new_operation/ HTTP/1.1" 200 21 [18/Feb/2018 22:53:04] "GET /expenses/manage_operations/?csrfmiddlewaretoken=okXK8OwPJ9BJGQeMvSW3Y5koSeTEIXyQDBOAroI1OU8tD7GPxQxZQ37IdhdkhiKe&account=1&type=-1&category=1&date=2001-01-01&amount=2001 HTTP/1.1" 200 3842 I don't understand where did the last one came from. I know I have specified success_url which is a legacy code after previous implementation but it's not used anymore since I have redefined from_valid method. Also I don't get why this last request contains all parameters that I have posted before. Could you please explain it to me? Here is my ajax post method: function postForm(url, form_selector) { var form = $(form_selector); var csrf_token = $('input[name="csrfmiddlewaretoken"]').attr('value') form.submit(function () { $.ajax({ headers: { 'X-CSRFToken': csrf_token }, type: 'POST', url: url, data: form.serialize() }); }); }; -
How to disable Django showing decimal separator in templates?
I have a Django app, when i was writing the code on my pc, it was showing the numbers in the templates in this style: 1000 -> 1,000 (I use the use thousand separator) But when i deployed the app to my server, it shows: 1000 -> 1,000.00 but i don't what to use the numbers with the decimal separator. I tried formatting the numbers with the intcoma filter but doesn't work anyway. How i can get rid of this? -
how to retrieve specific card without using card id? stripe, django
I know we can use stripe customer id to retrieve list of cards attached to the customer id. Also, I know we can retrieve ONE specific card with the card's id....But what if I do not want to use the card id to retrieve the card. Instead I want to use exp month, year, last4. Is this possible? I thought of all_cards = stripe.Customer.retrieve(cus_id).sources.all(object=CARD) the_card = all_cards.all( exp_month=data.get(EXP_MONTH), exp_year=data.get(EXP_YEAR), last4=data.get(LAST_4) ) but it says no such parameters such as exp_month I thought of doing it in a way to loop through all the card and match the parameters which myself believes would be a bad idea if there is a better one. Does anyone have a better idea or suggestions? Thanks in advance for any advise -
How do I make a password from one `input` match another as I type?
I have this at the top of my HTML file: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> <script type="text/javascript"> var app= angular.module("app",[]); app.config(function($interpolateProvider){ $interpolateProvider.startSymbol("[[["); $interpolateProvider.endSymbol("]]]"); }); app.controller("MainCtrl",function($scope){ $scope.name= "World"; }) </script> I have two input elements. <input id="id_password1" name="password1" ng-model="pw" placeholder="Password" type="password" required=""> and <input id="id_password2" name="password2" ng-model="pw" placeholder="Confirm password" type="password" required=""> As I type my password into the first input, I'd like to fill the second with what I'm typing in the first. How do I do this? Edit: These inputs are in a form made with Django. In my forms.py, I have this. class RegisterForm(UserCreationForm): ''' Form that makes user using just email as username ''' username= forms.EmailField(label=_("Email"), widget=forms.TextInput(attrs={"placeholder":"Email", "id":"id_register_username"})) password1= forms.CharField(label=_("Password"), widget=forms.PasswordInput(attrs={"placeholder":"Password", "ng-model":"pw"})) password2= forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput(attrs={"placeholder":"Confirm password", "ng-model":"pw"})) -
How to implement Premium payments in Django
I am on the way to finish my project. I want to use a payment access. Maybe someone know how to solve it. For example the user will can decide what a plan want. The 3 plans will be available:basic,premium and pro. If the user choose the basic plan then can create for example 10 records, if premium 20 records etc. I want to use a Polish provider of payment. -
django module' object has no attribute 'vote'
I'm currently doing the tutorial on the Django website, and I've been running into this problem. command line views.py urls.py -
Ansible-playbook says file exists, and than says it doesn't exist
I am trying to debug my ansible-playbook, and figure out why an RSA key I copy onto a Docker Image fails to be authenticated when cloning a git repository onto that Docker Image. The first thing I wanted to look at is if the RSA key file I moved even exists in the Docker Image my playbook is creating. I run a couple tasks, one to see if the file exists, and than another than displays the RSA key to me. The first task that sees whether the file exists saves that result to a variable, and in that variable I can see that the file does in fact exist. When I try to print the contents of that file though, I get an error message saying that file path doesn't exist. ANSIBLE - name: Upload Deploy Private Key /home/app-user/.ssh/id_rsa copy: src=keys/keys dest="/home/app-user/.ssh/id_rsa" mode=0400 - name: Check that /home/app-user/.ssh/id_rsa exists stat: path: /home/app-user/.ssh/id_rsa register: stat_result - debug: var: stat_result - debug: msg="the value of id_rsa is {{lookup('file', '/home/app-user/.ssh/id_rsa') }}" TERMINAL docker: TASK [base : Upload Deploy Private Key /home/app-user/.ssh/id_rsa] ******** docker: Sunday 18 February 2018 13:24:36 -0600 (0:00:00.508) 0:02:20.492 ******* docker: changed: [default] docker: docker: TASK [base : Check that … -
How to define hidden field widget and set up value into modelform and save it in DB?
I have such models.py class User_information(models.Model): name = models.CharField(max_length=50) url = models.URLField() def __str__(self): return self.name And my forms.py class PostForm(ModelForm): class Meta: model = User_information fields = ['name', 'url'] labels = { 'name': _('Имя'), 'url': _('link'), } widgets = { 'name': Textarea(attrs={'cols': 80, 'rows': 3}), # 'url' : ????????????? } I need to save a current url page from hidden field of form. How can I set up hidden field and get current url of form's page and save it? -
use django template with dash application
I have set-up a dash application that works well with my django website, but I would like to have the dash application on a page that has a template. The setup I have is the usual one, that is : views.py def dispatcher(request): ''' Main function @param request: Request object ''' params = { 'data': request.body, 'method': request.method, 'content_type': request.content_type } with server.test_request_context(request.path, **params): server.preprocess_request() try: response = server.full_dispatch_request() except Exception as e: response = server.make_response(server.handle_exception(e)) return response.get_data() @login_required def dash_index(request, **kwarg): return HttpResponse(dispatcher(request)) @csrf_exempt def dash_ajax(request): return HttpResponse(dispatcher(request), content_type='application/json') and urls.py urlpatterns = [ re_path('^_dash-', views.dash_ajax), re_path('^', views.dash_index), ] The above code works fine. Now I've tried the following for embedding the page (view dash_index) within a template (called dashboard template). The template is not for formatting the app itself, but for elements that will be "around" the app, such as navbar, footer, menu etc. Try n°1 @login_required def dash_index(request, **kwarg): template_name = "dashboard_template.html" return HttpResponse(dispatcher(request),template_name) doesn't yield error, but doesn't display template. try n°2 : @login_required def dash_index(request, **kwarg): template = loader.get_template("dashboard_template.html") return HttpResponse(template.render(dispatcher(request))) I get the following error from the urls.py file AttributeError: module 'app_name.views' has no attribute 'dash_index' Try n°3 : @login_required def dash_index(request, **kwarg): return … -
Converting function based view to class based view to return JSON Response
I have a function based view which works fine with Bootstrap Modal dialog and returns the JSON Response. I am trying to implement this with CreateView but couldn't make it to work. Function Based View which works fine :- def task_create(request): form = CreateTaskForm(initial={'owner' : request.user, 'assignee' : request.user}) context = {'form': form} html_form = render_to_string('tasks/task_create_ajax.html', context, request=request) return JsonResponse({'html_form': html_form}) Attempt for Class Based View :- class CreateTaskView(LoginRequiredMixin, CreateView): form_class = CreateTaskForm def get_template_names(self): if self.request.is_ajax(): return ['tasks/task_create_ajax.html'] else: return ['tasks/createtask.html'] def get_form_kwargs(self): kwargs = super(CreateTaskView, self).get_form_kwargs() kwargs.update({'initial': {'owner' : self.request.user, 'assignee' : self.request.user}}) return kwargs def form_invalid(self, form): response = super(CreateTaskView,self).form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): response = super(CreateTaskView, self).form_valid(form) if self.request.is_ajax(): print(form.cleaned_data) data = { 'message': "Successfully submitted form data." } return JsonResponse(data) else: return response Problem :- In function based view, the html form is passed via variable html_form which I can view/debug in browser using console.dump command. When I use the class based view, my form didn't get populated. Can someone please suggest what should be the correct approach to make it work with class based view? How can I pass the JsonResponse for the form (get method) with … -
What's wrong in this python code?
def vector(sample_list): for item in sample_list: sums = 0 square = item**2 sums = square + sums magnitude = sums**0.5 return magnitude print(vector([2,3,-4])) Why this code doesn't give the correct magnitude? It gives the last value of the vector in function call. -
Transfer form together with other data using one AJAX post. Django
Very simple task. It is necessary to transfer data from the form together with other data using AJAX POST. The problem is how to extract this data later from the form, because they represent a whole line. $(function() { $('#myform').submit(function(event) { event.preventDefault(); var form=$('#myform').serialize(); var data={}; data['form']=form; data['csrfmiddlewaretoken']='{{ csrf_token }}'; data['other_data']='other_data'; $.ajax({ type: 'POST', url: '/myajaxformview', dataType: 'json', data: data, success: function (data, textStatus) { $('#output2').html(JSON.stringify(data)); }, error: function(xhr, status, e) { alert(status, e); } }); }); }); def myajaxformview(request): if request.method == 'POST': if request.is_ajax(): data = request.POST print(data) #<QueryDict: {'form': ['csrfmiddlewaretoken=VtBJ03YJZsEocJ5sxl9RqATdu38QBPgu4yPAC64JlpjOzILlF1fOQj54TotABHx9&field1=1&field2=2'], 'csrfmiddlewaretoken': ['VtBJ03YJZsEocJ5sxl9RqATdu38QBPgu4yPAC64JlpjOzILlF1fOQj54TotABHx9'], 'other_data': ['other_data']}> form=data.get('form') #csrfmiddlewaretoken=VtBJ03YJZsEocJ5sxl9RqATdu38QBPgu4yPAC64JlpjOzILlF1fOQj54TotABHx9&field1=1&field2=2 print(form) return HttpResponse(json.dumps(data)) return render(request, 'foo.html') -
Saving Django Media files on File System in Production
I am building a Django application where I have to serve some media files on server. Due to some limitations, I cannot use separate media file storage like S3 or Azure etc. What I actually do is that I need to generate an audio file on the basis of data provided by user and then play that file on browser. I delete that file after playing it. This is a research based project with no user based data and also data will be very small. Therefor I want to store media file on same server. When I run my application with DEBUG=True, data is uploaded on server and I can also access it in my web page. But when when I set DEBUG=False, I cannot access my media files stored in same server. I know the problem is that I need to deploy my media file to a separate server in production environment. But as I said, I cannot use a separate media file storage. I know that In production environment, I need to use server like Nginx and Apache when I will set path of my media file storage in nginx/apache settings and it will work. But the problem … -
Sending messages to groups in Django Channels 2
I am completely stuck in that I cannot get group messaging to work with Channels 2! I have followed all tutorials and docs that I could find, but alas I haven't found what the issue seems to be yet. What I am trying to do right now is to have one specific URL that when visited should broadcast a simple message to a group named "events". First things first, here are the relevant and current settings that I employ in Django: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [('localhost', 6379)], }, } } ASGI_APPLICATION = 'backend.routing.application' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'channels', 'channels_redis', 'backend.api' ] Next, here is my EventConsumer, extending the JsonWebsocketConsumer in a very basic way. All this does is echo back when receiving a message, which works! So, the simple send_json response arrives as it should, it is ONLY group broadcasting that does not work. class EventConsumer(JsonWebsocketConsumer): groups = ["events"] def connect(self): self.accept() def disconnect(self, close_code): print("Closed websocket with code: ", close_code) self.close() def receive_json(self, content, **kwargs): print("Received event: {}\nFrom: {}\nGroups: {}".format(content, self.channel_layer, self.groups)) self.send_json(content) def event_notification(self, event): self.send_json( { 'type': 'test', 'content': event } ) And here … -
Ansible-Playbook debug task skipping without reason
I am running an Ansible playbook to create a docker container with a Django application. I add an RSA key to the container, create directories, and try to clone the Django repository into the container. I get an authentication error, so I'm trying to debug the issue, first off seeing if the RSA key exists. When I add a debug task however, and run the playbook, it just says 'skipped', and doesn't offer any message. I'm new to Ansible, and read the documentation, but couldn't find a reason why. Ansible Tasks - name: Upload Deploy Private Key {{home_path}}/.ssh/id_rsa copy: src=keys/django-keys dest="{{home_path}}/.ssh/id_rsa" mode=0400 - name: Check that key exists stat: path: {{home_path}}/.ssh/id_rsa register: stat_result - debug: var: stat_result verbosity: 3 Shell docker: TASK [base : Upload Deploy Private Key /path/.ssh/id_rsa] ******** docker: Sunday 18 February 2018 12:37:33 -0600 (0:00:00.500) 0:02:03.199 ******* docker: changed: [default] docker: TASK [base : Check that /path/.ssh/id_rsa exists] **************** docker: Sunday 18 February 2018 12:37:34 -0600 (0:00:00.861) 0:02:04.060 ******* docker: ok: [default] docker: TASK [base : debug] ******************************************************* docker: Sunday 18 February 2018 12:37:34 -0600 (0:00:00.334) 0:02:04.718 ******* docker: skipping: [default] -
Django m2m field doesn't assign to parent object in view
I've read the Django 1.11 docs on this topic and countless questions here on SO. I'm sure I'm missing something simple, but I cannot see why my problem is occurring and have fruitlessly tried endless variations to solve, so I submit it to wiser minds for consideration. (I will post the relevant code below, wherein I believe the problem lies. And will post more if necessary, but I don't want to drown this post in code in advance if it doesn't contribute...) I am implementing a tagging system for my project. I've tried the various plug-in solutions (taggit, tagulous, etc) and each for their own reason doesn't work the way I would like or doesn't play well with other parts of my project. The idea is to have a Select2 tagging field allow users to select from existing tags or create new. Existing tags can be added or removed without problem. My difficulty is in the dynamic generation and assignment of new tags. Select2 helpfully renders the manually-entered tags in the DOM differently than those picked from the database. So upon clicking submit, I have javascript collect the new tags and string them together in the value of a hidden … -
Itterate over all current sessions in django
Is it possible in django to itterate all current sessions? I want to implement a calendar where it is impossible to book a timeslot that someone else is booking. I Keep a list of timeslots id's in the session before the user proceeds to checkout. -
unable to create a attrs for fields
i am unable to add attrs for my fields. See my code as below. by adding the attrs for one one fields its working but adding for all fields its not working here my form class AddProducts(forms.ModelForm): class Meta: model = ProductsModel fields = '__all__' def __init__(self, *args, **kwargs): super(AddProducts, self).__init__(*args, **kwargs) for field in self.fields: field.widget.attrs['class'] = 'mdl-textfield__input' and my html {% extends 'home/base.html' %} {% block body %} <main class="mdl-layout__content"> <div class = "mdl-grid"> <form method="post"> {% csrf_token %} {% for field in form %} <div class="mdl-cell mdl-cell--6-col login-card-text mdl-textfield mdl-js-textfield"> {{ field }} <label class="login-card-input mdl-textfield__label" for="{{ field.name }}">{{ field.label }}</label> </div> {% endfor %} <br> <button type="submit" name="logout" class="demo_btn_color mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect">Submit</button> </form> </div> </main> {% endblock %} and my view def createProducts(request): template_name = 'home/dashboard_edit.html' form = AddProducts() if request.POST: form = AddProducts(request.POST) if form.is_valid(): form.save() # user = authenticate(username=username, password=password) # if user is not None: # if user.is_active: # login(request, user) # return redirect('home:index') # return render(request, 'home/add_user.html', {'form': form}) return redirect('home:adduser') return render(request, template_name, {'form': form}) -
Load JSON file's content to Heroku's environment variable
I am using Google Speech API in my Django web-app. I have set up a service account for it and am able to make API calls locally. I have pointed the local GOOGLE_APPLICATION_CREDENTIALS environment variable to the service account's json file which contains all the credentials. This is the snapshot of my Service Account's json file: I have tried setting heroku's GOOGLE_APPLICATION_CREDENTIALS environment variable by running $ heroku config:set GOOGLE_APPLICATION_CREDENTIALS="$(< Speech-Api-Proj.json)" $ heroku config GOOGLE_APPLICATION_CREDENTIALS: { ^^ It gets terminated at the first occurrence of " in the json file which is immediately after { and $ heroku config:set GOOGLE_APPLICATION_CREDENTIALS='$(< myProjCreds.json)' $ heroku config GOOGLE_APPLICATION_CREDENTIALS: $(< Speech-Api-Proj.json) ^^ The command gets saved into the environment variable I tried setting heroku's GOOGLE_APPLICATION_CREDENTIALS env variable to the content of service account's json file but it didn't work (because apparently the this variable's value needs to be an absolute path to the json file) . I found a method which authorizes a developer account without loading json accout rather using GOOGLE_ACCOUNT_TYPE, GOOGLE_CLIENT_EMAIL and GOOGLE_PRIVATE_KEY. Here is the GitHub discussion page for it. I want something similar (or something different) for my Django web-app and I want to avoid uploading the json file to … -
How to search with date and given time
I want to show the details when user enter a datefield and also time range like 1:00am to 3:00 am how to do this in Django using query set I have search related o this but I don't find any useful material please help me -
tests stall using docker, selenium for django app
Been struggling a bit with selenium tests through Docker. hoping for some input. If it is the first time I am starting the container, I can run a single test perfectly. Then, the process stalls on the next test with this value showing from the selenium_hub container: selenium_hub | 16:27:06.882 INFO - Got a request to create a new session: Capabilities {browserName: chrome, version: } and this showing in the terminal with Django test function running: System check identified no issues (0 silenced). Log in | Django site admin F If i try to run any tests again with the same containers without stopping / restarting them, the process stalls in the same point on the very first test. I appreciate any help. Here's my docker-compose.yml: version: '2' services: db: image: postgres django: container_name: django build: . command: python manage.py runserver 0.0.0.0:8080 volumes: - .:/code ports: - "8080:8080" depends_on: - db selenium_chrome: container_name: selenium_chrome image: selenium/node-chrome-debug volumes: - /dev/shm:/dev/shm environment: - HUB_PORT_4444_TCP_ADDR=selenium_hub - HUB_PORT_4444_TCP_PORT=4444 ports: - "5900:5900" depends_on: - selenium_hub selenium_firefox: container_name: selenium_firefox image: selenium/node-firefox-debug volumes: - /dev/shm:/dev/shm environment: - HUB_PORT_4444_TCP_ADDR=selenium_hub - HUB_PORT_4444_TCP_PORT=4444 ports: - "5901:5900" depends_on: - selenium_hub here's my tests: from django.test import TestCase, tag from selenium import … -
delete is not allowed in django rest
I am writing a restful web service for an Android app by django rest framework . before when I writed a model ( ex:profile) and a view with ModelViewSet and a serilazer with ModelSerializertested a json and a url with simple route for: www.example.com/profiles/ , I got a json with delete option I mean I could got : Allow: GET, POST,DELETE, HEAD, OPTIONS and know I have written a lot of codes with ModelViewSet but I can not see Delete in Allow and can not get anything of delete request , in postman I get : "detail": "Method \"DELETE\" not allowed." before I added codes for permissions and authentication but now i create a new project and without any security issues , what happened in my project ? why I can not access to Delete ? why is not allowed for me ? and how can I fix this problem . models.py: from django.db import models class User(models.Model): username = models.CharField(max_length=50 , unique=True) password = models.CharField(max_length=50) idName = models.CharField(max_length=50 , blank=True , null=True) enable = models.BooleanField(default=False) name= models.CharField(max_length=50) family = models.CharField(max_length=50) email = models.EmailField() user_image = models.ImageField(unique=True , blank=True , null=True , upload_to='user_images') birthDay = models.DateTimeField(blank=True , null=True) GcmRegisterationId = … -
how to use PUT to update a value in django
Desperate need help. How to write this?enter image description here -
how can i run this python script from javascript onClick
The problem is that we have a button that we want to use when the user clicks it, it must run a python script that will do what we implemented it. Can I please know what the mistake I did, so in future I won't be able to fall for it again. I'm trying to run a python script from java event listener or html, or anyway that I could run the script if the button is clicked js code button_pressed = document.getElementById("press-btn"); button_pressed.addEventListener("click", myFunction); function myFunction() { debugger; System.Diagnostics.Process.Started("python.exe","testAPI.py"); } HTML CODE <div class="row"> <form method="post" action="#" class="contact-form"> <div class="row"> <div class="col span-3-of-3"> <p class="center-text">-uOttaHack Hackathon project: </p> </div> <div class="col span-3-of-3"> <br> <p class="center-text">Creating described video for real life using Google Vision API and Raspberry Pi.</p> </div> </div> <div class="row"> <div class="col span-1-of-3"> </div> <div class="col span-2-of-3"> </div> </div> <div class="row"> <div class="col span-1-of-3"> </div> <div class="col span-2-of-3"> <input type ="button" class="btn-press" id ="press-btn" name="btn" value="Scan me"> </div> </div> DJANGO(PYTHON) export DJANGO_SETTINGS_MODULE='config.settings.production' export DJANGO_SECRET_KEY='<secret key goes here>' export DJANGO_ALLOWED_HOSTS='<www.your-domain.com>' export DJANGO_ADMIN_URL='<not admin/>' export DJANGO_MAILGUN_API_KEY='<mailgun key>' export DJANGO_MAILGUN_SERVER_NAME='<mailgun server name>' export MAILGUN_SENDER_DOMAIN='<mailgun sender domain export DJANGO_AWS_ACCESS_KEY_ID= export DJANGO_AWS_SECRET_ACCESS_KEY= export DJANGO_AWS_STORAGE_BUCKET_NAME= export DATABASE_URL='<see below>' -
Django Framework : Attribute error 'Settings' object has no attribute 'TEMPLATE_DIRS'
I am a newbie in Django framework, unable to understand this issue. While running ./runtests.py command it gives attribute error message. Here is the error detail. ./runtests.py Testing against Django installed in '/usr/local/lib/python2.7/dist-packages/django' Traceback (most recent call last): File "./runtests.py", line 440, in <module> options.debug_sql) File "./runtests.py", line 239, in django_tests state = setup(verbosity, test_labels) File "./runtests.py", line 111, in setup 'TEMPLATE_DIRS': settings.TEMPLATE_DIRS, File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 57, in __getattr__ val = getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'TEMPLATE_DIRS'