Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django HTML for loop not showing corresponding values
I am using a for loop in an HTML Template, it recognizes the fact that they are there but it does not show them in the page like it should. my views: person = [] x = people.objects.filter(deal='q') for person in x: print(person.name) if person.paid_status == True: person.append(lender) return render(request, '.html', {'person': person}) my template: <div> {% if person %} There are {{ person|length }} persons. {% for p in person %} <p> {{ p.name }} </p> {% endfor %} {% else %} <p> As of now no persons have appeared. </p> {% endif %} </div> in the console it prints the persons name correctly so I am confused why it does not work in the HTML All I see is that there are 2 persons(which is correct) but then it does not list them. Thanks in advance. -
How do you output full S3 URI in Graphene in Django?
I am using graphene-python with django and storing my media files on S3 with django-storages. I am failing to properly return a Query with a full URI representation for the ImageField. How can this be achieved? Current output: { "data": { "teamScores": { "edges": [ { "node": { "team": { "img": "uploaded_images/15d979149acc474d90330e65f5461ad1.jpg", "name": "Cool Name" }, "score": 30 } } ] } } } Desired output: { "data": { "teamScores": { "edges": [ { "node": { "team": { "img": "https://my-team-score-test.s3.amazonaws.com/uploaded_images/15d979149acc474d90330e65f5461ad1.jpg", "name": "Cool Name" }, "score": 30 } } ] } } } -
ValueError when db settings altered in settings.py Django documentation
Hi iam following Django documenatation,I have installed Django 1.8 and python 2.7.12,I want to connect to oracle 11g database,For this I have altered settings.py file in mysite folder like this for DATABASE information DATABASES = { 'default': { 'ENGINE' : 'django.db.backends.oracle', 'NAME' : 'XE', 'USER' : 'chandan', 'PASSWORD' : 'root', 'HOST' : 'localhost', } } Iam getting below error when i run python manage.py runserver and python manage.py migrate from .utils import InsertIdVar, Oracle_datetime, convert_unicode File "C:\PYTHON27\lib\site-packages\django\db\backends\oracle\utils.py", line 10, in <module> (int(Database.version.split('.', 2)[1]) >= 1 or ValueError: invalid literal for int() with base 10: '0rc1' Do i have to alter my DATABASE part in settings.py or what needs to be done? -
how to filter the model where 2 fields are attributed to the user?
How to filter the model where 2 fields are attributed to the user, where in these 2 fields you can be, how to filter 1 by calling and output all in one variable. models.py class Conversation(models.Model): my = models.ForeignKey(UserProfile, related_name='My') friend = models.ForeignKey(UserProfile, related_name='Friend') short_message = models.ForeignKey("Message", related_name="Short_Message") timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) I can be in these 2 fields, but how to pull all 1 at a time, that is, there is a model where I write messages and where I to output through one... I need to know if such a model with the field my = username and suddenly there is such a model where I will be that friend = username that is I can be in 2 fields how to pull all at once? So that there are not many cycles! -
Break Down Django Query object (Q)
After doing a query in a Django script I wrote, I was given this Q object. <Q: (AND: ('lesson_object_id__in', [322, 327, 328, 329, 330, 332, 1120, 1176]))> I want to break down that Q object so I only have the list [322, 327, 328, 329, 330, 332, 1120, 1176]. How would I go by doing that? Thanks -
Django Rest Framework organize Interactive API Docs
I'm auto-generating an API using django rest framework's interactive API doc generation but I'm coming across a little issue. I have core entities like cars and people and there's a parent entity called town. The routes to modify things look like /api/town/<town pk>/cars/<car pk>, but the way the interactive API docs render, I only see town originally It renders kind of like this town -- /api/town/<town pk>/cars/<car pk> -- /api/town/<town pk>/people/<person pk> But the view is collapsed originally, so all you see at the start is town Does anybody know if there's a way to cluster things in individual groups, like cars -- /api/town/<town pk>/cars/<car pk> people -- /api/town/<town pk>/people/<person pk> The initial view would then be cars people which I think is a lot easier to understand, and more organized Thanks! -
Tutorials on how to create a Django application that uses the Cesium JavaScript library?
I would like to create a Django application that uses the Cesium JS library - and I am unsure of where to begin. I have completed the Cesium Up and Running tutorial, yet I have no idea how to incorporate it into a Django application. I have set up Django with Postgres, Nginx, and Gunicorn on Ubuntu 16.04, and have incorporated two application projects that I found on GitHub. Are there any tutorials demonstrating how to create such an application? -
How to create drop down in Django using the list in view
How can I create a dropdown in my template using the list values present in my view. I do not want this to be present in my models.py. My views.py has generated some values which I would like to display in dropdown. Example: Say I have z=[1,2,3,4]. I would like this value to be displayed in a drop down box in the template. -
Ajax, Jquery Get or Post Django
Hello guys I'm working in a web app using python django as backend, and all is working fine, nowadays I have worked only with forms and sometimes with get or post option, yesterday I was trying to get info though ajax without forms, but I realized I only can use it with "get" option instead of post, Am I right? -
How to perform sql operations betterly in django?
Building an analysis app using django + postgres. Where to perform large and complex sql operations. How to optimize for faster calculations. Perform sql operation at client or Server side? -
I am trying to make login with facebook in local server in django. I have follow the process but while login the page showing below statement
Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings. Please give solution how to resolve this exception -
How to use checkboxes in Django Admin for a ManyToMany field through a intermediate table
I'll make a quick resume so you can understand better the structure: The Cars can be driven by different drivers and these drivers could have won trophies. Trophies must be associated to the driver and to the car he used. class CarDriver(models.Model): driver = models.ForeignKey('Driver', null=False) car = models.ForeignKey('Car', null=False) trophies = models.ManyToManyField('Trophy', blank=True) class Driver(models.Model): name = models.CharField(max_length=255) class Car(models.Model): name = models.CharField(max_length=255) drivers = models.ManyToManyField(Driver, blank=True, through=CarDriver) class Trophy(models.Model): position = models.IntegerField(default=1) I want to display the model Car in Django Admin but using a list of checkboxes to select the drivers, so the driver selection will be way faster than using inlines: class CardDriverInline(admin.TabularInline): model = CarDriver class CarAdmin(admin.ModelAdmin): inlines = [ CardDriverInline, ] admin.site.register(Car, CarAdmin) So is there a way to use checkboxes for multiple driver selection? -
Cannot establish connection to sql-server using pyodbc on Windows 10
Getting this error when trying to run development server on django. django.db.utils.Error: ('08001', '[08001] [Microsoft][SQL Server Native Client 11.0]Named Pipes Provider: Could not open a connection to SQL Server [53]. (53) (SQLDriverConnect)') Here is my settings.py databases DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'mydata', 'USER': 'user@mydata', 'PASSWORD': '**password**', 'HOST': 'mydata.database.windows.net', 'PORT':'**port**', 'OPTIONS': { 'driver': 'SQL Server Native Client 11.0', 'host_is_server': True, 'MultipleActiveResultSets': False, 'Encrypt': True, 'TrustServerCertificate': False, 'Connection Timeout': 30, 'Persist Security Info': False, }, }, } I have django-pyodbc and django-pyodbc-azure installed. Using django version 1.11. Any help would be awesome! Thank you. -
how to mail a file(.csv) using django?
I am getting following error. I checked out all the solutions on stackoverflow but i am not getting desired result.I have also checked django official documents. IOError at /: [Errno 22] invalid mode ('rb') or filename: '"C:\Users\Mohit\Desktop\alpha_machine\user_21abc420-20e8-4fff-bcab-13b647cf6201\finalResult.csv"' Here is my views.py: from django.conf import settings from django.core.mail import send_mail from django.shortcuts import render from .forms import filenameForm import os import shutil from django.core.mail import EmailMessage def home(request): title= 'Welcome' #if request.user.is_authenticated(): #title= "My Title %s" %(request.user) form = filenameForm(request.POST or None,request.FILES or None) context = {"title": title, "form": form} if form.is_valid(): instance=form.save(commit=False) instance.save() context={"title":"Thank You"} subject='Confirmation message' form_email=form.cleaned_data.get("email_id") form_id=form.cleaned_data.get("id1") form_file = form.cleaned_data.get("file") contact_message='Job id is:'+ str(instance.id1) from_email=settings.EMAIL_HOST_USER to_email=[from_email,instance.email_id] send_mail(subject, contact_message, from_email, to_email, fail_silently=True,) shutil.copy2(r'C:\Users\Mohit\Desktop\alpha_machine\models\decisionTree.R', r'C:\Users\Mohit\Desktop\alpha_machine\user_'+str(instance.id1)) shutil.copy2(r'C:\Users\Mohit\Desktop\alpha_machine\models\linearModel.R', r'C:\Users\Mohit\Desktop\alpha_machine\user_' + str(instance.id1)) shutil.copy2(r'C:\Users\Mohit\Desktop\alpha_machine\models\neuralNetwork.R', r'C:\Users\Mohit\Desktop\alpha_machine\user_' + str(instance.id1)) shutil.copy2(r'C:\Users\Mohit\Desktop\alpha_machine\models\randomForest.R', r'C:\Users\Mohit\Desktop\alpha_machine\user_' + str(instance.id1)) #shutil.copy2(r'C:\Users\Mohit\Desktop\alpha_machine\models\svm.R', #r'C:\Users\Mohit\Desktop\alpha_machine\user_' + str(instance.id1)) shutil.copy2(r'C:\Users\Mohit\Desktop\alpha_machine\runAllModels.py', r'C:\Users\Mohit\Desktop\alpha_machine\user_' + str(instance.id1)) folder = r'C:\Users\Mohit\Desktop\alpha_machine\user_'+str(instance.id1) file = r'"{}\runAllModels.py"'.format(folder) os.chdir(folder) os.system('python ' + file) subject1 = 'Final file' email = EmailMessage( subject1, 'File contanins results of many models ', from_email, to_email, ) folder = r'C:\Users\Mohit\Desktop\alpha_machine\user_' + str(instance.id1) files = r'"{}\finalResult.csv"'.format(folder) email.attach_file(files) email.send() return render(request, "home.html", context) -
How do I access a local IP address from a hosted site with Django python?
I have a controller that has APIs only accessible on my local network, with a local address of, say, 10.0.1.7. When I host Django on my local network (http://127.0.0.1:8000/), I am able to successfully post to the controller APIs. However, when I host the site externally (let's call it www.djangolan.com), the post does not execute. I would like to know if there is a way to configure the settings/permissions such that when a post is made from the site www.djangolan.com, while my machine is connected to the LAN, that it is able to connect. def user_created(request): contents = {} if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): firstName = form.cleaned_data['firstName'] lastName = form.cleaned_data['lastName'] url = "http://adminname:password@10.0.1.7/api/" fullName = lastName + " , " + firstName createUserJSON = {"SetUser": {"User": [{ "Name": fullName, "Description": "", "Attribute": [ { "type": "", "Name": "FirstName", "Value": firstName }, { "type": "", "Name": "LastName", "Value": lastName } ] }] } } r = requests.post(url,json=createUserJSON) return render(request,'user_created.html',contents) -
Django - Celery with RabbitMQ: task always remains in PENDING
I have to use Celery 4.0.2 with RabbitMQ 3.6.10 to handle an async task. Then, I have followed this tutorial: https://www.codementor.io/uditagarwal/asynchronous-tasks-using-celery-with-django-du1087f5k However, I have a slight problem with my task because it's impossible to have a result. My task always remains in "PENDING" state. My question is what i have to do to get a result ? Thank you in advance for your answer. Here my code: Here my __init_.py: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app'] Here a part of my setting.py: BROKER_URL = 'amqp://guest:guest@localhost//' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' Here my celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') app = Celery('mysite', backend='amqp', broker='amqp://guest@localhost//') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. … -
asynchronous web development with django. too much technologies
I've just started with asynchronous web development (Django) and I am a little confused. There is so much technologies and I don't know what is the best choice. In my app I need rea-time comunication between server and client (I'm going to use WebSocket with Django Channels - I think this is a good option, isn't it?) But maybe asyncio lib would be better? On the second way, I need something to doing backgraound task. (sending mass emails, thumbnailing photo, etc) What I should chose? Celery? asyncio lib? New thread or procces for that? Or maybe Django Channels can doing stuff like this? Could you guys explain me when use asycio lib, whene Celery (or other tasks queue tool), and when multithreatin / multiprocessing? I am soo confused with this all techniqu. -
Find out closest date in a date list django queryset python
I have a date list (date_list) that returns these dates. I now need to find out what date is closest to another date(base_date). I am using python and django to get this data date_list = [datetime.date(2017, 6, 18), datetime.date(2018, 2, 4), datetime.date(2018, 2, 11), datetime.date(2018, 4, 23), datetime.date(2018, 6, 17)] base_date = [datetime.date(2016, 4, 7)] -
The view music.views.detail didn't return an HttpResponse object. It returned None instead
MY VIEW.PY FILE IS from django.http import Http404 from django.shortcuts import render from .models import Album def index(request): all_albums = Album.objects.all() return render(request, 'music/index.html', {'all_albums': all_albums}) def detail(request, album_id): try: album = Album.objects.get(pk=album_id) except Album.DoesNotExist: raise Http404("Album does not exist") return render(request, 'music/index.html', {'album': album})' DETAIL.HTML FILE IS {{ album }} GETTING ERROR::The view music.views.detail didn't return an HttpResponse object. It returned None instead.Any help plz? -
Changin admin email in Django
So I am currently building a project with Django and will need to change the admin email to someone higher up in my division. However I am not sure who's email that will be as they are not sure yet either. If I put my email in now (as I will need to be using it when building the app), can I change it once it is ready to be delivered? -
Setting up Django first_project - "ImportError - Did you forget to activate a virtual environment?"
I've been learning the basics of python (first language for me) over the last few months. I now want to try doing something practical and get into using Django. I'm finding the setup process extremely difficult (thank god for youtube tutorials). I've installed python, pip, django and virtualenv. I activated my first project: PS C:\Users---\Desktop\first_project> virtualenv first_project Using base prefix 'c:\users\---\anaconda3' As soon as I try to run the server: python manage.py runserver I get the ImportError - "ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?". I'm using Windows 10..any idea what the problem might be? Thanks in advance. -
Vim Color Scheme Doesn't Work for One Specific Python File
I have a Django application that contains numerous applications each of which each contain the usual Python files (models.py, views.py, test.py, etc.). I have set my Vim colorscheme to distinguished. Recently I noticed that the colorscheme doesn't take effect when I open a specific Python file in a particular directory, promotion/views.py. When I open that file, I see all my code but the color scheme isn't working. Instead I see a black background with all the fonts white. Interestingly, if I do ":colorscheme", it still says "distinguished". It would appear that some Vim configuration file is corrupted with respect to this one file. Here's why I think that: If I open any other .py file in that same promotion subdirectory or any other directory, the color scheme works. If I create a new file promotion/test.py, the color scheme works. If I rename that particular view.py file to newview.py, the color scheme works. If I delete promotion/views.py and recreate it (same path, same name), the colorscheme doesn't work nor do any of my vim-snippets snippets. Here are the pertinent lines in my .vimrc file: # $HOME/.vimrc set nocompatible filetype off set rtp+=~/.vim/bundle/Vundle.vim call vundle#begin() Plugin 'VundleVim/Vundle.vim' Plugin 'Lokaltog/vim-distinguished' " other plugins … -
How to add file to django model form with onetonefield to User
I would like to know if any one has an idea how to upload a file with django model form ,with the model class having onetoonefield=User . -
Is it possible to set the Django API so that it only responds in JSON format?
Is it possible to set the Django API so that it only responds in JSON format? I made a mistake deliberately in the example shown below to explain what I mean. I am trying to create API according to assumptions of REST. So my API should only responds in JSON and returns status, or sometimes just returns status without body. I don't want to html etc. <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Page not found at /logi3</title> <meta name="robots" content="NONE,NOARCHIVE"> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; margin-bottom:.4em; } h1 span { font-size:60%; color:#666; font-weight:normal; } table { border:none; border-collapse: collapse; width:100%; } td, th { vertical-align:top; padding:2px 3px; } th { width:12em; text-align:right; color:#666; padding-right:.5em; } #info { background:#f6f6f6; } #info ol { margin: 0.5em 4em; } #info ol li { font-family: monospace; } #summary { background: #ffc; } #explanation { background:#eee; border-bottom: 0px none; } </style> </head> <body> <div id="summary"> <h1>Page not found <span>(404)</span> </h1> <table class="meta"> <tr> <th>Request Method:</th> <td>GET</td> </tr> <tr> <th>Request URL:</th> <td>http://localhost:8000/logi3</td> </tr> … -
How django knows when 500 or related server error occurs?
I know that django sends mail to the users in the admin list but i want to know how django itself gets notified about the error i mean i am searching something like if 500 error occurs: send slack message ... i have no problem integrating with slack but don't know to get that if condition. i have read about the logging but didn't find anything relevant here are my logging settings LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(os.path.join(BASE_DIR, 'econnect-local.log')), }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, 'xhtml2pdf': { 'handlers': ['file'], 'level': 'DEBUG' }, }, } may be i am missing some stupid thing. thanks for your help.