Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting csrfmiddleware token in url
I am getting csrf token in the url after submitting my form like this. http://127.0.0.1:8000/detail/?csrfmiddlewaretoken=lqvoeSG32IcodLTFksWEU1NPQ9XCmHybwmzMKEuPzxDN1e73B0JORpAGOcGGxsjH&symbol=FLWS After making a GET request to view, the url is showing the csrf token in the url. /views.py def search(request): if(request.method=='GET'): form=searchform(request.GET) if(form.is_valid()): id=request.GET['symbol'] data=company.objects.filter(Symbol=id) form=searchform() return render(request, 'list-company.html',{"data":data,"form":form}) /urls.py from django.contrib import admin from django.urls import path from csv2db.views import Company,search urlpatterns = [ path('admin/', admin.site.urls), path('company/',Company,name='company-details'), path('detail/',search,name='search') ] form in HTML file {% block content %} <form method="get" action="{% url 'search' %}"> {% csrf_token %} {{ form.as_ul}} <button type="Submit">Submit</button> </form> -
How can I delete specific song and also edit song info from my album list without using DeleteView in python Django ? Please help me
models.py This is my view file with Album and Song Classes. class Album(models.Model): artist = models.CharField(max_length=250) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=250) album_logo = models.FileField() def __str__(self): return self.album_title + '-' + self.artist class Song(models.Model): song = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length =10) song_title = models.CharField(max_length=250) #is_favorite = models.BooleanField(default=False) def __str__(self): return self.song_title views.py This is my views file for Deleting Song def delete_songs(request, album_id): if request.method == "GET": -
Creating a dynamic query system in django
I'm trying to create a query system in django, which will ask question to the user to narrow down a database to get a specific record based on the inputs. The problem I'm having is how to make it so that the question it is asking changes. Currently the database consists of chemicals, and the question are based on a set of properties that are already stored. For example, the system should ask "What is the solublity?" or "What is the boiling point?". Any help is appreciated. -
TypeError: "Unicode-objects must be encoded before hashing" error when using AWS signing Process for Python
I'm validating my AWS keys for S3 storage for my Django project. So I'm following the official walkthrough here. I've pasted the first part (Using GET with an Authorization Header (Python)) into my AWS conf.py file (which is imported into my settings.py). However the walkthrough is in Python 2.7 and my project is running off Python 3.5. Therefore I'm getting this error: payload_hash = hashlib.sha256('').hexdigest() TypeError: Unicode-objects must be encoded before hashing Any idea how I can fix this? -
Django with nginx connection error
I'm just making webserver with django. Now, I want to publish Django by uwsgi+Nginx, So I read some documents(http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html). While following that doc, I met some errors. When I connect to mydomain.com:8000, It throws 502 Bad Gateway error. (Actually, when I worked, changed mydomain.com to real domain that I have) After error, /var/log/nginx/error.log is in below. 2018/02/20 14:56:15 [error] 7548#7548: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.30.1.254, server: mydomain.com, request: "GET / HTTP/1.1", upstream: "uwsgi://127.0.0.1:8001", host: "mydomain.com:8000" ^C This is my configure files. [project_rest.conf] upstream django { # server unix:///path/to/your/mysite/mysite.sock; # for a file socket server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000 # the domain name it will serve for server_name .mydomain.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /home/app/project_rest/media; } location /static { alias /home/app/project_rest/static; } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/app/project_rest/uwsgi_params; # the uwsgi_params file you installed } … -
want to run multiple commands with single script
I am creating a single script for setup and running whole Django project. I mentioned three commands in script. which executed one on one.... commands subprocess.run(args=['nohup', 'airflow', 'scheduler']) subprocess.run(args=['nohup', 'airflow', 'webserver']) subprocess.run(args=['python', 'manage.py', 'runserver']) I used nohup for airflow webserver and scheduler to runs on background all three command runs one by one as per requirement but the problem is when airflow scheduler runs the script stops at point. is there any command or somthing i can used to run all the commands in single script with stop points -
Pip install non-conda package returns blank in anaconda prompt
I am trying to install a django package using the Anaconda prompt. As instructed by the documentations, I use "pip install (package-name)". However, every time I use pip install, it returns nothing ( blank on the next line). I've also tried "conda install (package-name)" and it could not find the package. If this is not the best method to install django packages with anaconda, could you suggest another way? Thanks! conda: 4.3.30-py35hec795fb_0 conda-env: 2.6.0-0 pip: 8.1.2-py35_0 conda environments : root -
Creating a Django user model with groups and group admins
I'm creating django website with users and groups... I'm trying to give users an option to leave a group...or A group admin can add and more so remove a user...Just like a WhatsApp group operates...How can one achieve this?? -
Python manage.py runserver running, but site cant be reached
I recently pushed a Django application into a docker container. I SSH'd into that container using docker run -it locally, and tried to run 'python manage.py runserver'. It shows the command is running Performing system checks... System check identified no issues (0 silenced). kdlkjFebruary 20, 2018 - 04:54:28 Django version 1.11.6, using settings 'settings.base' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. But when I go to http://127.0.0.1:8000, it says the site can't be reached. -
Facing issues with HttpResponseRedirect in Django
I am creating a basic login functionality for the user.If the login is successful I am redirecting the user to my index page which I have hardcoded in HttpResponseRedirect. But once I click the login Button its saying, TypeError at /Login/ login() takes 1 positional argument but 2 were given index page in urls.py id defined as below, url(r'^$',views.index,name='index'), Below is the code for my index view and login view: def index(request): return render(request,'authentication_app/index.html') def login(request): if request.method=='POST': username=request.POST.get('name') password=request.POST.get('password') user = authenticate(username=username,password=password) if user: if user.is_active: login(request,user) return HttpResponseRedirect('/') else: return HttpResponse('Your Account has become Invalid') else: print('Someone tried to login with wrong credentials:{0},{1}'.format(username,password)) return HttpResponse('Username and Password mismatch.Please enter valid credentials') else: return render(request,'authentication_app/login.html',{}) -
Why i cannot start service web?
Help me with this error please. ERROR: for web Cannot start service web: driver failed programming external connectivity on endpoint semestral_dj01 (335d0ad4599512f3228b4ed0bd1bfed96f54af57cff4a553d88635f80ac2e26c): Bind for 0.0.0.0:8000 failed: port is already allocated ERROR: Encountered errors while bringing up the project.enter image description here -
how do I call specific function in views.py through ajax call in javascript file?
In Django we map URLs to functions in views.py. If we do an ajax call then we need to mention url in ajax call but that will call the function mapped to that url. I want to call specific function from views.py via ajax call? What should I do so that I can call any function in views.py via AJAX call without changing url? views.py def index(request): codes=Code.objects.all()[:10] context={ 'name': 'KD', 'codes': codes } return render(request,'coding/index.html',context) def details(request): code=Code.objects.get(1) context={ 'code': code } return render(request, 'coding/details.html', context) urls.py from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('',views.index, name="index" ), path('details',views.details, name="details" ), ]; javascript <script type="text/javascript"> $(document).ready(function() { $("#tests").submit(function(event){ event.preventDefault(); $.ajax({ type:"POST", url:"/details/", // what changes should be done so that I can call other function in views.py? data: { 'video': $('#tests').val() }, success: function(){ $('#message').html("<h2>Code Submitted!</h2>") } }); return false; }); }); </script> -
Creating new model in Django with POST data from Python requests
I'm trying to take information from a POST request made from Python requests and add it to my model: def message(request): if request.method == 'POST': form = InputInfoForm(request.POST) #form models make validation easy if form.is_valid(): InputInfo.name = request.POST.get('name') InputInfo.conversation_id = request.POST.get('conversation_id') InputInfo.message_body = request.POST.get('message_body') return HttpResponse(status=200) return HttpResponse(status=200) Here's the request post_data = {'name': 'charles', 'conversation_id': '3', 'message_body': 'Ada Challenge'} r = requests.post('http://127.0.0.1:8000/message/', data=post_data) I'm not sure if I'm handling the requests right in the view -
Django Celery receiving and accepting tasks, but not executing them
I'm running a Django 1.11 server on Digital Ocean running Ubuntu 16.04, Gunicorn, Nginx, and am trying to set up Celery tasks using Redis. The service seems to work and receive periodic tasks fine when I do: celery -A config worker -B -l debug And the tasks are received and accepted, but they don't execute. To test, I'm sending this function: @shared_task(name="sum_two_numbers") def add(x, y, **kwargs): return x + y with: add.delay(1,3) And this is the complete printout of the console that Celery is running on: -------------- celery@myproject v4.1.0 (latentcall) ---- **** ----- --- * *** * -- Linux-4.4.0-112-generic-x86_64-with-Ubuntu-16.04-xenial 2018-02-19 23:18:12 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: myproject:0x7f2cd60dc9e8 - ** ---------- .> transport: redis://127.0.0.1:6379// - ** ---------- .> results: redis://localhost:6379/ - *** --- * --- .> concurrency: 1 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . . . . sum_two_numbers [2018-02-19 23:18:12,858: INFO/MainProcess] Connected to redis://127.0.0.1:6379// [2018-02-19 23:18:12,876: INFO/MainProcess] mingle: searching for neighbors [2018-02-19 23:18:13,910: INFO/MainProcess] mingle: all alone [2018-02-19 23:18:13,924: WARNING/MainProcess] /home/user/.virtualenvs/myproject/lib/python3.5/site-packages/celery/fixups/django.py:202: UserWarning: Using settings.DEBUG leads to a memory leak, never use … -
Django gives error "Select a Valid choice" . Django Version 1.11.5
My models.py is below: from django.db import models from extensions.models import SipExtension xmpp_users = SipExtension.objects.values_list('real_name',flat=True) xmpp_users_choices = [('', 'None')] + [(real_name,real_name) for real_name in xmpp_users] class xmpp_buddy_groups(models.Model): group_name = models.CharField(max_length=30) name = models.CharField(choices=xmpp_users_choices,max_length=100) def __str__(self): return '%s %s' % (self.group_name,self.name) my forms.py is below: from django import forms from .models import xmpp_buddy_groups from extensions.models import SipExtension class xmpp_buddy_groups_form(forms.ModelForm): xmpp_users = SipExtension.objects.values_list('real_name',flat=True) xmpp_users_choices = [('', 'None')] + [(real_name,real_name) for real_name in xmpp_users] name = forms.ChoiceField(xmpp_users_choices,required=True, widget=forms.SelectMultiple()) # name = forms.ModelChoiceField(widget=forms.CheckboxSelectMultiple,queryset=SipExtension.objects.values_list('real_name',flat=True),required=True) class Meta: model = xmpp_buddy_groups fields = ['group_name'] my views.py is below: from django.shortcuts import render from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from .forms import xmpp_buddy_groups_form @login_required def index(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = xmpp_buddy_groups_form(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: #return HttpResponseRedirect('/index.html') form.save() # if a GET (or any other method) we'll create a blank form else: form = xmpp_buddy_groups_form() print(form.errors) return render(request, 'xmpp/index.html', {'form': form}) My template index.html is below {% extends … -
unable to see my anything in database pycharm
I really am at a loss here. I am using Pycharm 5.0.4 and running a virtual env with Python3 and Django 2.0.1. I am trying to get my database up and running for my project, but no matter what I do I cannot seem to get anything to show up in the database tool window drop down in Pycharm. I have 'ENGINE': 'django.db.backends.sqlite3' set in my settings.py, and in Pycharm i am going to: Create New -> Data Source -> SQlite(Xerial). I then makemigrations and migrate but nothing shows up in the database. I can even go to the project website and succesfully add/create models in the admin site. But I cannot figure out where they are or see them... It was working at one point but I deleted my database because I was getting some errors and now I am trying to recreate it. -
Return specific wagtail setting for site
Just recently migrated domains to a single site but all settings are set per site. (navbar etc) Is tehre a way in wagtail to return a specific site's settings based upon the url? I tried monkey-patching the settings function in wagtail.contrib.settings.context_processors to return SettingsProxy(site) where site is the string of the appropriate site. But, this settings object contains nothing in the template. -
NOAUTH Authentication required - deploying with Heroku (Channel 2.0.2 - Django 2.0.2 - Heroku-Redis)
I am trying to run the multichat example of Channels 2.0.2 (Django 2.0.2) @ Heroku with heroku-redis. But I'm getting NOAUTH Authentication required (btw: I am able to run locally): 2018-02-20T02:16:34.648943+00:00 app[web.1]: 10.45.77.75:32339 - - [20/Feb/2018:02:16:34] "WSCONNECTING /chat/stream/" - - 2018-02-20T02:16:34.649549+00:00 app[web.1]: 2018-02-20 02:16:34,649 DEBUG Upgraded connection ['10.45.77.75', 32339] to WebSocket 2018-02-20T02:16:34.650407+00:00 app[web.1]: 2018-02-20 02:16:34,650 DEBUG Creating tcp connection to ('ec2-34-238-60-32.compute-1.amazonaws.com', 28169) 2018-02-20T02:16:34.659050+00:00 app[web.1]: 2018-02-20 02:16:34,658 DEBUG WebSocket ['10.45.77.75', 32339] open and established 2018-02-20T02:16:34.659217+00:00 app[web.1]: 10.45.77.75:32339 - - [20/Feb/2018:02:16:34] "WSCONNECT /chat/stream/" - - 2018-02-20T02:16:34.659974+00:00 app[web.1]: 2018-02-20 02:16:34,659 DEBUG WebSocket ['10.45.77.75', 32339] accepted by application 2018-02-20T02:16:34.666248+00:00 app[web.1]: 2018-02-20 02:16:34,666 DEBUG Closed 0 connection(s) 2018-02-20T02:16:35.085802+00:00 app[web.1]: 2018-02-20 02:16:35,085 ERROR Exception inside application: NOAUTH Authentication required. 2018-02-20T02:16:35.085814+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/channels/consumer.py", line 54, in __call__ 2018-02-20T02:16:35.085816+00:00 app[web.1]: await await_many_dispatch([receive, self.channel_receive], self.dispatch) 2018-02-20T02:16:35.085818+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/channels/utils.py", line 47, in await_many_dispatch 2018-02-20T02:16:35.085820+00:00 app[web.1]: result = task.result() 2018-02-20T02:16:35.085822+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/channels_redis/core.py", line 160, in receive 2018-02-20T02:16:35.085824+00:00 app[web.1]: return await self.receive_buffer_lpop(channel) 2018-02-20T02:16:35.085826+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/channels_redis/core.py", line 222, in receive_buffer_lpop 2018-02-20T02:16:35.085828+00:00 app[web.1]: task.result() 2018-02-20T02:16:35.085829+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/channels_redis/core.py", line 173, in receive_loop 2018-02-20T02:16:35.085831+00:00 app[web.1]: real_channel, message = await self.receive_single(channel) 2018-02-20T02:16:35.085833+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/channels_redis/core.py", line 189, in receive_single 2018-02-20T02:16:35.085835+00:00 app[web.1]: pool = await self.connection(index) 2018-02-20T02:16:35.085836+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/channels_redis/core.py", line 386, in … -
Angular 2 frontend django 2 REST framework backend user auth
I'm new to Django and JavaScript, so please forgive me if this is an obvious question. What is the best way to authenticate users? I can only find posts about using this which doesn't support django 2. Thanks for your help. -
Getting a 403 error involving CSRF when trying to connect to localhost (python requests)
I'm trying to test a connection to one of my Django views using Python's requests library. When I try to make a POST request on it I receive info when viewing request.text telling me the CSRF verification failed, and that I need a CSRF token when submitting forms. I've done some more research here and tried my best with this This is my code right now: post_request = requests.session() post_request.get('http://127.0.0.1:8000/message/') csrftoken = post_request.cookies['csrftoken'] headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36'} final_request = post_request.post('http://127.0.0.1:8000/message/', headers=dict(Referer=post_request)) This is my view: def add_message(request): form = InputInfoForm(request.POST) if request.method == 'POST': return HttpResponse('hey') return HttpResponse('test') So how do I verify the CSRF token in the view using requests? -
AJAX call taking super long (2-4 secs)
I'm really stumped on an issue that I need to fix ASAP. On my website, whenever you pan the map, an ajax call is fired, doing a query in the database. The problem is, the ajax call takes somewhere between 2-10 seconds, which is unacceptable. Link to website There are about 500k records in my database. I notice that the more records I add, the slower it gets. That makes sense right, but why is it exceptionally slow and so inconsistent? I am using Digitalocean. When I check my control panel, the CPU/RAM/disk are all operating at very low levels. The AJAX call code: def filter_closed_listings(request): zoom = int(request.GET.get('zoomLevel')) minLat = request.GET.get('minLat') maxLat = request.GET.get('maxLat') minLng = request.GET.get('minLng') maxLng = request.GET.get('maxLng') sold = request.GET.get('sold') property_type = request.GET.get('pType') building_style = request.GET.get('bType') showActiveListings = request.GET.get('showActiveListings') showSoldListings = request.GET.get('showSoldListings') showEndedListings = request.GET.get('showEndedListings') bed = request.GET.get('bed') bath = request.GET.get('bath') low_price = request.GET.get('low') high_price = request.GET.get('high') includePandL = request.GET.get('includePandL') transaction_type = request.GET.get('transactionType') ended_time_difference = datetime.date.today() + datetime.timedelta(-int(sold)) # Date check print(ended_time_difference) # Initial filter with map bounds and date check data = Listing.objects.filter(la__gt=minLat).filter(la__lt=maxLat).filter(lo__gt=minLng).filter(lo__lt=maxLng) data = data.filter(transaction_type=transaction_type) # 0 is 'Any'. Therefore a filter is done if selection is not 'Any'. if not property_type == '0': … -
Django REST Framework setting to change the auto added 'Id' to 'djangoID'
I'm happy to let DRF add an 'ID' column to my model if no primary key is defined. Is there a way in settings to make this name more appropriate? eg 'ID' would actually be 'djangoID' -
Django queryset with prefetch or not?
I have such models class Category(models.Model): name = models.CharField() … class Product(models.Model): category = models.ForeignKey(Category, verbose_name=‘cat’) name = models.CharField() price = models.IntegerField() I need to create queryset which will select all products with price >= 100 grouped by categories. Afterwards I need to get count of products in each category. I did categories = Category.objects.filter(product__price__gte = 100) This queryset gave me all categories which contain product with price >= 100. But how can I get count of products in it and products themseves? Maybe I need to use a prefetch_related, but I don't know how. -
Django foreign keys are not saving properly
I have multiple foreign keys in the same model and for some reason, whenever I hit submit on the form, the last foreign key is overriding the previously entered ones. Can anyone see whats going on? models.py class Meal(models.Model): """ Three of these will be given to a study """ date = models.DateField(null=True, blank=True) start_time = models.TimeField(null=True, blank=True) stop_time = models.TimeField(null=True, blank=True) description = models.CharField(max_length=256, null=True, blank=True) class Meta: verbose_name_plural = 'Meals For Studies' def __str__(self): return "Meal Information for CRF # " + str(self.general_info.case_report_form_number) class MotionStudyInstance(models.Model): # ###############ADD MEAL INFORMATION####################### meal_one = models.ForeignKey(Meal, related_name='first_meal', on_delete=models.CASCADE, null=True, blank=True) meal_two = models.ForeignKey(Meal, related_name='second_meal', on_delete=models.CASCADE, null=True, blank=True) meal_three = models.ForeignKey(Meal, related_name='third_meal', on_delete=models.CASCADE, null=True, blank=True) class Meta: verbose_name_plural = 'Motion Studies Awaiting Validation' def __str__(self): return "CRF: #" + str(self.general_info.case_report_form_number) forms.py class MealForm(forms.ModelForm): class Meta: model = Meal views.py class MotionStudyInstanceFormView(LoginRequiredMixin, View): def post(self, request): if request.method == 'POST': form = MotionStudyInstanceForm(request.POST, request.FILES) meal_one_form = MealForm(request.POST) meal_two_form = MealForm(request.POST) meal_three_form = MealForm(request.POST) if meal_one_form.is_valid() and meal_two_form.is_valid() and meal_three_form.is_valid(): meal_one = meal_one_form.save() meal_two = meal_two_form.save() meal_three = meal_three_form.save() motion_study_instance_one = form.save(commit=False) motion_study_instance_one.meal_one = meal_one motion_study_instance_one.meal_two = meal_two motion_study_instance_one.meal_three = meal_three motion_study_instance_one.save() return redirect('data:motion-studies') else: form = MotionStudyInstanceForm() return render(request, self.template_name, {'form': form}) -
Django 1.9 No module named 'django.urls'
Trying to install pcapdb on a fresh debian install (requires django==1.9) installed via 'sudo pip3 install django==1.9' Other parts of django can be imported without issue e.g. django.conf, django.db, django.utils, etc. Output of 'pip3 list | grep -i django' Django (1.9) django-auth-ldap-ng (1.7.6) django-braces (1.12.0) django-celery (3.2.2) django-filebrowser (3.9.1) django-grappelli (2.10.2) django-hosts (3.0) django-url-tools (0.0.8) djangorestframework (3.7.7) djangorestframework-jwt (1.11.0) pip3 --version pip 9.0.1 from /usr/lib/python3/dist-packages (python 3.6) django version from interpreter import django print(django.get_version()) # 1.9 Ideas?