Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use django 3.0 ORM in a Jupyter Notebook without triggering the async context check?
Django 3.0 is adding asgi / async support and with it a guard around making synchronous requests in an async context. Concurrently, IPython just added top level async/await support, which seems to be running the whole interpreter session inside of a default event loop. Unfortunately the combination of these two great addition means that any django ORM operation in a jupyter notebook causes a SynchronousOnlyOperation exception: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. As the exception message says, it's possible to wrap each ORM call in a sync_to_async() like: images = await sync_to_async(Image.objects.all)() but it's not very convenient, especially for related fields which would usually be implicitly resolved on attribute lookup. (I tried %autoawait off magic but it didn't work, from a quick glance at the docs I'm assuming it's because ipykernels always run in an asyncio loop) So is there a way to either disable the sync in async context check in django or run an ipykernel in a synchronous context? For context: I wrote a data science package that uses django as a backend server but also exposes a jupyter based interface on top of the ORM that allows you … -
Why does collectstatic copy to wrong directory?
I thought I understood static files, collectstatic, etc. But this has my head spinning: In settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static') Then I run python manage.py collectstatic Then I see You have requested to collect static files at the destination location as specified in your settings: D:\Code\Project\staticfiles I'm pretty sure at one point I did actually use 'staticfiles'. But now I've changed it to 'static' and it still thinks the destination should be staticfiles. I've deleted the __pycache__ folder and it still doesn't work. -
django nav bar buttons dont work 4040 page not found error
i am making my first web page with django.I have a nav bar with a few buttons and I am trying to get the register button to work. but when i click it it gives me a page not found 404 error i have been going trough my code but i cant find anything wrong this is my mysite urls """mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))""" # this is mysite not main from django.conf.urls import url,include from django.contrib import admin #url('^admin/', admin.site.urls), urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('main.urls')), url(r'^tinymce/', include('tinymce.urls')), ] this is my main urls """mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: … -
How to fix "Error loading either pysqlite2 or sqlite3 modules" after running python manage.py runserver?
I'm trying to start my first project using Django. I'm using Anaconda and Python 2.7. So far I did this in Anaconda prompt: conda create -n recepti_venv (it worked) conda activate recepti_venv (it worked) pip install django (it worked) django-admin startproject projekt_upi (it worked) cd projekt_upi (it worked) python manage.py runserver ( didn't work -- Error loading either pysqlite2 or sqlite3 modules ) I tried pip install pysqlite (didn't work -- Failed building wheel for pysqlite) and conda install libsqlite3-dev (didn't work -- The following packages are not available from current channels: - libsqlite3-dev) -
Difficulty with Django populating an HTML selection dropdown with data from a SQLite database
I'm attempting to create a dropdown selection on an HTML page containing options from my database, but it keeps coming up empty without any errors or any indication as to what is wrong. I'm trying to use a trimmed down version of this solution. Below is what I have: views.py: from django.shortcuts import render from django.views.generic import TemplateView # Import TemplateView from django.http import HttpResponse from pathfinder.models import characterTable [...] class battleSimView(TemplateView): template_name = "battleSim.html" def post(request): item = characterTable.objects.all() # use filter() when you have sth to filter ;) return render_to_response ('battleSim.html', {'items':item}, context_instance = RequestContext(request),) [...] models.py: from django.db import models class characterTable(models.Model): userID = models.CharField(max_length = 32) playerName = models.CharField(max_length = 32) race = models.CharField(max_length = 32) playerClass = models.CharField(max_length = 32) strength = models.CharField(max_length = 2) dexterity = models.CharField(max_length = 2) constitution = models.CharField(max_length = 2) intelligence = models.CharField(max_length = 2) wisdom = models.CharField(max_length = 2) charisma = models.CharField(max_length = 2) def __str__(self): return (self.userID + ": " + self.playerName ) [...] form area of battleSim.html, in my templates folder [...] <form method="POST"> <select name="item_id"> {% for entry in items %} <option value="{{ entry.userID }}">{{ entry.playerName }}</option> {% endfor %} </select> </form> [...] I'm just not … -
Django datatable server side processing having problems with djang templating engine
I am having trouble with django-datatables server side processing. The server side processing works but it seems like the {% if %} {% endif %} statements wasn't being read. Here a screenshot sample when i commented out the serverside=True. but when i uncomment the serverside=True -
How to retrieve object that a different object is linked to in template? Django
I have a quiz model and a view where I'm displaying a list of all the quizzes on the page. I want to show the score that they got alongside each quiz. Currently, I have a score model that links to each quiz and the user that took the quiz. I want to do something like Score.objects.filter(user=request.user, quiz=quiz).get_percentage() to show the percentage achieved for that quiz. However this doesn't work in template code of course. def learn(request): #Quiz Screen context = { 'quizzes':Quiz.objects.all(), 'scores':Score.objects.filter(user=request.user), } return render(request, 'quiz_app/learn.html', context) {% extends "quiz_app/base.html" %} {% block content %} <a href="{% url 'quiz-create' %}">New Quiz</a> {% for quiz in quizzes %} <a id="quiz-anchor" href="{% url 'quiz-detail' quiz.id %}"> <article class="quiz-thumbnail-large"> <h2>{{ quiz.title }}</h2> <h3>{{ quiz.question_amount }} Questions</h3> <p>Score: {{ quiz.score.get_percentage }}%</p> </article> </a> {% endfor %} {% endblock content %} -
Django Most Efficient Way to Sort Models in Lists
I have a todo app that has reminders, and recently decided to add a function to allow the user to put a reminder in certain lists, such as school, work, groceries, etc. Right now I'm stuck between two options. Option 1 is to create a ReminderList model and have a foreign key to reminders and Users, which would be more work. Option 2 is to create a ReminderListItem model and have a form to create a new list (which would just be a string of the name to be added to a list of options). Then, in the view I would just pass through 'list_name': Reminder.objects.filter(parent_user=user, type_of_remind="Regular", reminder_list=list_name). Which option would be more efficient? Models.py: class Reminder(models.Model): remind_types = [('Regular', 'Regular'), ('Long Term', 'Long Term')] remind_lists = [('General','General')] title = models.CharField(max_length=100) description = models.TextField() remind_time = models.DateTimeField(blank=True) parent_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) type_of_remind = models.CharField(max_length=12, choices=remind_types, default='Regular') remind_list = models.CharField(max_length=20, choices=remind_lists, default='General') complete = models.BooleanField(default=False) -
Get the index value of the html drop-down in Django view
I am making a Django WEB APP My templates has a template called search.html, in my search.html i have a drop-down and the no of elements in the drop down is decided by the length of list which i receive by making a API call now the no of items in the list is always different and so is the length of the drop-down so i have used a for loop to show all the elements in the drop-down. search.html <div class="container"> <br> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Names </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for items in name %} <a class="dropdown-item" href="{% url 'details' %}">{{ items }}</a> {% endfor %} </div> </div> Each element in drop-down is a tag i.e it will be a link to some other page. in the same JSON received by making the API calls is the details that i want to show on the new HTML PAGE i.e, details.html Now , I want the index of the item clicked in the drop-down in my views.py so i can display the result accordingly. for example, a user clicks on the 3 rd element of the drop-down i.e, index 2 i … -
How to return data from two different tables in django?
Hi I have two models in my models.py. I need to return an json response which include data from two table. How shoul my view and serializer look like? class Device(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) device_name = models.CharField(max_length=200, null=True, blank=True ) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.device_name) class StatusActivity(models.Model): OFFLINE = 1 ONLINE = 2 STATUS = ( (OFFLINE, ('Offline')), (ONLINE, ('Online')), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) device_id = models.ForeignKey(Device, related_name='StatusActivity', on_delete=models.CASCADE) changed_to = models.PositiveSmallIntegerField(choices=STATUS) modified_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.device_id) Expected Response: { "device_id":"", "device_name":"", "changed_to":"", "modified_at":"", } -
Bad value for attribute “href” on element “a”: Illegal character in path segment
Django HTML file has issues with this error: Bad value “{% url 'login' %}” for attribute “href” on element “a”: Illegal character in path segment: “{” is not allowed. Source Code: <!DOCTYPE html> <html lang="en"> <head> <title>My django login project</title> </head> {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} {% if user.is_authenticated %} Hi {{ user.username }}! {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">login</a> {% endif %} {% endblock %} </html> -
When I set my django app setting to Debug = False I get a could not connect to server: Connection refused
I keep getting this error when I try to runserver the server on Debug = False DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'www.mysite.com'] the error says this django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? -
for ok, result in streaming_bulk (...).. Explain the python for loop structure
Anyone plz explain the line of code es_question = (q.as_elasticsearch_dict() for q in questions) for ok, result in streaming_bulk( get_client(), es_question, index = settings.ES_INDEX, raise_on_error = False ): if not ok: all_ok = False action, result = result.popitem() logger.error(FAILED_TO_LOAD_ERROR.format(result['_id'], result)) I want to know what the for loop does on es_questions and the explanation for line of code below es_question -
Passing list as a parameter in url routing in Django
I have a Business model in Django where I need to insert information from an API. However, I want to avoid the duplicates in the database. So, whenever user clicks on a specific link of business I need to check if it already exists on database and if not I have to insert it into the database and view the result. Following code is what I have done so far. def checkBusiness(request, business): try: result = Business.objects.get(checkId=business.checkId) except Business.DoesNotExist: b = Business(name=business[0]['name'], street_address=business[0]['location']['address'], city=business[0]['location']['city'], state=business[0]['location']['state'], country=business[0]['location']['country'], category=business[0]['categories']['name'], distance=business[0]['location']['distance'], checkId=business[0]['id']) b.save() result = Business.objects.get(checkId=checkId) context = { 'business': result, } return render(request, "MyDiary/checkBusiness.html", context) Here is how my routing looks like: path('checkBusiness', views.checkBusiness, name='checkBusiness'), And this is my html: {% for business in businesses %} <li> /*business is a json file for specific business detail*/ <a href="{% url 'checkBusiness' business %}" > {{ business.name }}, {{ business.location.address }}, {{ business.location.postalCode }} </a> </li> {% endfor %} -
Why the name of my <a> is not changing with the for loop?
I'm working with django and I need to create dynamically some links <a>. My code is, {% for node in Last_val_nodes %} <a href="#" class="nodeInfo" name="{{node.0}}">{{node.0}}</a> {% endfor %} The links showed are ok, if for example I have a list of 3 nodes like, ['Node X','Node A','Node P'] I can see the three perfectly. But now I want to know what link has been clicked. For this I'm using jquery, $('.nodeInfo').click(function(){ var name = $('.nodeInfo').attr("name"); alert(name); }); But when I click it always alert the first node name, in this case "Node X". Why is not writing a different name for every one? How can I know the link clicked if it is created dynamically? Thank you -
How can i use PUT method to edit Serialized data
i created an 'edit' function to edit username of user. def edit(request): if request.user.is_authenticated: data = request.POST s = UserSerializer(data=data) u = s.is_valid() if u: s.update(data) return JsonResponse( { 'message' : 'profile edited!' },status=201 ) else: return JsonResponse( { 'message' : 'you are not login!' },status=401 ) i don't know where PUT should be used and also how can i use update() . -
Cannot login/Unable to login django tenant
Background: I am developing my first multi tenant application with django. I have successfully followed the tutorial given by https://github.com/tomturner/django-tenants It was easy to create tenants, I could create user/superuser in public and tenant schemas and could login with those users in corresponding tenants at locahost:8000/admin/ and mytenant.localhost:8000/admin/ But needed a global auth for users related to multiple tenants(per domain rather than separate login for each subdomain) so I used https://github.com/Corvia/django-tenant-users I am still successful to create tenants and users (physical schemas in database as well) using following code. but issue is I am unable to access (even after success in login) admin page both at http://localhost:8000/admin and http://mytenant.localhost:8000/admin with any of created users and sadly I get no message at all public_owner = "owner@local" create_public_tenant("localhost", public_owner) public_admin = "admin@local" TenantUser.objects.create_superuser('xxx', public_admin) tenant_super_user = "admin@" + tenant_name TenantUser.objects.create_superuser('xxx', tenant_super_user) provision_tenant(tenant_name, tenant_name, tenant_super_user) More details: I tried debugging my login function of django, It successfully logins in and its 302 status code promises to redirect to /admin and it also shows that authenticated user (request.user) is superuser, but does not go to admin page My Installed apps is settings.py are SHARED_APPS = ( 'django_tenants', 'django.contrib.admin', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', … -
Send data from Django to another server
I have an already existing Django app. I would like to add a system that sends data from my Django application to another Python application hosted on another server, so that the Python application receives data from the Django App in json format, possibly. So for example, i would need to create a view that every tot seconds sends the data from a DB table to this application, or when a form is hit, the data is sent to this external application. How can i do this? Is there an example for this particular matter? I don't know what tools i'd need to use to create this system, i only know that i would need to use Celery to perform asynchronous tasks, but nothing else; should i use Webhooks maybe? -
Use model_to_dict() function for non-default database instance in Django
I want to convert my model instance to dictionary but I get an error because the instance is not in my default database. The error is: --------------------------------------------------------------------------- UndefinedTable Traceback (most recent call last) ~/Documents/kangaroo/.venv/lib/python3.6/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args) 83 else: ---> 84 return self.cursor.execute(sql, params) 85 UndefinedTable: relation "etl_mortgage" does not exist LINE 1: ...e"."daily_loss", "etl_mortgage"."total_debt" FROM "etl_mortg... etl is the name of my django app. The non-default database models were inserted by python manage.py inspectdb --database 'db' and were copied to a separated file. By the way, I got my instance from the database by using using('non-default-database') successfully. -
How to send an image from dir in django
I want to add a url for favicon like /favicon.ico. My image is at static/graphics/images/favicon.ico. I don't want to redirect. I tried:- from django.contrib import admin from django.urls import path, include from search import views from django.views.generic.base import RedirectView faviconI=RedirectView.as_view(url='/static/gr/favicon.ico') urlpatterns = [ path('', views.Page, name='Home'), path('favicon.ico/', faviconI, name="favicon") ] But the code gave a redirect. I want to load image from dir without redirecting. -
change forms.py widget dynamically with user input from dropdown field in Django
I am trying to make a coding webapp in which users can write choose language and write the code.For it I am using ace editor.Ace editor requires the "mode" variable to know the language and provide syntax highlighting. So,I have made a dropdown and I want to set the value of "mode" as the value of the dropdown field.e.g. If the users choose C++ I want mode="c++".I have the following code but I can't think of how to do it. forms.py from django_ace import AceWidget class notepadModelForm(forms.ModelForm): Your_code = forms.CharField(widget=AceWidget(mode='python', theme='clouds')) class Meta: model=notepadForm fields=['Title','Your_code','Separator'] models.py class notepadForm(models.Model): CHOICES=[('python','Python'),('Cplusplus','C++'),('c','C')] Title=models.CharField(max_length=120,null=False,blank=False) Separator=models.CharField(choices=CHOICES,max_length=10,default=";") Your_code=models.TextField(null=True,blank=True) I have searched for it and found some examples to dynamically add fields but modifying the widget I didn't found thats why I asked it here. -
I want to view the data by using join in django rest api
I want view the user saved category like below mentioned response by using django rest api Models.py class user(models.Model): user = models.CharField(max_length=255,unique=True) description = models.CharField(max_length=255, null=True, blank=True) class Category(models.Model): category = models.CharField(max_length=31, unique=True) image = ImageField(upload_to='category/%Y/%m/%d/', null=True, blank=True) sort_order = models.IntegerField(default=0) class savedcategory(models.Model): user = models.ForeignKey(User) category = models.ForeignKey(Category) I want a response likethis, { "user": "abc", "response":[{ "category": "red" }, { "category": "blue" } ]} } -
User information in a model post_save email
I have a model into I send an email each time this model is edited, with post_save, nice! I can recover fields from my model to display them in the email, good. But I would display information about the user connected, logged (username...). I tried some syntaxes, without success, please can you help me? In model.py, at the end of my model related: @receiver(post_save, sender=User) def save(self, **kwargs): text = 'Hello\n%s %s has just been edited.' % (self.first_name, self.last_name) my_from = 'webmaster@hg-map.fr' my_subject = 'Prospect Edit (from test instance, home)' email = EmailMessage(my_subject, text, my_from, to=['xxx@xxx.fr']) email.send() -
Python getting 'elementwise comparison failed' warning when trying to filter dataframe in Django views
I am trying filter some data from the inputs I got from POST data. I have a dataframe data that contains information. views.py def xpage(request): if request.method == 'POST': form = regFrom(request.POST) if form.is_valid(): category = form.cleaned_data['category'] year = form.cleaned_data['year'] month = form.cleaned_data['month'] df = data.loc[(data['category'] == category) & (data['year'] == year)] ... code continues ... But warning occurs at df: /virtualenv/lib/python3.7/site-packages/pandas/core/ops/__init__.py:1115: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison It occurs when I try to filter the data dataframe with conditions using .loc and returns an empty dataframe. When I search them myself by assigning values to category and year, the data exists. How can I solve this problem? -
How to get the name of the Foreign Key tables for a model instance in Django?
I want to get the name of the tables that are foreign key fields for my model instance. For example, I know that I can get data about my fields by using instance._meta.concrete_fields or by getting the name of fields in instance._meta.get_fields but I do not have any idea about getting the foreign keys fields table names. I wonder if you help me.