Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Struggling to connect Google Calendar to django app
I'm trying to connect to the Google Calendar API to my Django app by displaying the calendar and allowing people to select dates and then create an invitation. Is this possible? Is there any documentation on how to do integrate Google Calendar into Django? -
How to begin in the Django Framework?
i'm learning python language this year and i already know how to use lists, functions and the basic structures like repetition and control. The web development looks like a good place to start my new project so i thought about using a framework, maybe the Django can be a good option. I'd like to know if this framework is a good option for me, how i can make a environment of web development using the VScode and a easier database to integrate it. Thank you very much in advance. -
Too Many Redirects Error on Django website hosted through Heroku and a custom domain with Google Domains
I'm working on a personal project and it's the first app that I'm making with a custom domain instead of .herokuapp.com, and so I followed Heroku's guide for Google Domains forwarding. I changed the app to the hobby paid dyno level to use Heroku's SSL, and then set up the CNAME record as well as the forwarding parameters on the Google domains dashboard as detailed. As far as that documentation went that should have been all that I needed to do however... Now if I hit open app on the dashboard it works perfectly but it still goes to the .herokuapp.com extension but with HTTPS now, and if I go to the plain .com URL I get "ERR_TOO_MANY_REDIRECTS". I've been trying to troubleshoot this for some time now and I ultimately threw in the towel and came here to ask because I have no idea what tools I could use to troubleshoot the issue, whether to expect the problem/solution to be found in Django settings, Heroku configuration, or Google Domain settings. -
type object 'MODEL' has no attribute 'USERNAME_FIELD'
https://www.reddit.com/r/django/comments/obpvsm/i_dont_get_this_error_cant_find_anything_on_the SO this issue here is, a lot of the solutions just had a lot of code, and not a direct solution. -
I have issue in Django contact is not define
Contact is not define.Can anyone tell why it's undefine variable -
How to modify a form when returning it in django?
I am looking to modify a form and return that different form in django, however I have tried many different ways, all in views.py, including: Directly modifying it by doing str(form) += "modification" returning a new form by newform = str(form) + "modification" creating a different Post in models, but then I realized that wouldn't work because I only want one post All the above have generated errors such as SyntaxError: can't assign to function call, TypeError: join() argument must be str or bytes, not 'HttpResponseRedirect', AttributeError: 'str' object has no attribute 'save', and another authority error that said I can't modify a form or something like that. Here is a snippet from views.py: class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['content'] title = ['title'] # template_name = 'blog/post_new.html' success_url = '/' def form_valid(self, form): #debugging tempvar = (str(form).split('required id="id_content">'))[1].split('</textarea></td>')[0] #url r = requests.get(tempvar) tree = fromstring(r.content) title = tree.findtext('.//title') print(title) form.instance.author = self.request.user if "http://" in str(form).lower() or "https://" in str(form).lower(): if tempvar.endswith(' '): return super().form_valid(form) elif " http" in tempvar: return super().form_valid(form) elif ' ' not in tempvar: return super().form_valid(form) else: return None models.py: class Post(models.Model): content = models.TextField(max_length=1000) title = models.TextField(max_length=500, default='SOME STRING') # date_posted = … -
Opening a Django InMemoryUploadedFile leads to an I/O operation error?
I am attempting to upload a file to a bucket using Django. The file goes in from the view, is cleaned, and is then uploaded to s3 using a utility function in the model. heres the upload function: def upload_file(file_obj, object_name=None): """Upload a file to an S3 bucket :param file_obj: File to upload :param object_name: S3 object name. If not specified then file_obj is used :return: True if file was uploaded, else False """ bucket = settings.BUCKET # If S3 object_name was not specified, use file_obj if object_name is None: object_name = file_obj s3 = boto3.client('s3') try: s3.upload_fileobj(file_obj.open(), bucket, object_name) except ClientError as e: logging.error(e) return False return True the error returned is: File "/opt/profiles/profiles/core/utils.py", line 217, in upload_file s3.upload_fileobj(file_obj.open(), bucket, object_name) File "/usr/local/lib/python3.8/site-packages/django/core/files/uploadedfile.py", line 90, in open self.file.seek(0) ValueError: I/O operation on closed file. Now whats weird to me is that the error comes from file_obj.open(), whats the point of an open method that cant open a closed file? I don't want to pass the request.file straight from the view as I have in a property setter, and would like it to fire off whenever the property is changed in the model but I simply cannot figure out what … -
HTML/Bootstrap Is there anyway to display a large string with numbers as an ordered list? Working within Django
I'm building a gym workout database website with Django, and one aspect of my Workout model is instructions. Since I accepted the instructions as a text field: instructions = models.TextField() Therefore it displays all as a jumble, ie. 1. Adjust the bench to an incline of 15–30 degrees. 2. Lie back on the bench with the dumbbells, and, once in position, engage your core. 3. Press the dumbbells toward the ceiling. Your palms should be facing forward. Rotate your shoulders outward to engage your lats. Your upper back should remain tight and stable throughout the entire set. I'm wondering if there's a way to use regex, or some bootstrap class to reformat this into an ordered list where it is separated by individual steps. -
'CarFilter' object has no attribute 'favourite'
AttributeError at / 'CarFilter' object has no attribute 'favourite' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.7 Exception Type: AttributeError Exception Value: 'CarFilter' object has no attribute 'favourite' Exception Location: C:\Users\Shahin\Desktop\myenv\1005\car\views.py, line 32, in show_all_car_page Python Executable: C:\Users\Shahin\Desktop\myenv\Scripts\python.exe Python Version: 3.9.1 Python Path: ['C:\\Users\\Shahin\\Desktop\\myenv\\1005', 'C:\\Users\\Shahin\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Shahin\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Shahin\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Shahin\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\Shahin\\Desktop\\myenv', 'C:\\Users\\Shahin\\Desktop\\myenv\\lib\\site-packages'] Server time: Thu, 01 Jul 2021 20:50:50 +0000 Traceback Switch to copy-and-paste view C:\Users\Shahin\Desktop\myenv\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\Shahin\Desktop\myenv\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\Shahin\Desktop\myenv\1005\car\views.py, line 32, in show_all_car_page if filtered_cars.favourite.filter(id=request.user.id).exists(): … ▶ Local vars My Views def show_all_car_page(request): context = { } filtered_cars = CarFilter( request.GET, queryset=Car.objects.all() ) paginated_filtered_cars = Paginator(filtered_cars.qs, 6) page_num = request.GET.get('page', 1) car_page_obj = paginated_filtered_cars.get_page(page_num) try: page = paginated_filtered_cars.page(page_num) except EmptyPage: page = paginated_filtered_cars.page(1) is_favourite = False if filtered_cars.favourite.filter(id=request.user.id).exists(): is_favourite = True context = { 'filtered_cars': filtered_cars, 'page': page, 'car_page_obj': car_page_obj, 'is_favourite': is_favourite } return render(request, 'index.html', context=context) def favourite_post(request, id): post = get_object_or_404(Car, id=id) if post.favourite.filter(id=request.user.id).exists(): post.favourite.remove(request.user) else: post.favourite.add(request.user) return HttpResponseRedirect(post.get_absolute_url()) My Models class Car(models.Model): favourite = models.ManyToManyField(User, related_name='favourite', default=None, blank=True) -
how to read my files in template, django model filefield
I created two button for my pdf files, a button to read and one to download. my download button works but I don't know how to open the file. can I do as I did with the download button or is there a special method to open the files models.py class Books(models.Model): author = models.ManyToManyField(Author) title = models.CharField(max_length=250) image = models.ImageField(upload_to='pics/cover/', default='pics/default-cover.jpg') pdf_files = models.FileField(upload_to='pdfs/books/', default='pdfs/default-pdf.pdf') def __str__(self): return self.title forms.py class BookForm(ModelForm): class Meta: model = Books fields = '__all__' settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.contrib.staticfiles.urls import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', include('book.urls')), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) detail.html <div class="row"> <a href="{{ books.pdf_files.url }}"><button class="btn btn-outline-success">Download</button></a> <a href=""><button class="btn btn-outline-primary">Read</button></a> </div> views.py def addBooks(request): form = BookForm() if request.method == 'POST': form = BookForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('allbooks') context = { 'form': form } return render(request, 'formulaire_livre.html', context) -
503 DNS Service Unavailable Error in Django when calling Google Data QnA API
I am trying to create a Django web application where a user can search for data in a simple search bar. The user input is then used to call Google's Data QnA API, where the data is received from BigQuery and translated to natural language so that the user has a readable response. However, when I attempt to call the API, I get a 503 Service Unavailable Error. When I call the API locally in my terminal, it works fine. Here is my code: views.py from django.shortcuts import render import os from google.api_core.client_options import ClientOptions from google.cloud.dataqna import AutoSuggestionServiceClient, Question, QuestionServiceClient from google.cloud import bigquery client_options = ClientOptions(api_endpoint = f"us-dataqna-googleapis.com:443") suggest_client = AutoSuggestionServiceClient(client_options = client_options) questions_client = QuestionServiceClient(client_options = client_options) bq_client = bigquery.Client() def index(request): return render(request, 'index.html') def response(request): os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "[path to .json]" project = "[project name]" location = "us" scope = f"[scope of project]" parent = questions_client.common_location_path(project, location) if request.method == "POST": title = request.POST.get("q") question = Question(scopes = [scope], query = title) question_response = questions_client.create_question(parent = parent, question = question) chosen_interpretation_index = 0 question_response = questions_client.execute_question(name = question_response.name, interpretation_index = chosen_interpretation_index) chosen_interpretation = question_response.interpretations[chosen_interpretation_index] bigquery_job = chosen_interpretation.execution_info.bigquery_job job = bq_client.get_job(bigquery_job.job_id, bigquery_job.project_id, bigquery_job.location) job_results = job.result() headers … -
Django view not redirecting after AJAX POST request
I've switched from sending data from a <form> to building a JSON string myself and sending that to the server. I was expecting that after sending a POST request to my view that the browser would render the JSON response -- basically, show me a page of the posted JSON data. That was the case when I submitting via a form POST request. What actually happens is that the browser doesn't do anything. But I can nevertheless see that the server is sending the right response to the browser. But why doesn't the page redirect to show the JSON data? javascript.js async function submit() { let response = await fetch('/cartography/', { method: 'POST', body: JSON.stringify({test: "test"}), headers: { "Content-Type": "application/json;charset=utf-8", "X-CSRFToken" : csrfToken.value, }, }) } views.py def cartography_view(request): if request.method == 'POST': request_data = json.loads(request.body) json_data = json_dumps(request_data) return JsonResponse(json_data) # <-- doesn't redirect. but why? urls.py path('cartography/', cartography_view, name = 'cartography'), home.html <button class="pushable" onclick="submit"/>submit to cartography</button> -
Convert a Queryset object to a model instance
I have two models as following: class Genre(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Book(models.Model): genre= models.ForeignKey(Genre, related_name="book", on_delete=models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name def save_book(book_list): #book_list is a list of dict: [{'name': 'xxx', 'genre': 'xxx'}, {...}] for book in book_list: book_genre = book['genre'] genre= Genre.objects.get(name=book_genre ) book = {'name': book['name'], 'genre': genre} new_book = Book(**book) new_book.save() In the code above, instead of hitting the database with each Genre.objects.get(name=book_genre ), I want to use Genre.objects.all() to get all of them at once. However, this code: def save_book(book_list): #book_list is a list of dict: [{'name': 'xxx', 'genre': 'xxx'}, {...}] genres= Genre.objects.all() for book in book_list: book_genre = book['genre'] genre= genres.filter(name=book_genre) book = {'name': book['name'], 'genre': genre} new_book = Book(**book) new_book.save() gives the error ValueError: Cannot assign "<QuerySet [Genre:]>": "Book.genre" must be a "Genre" instance. How do I convert a member of the queryset to a model instance to be assign along foreign key as above? -
Customize PointField serialization
I want to rename keys in PointField from drf_extra_fields.geo_fields import PointField E.g i want to rename key 'latitude' with 'lat' I found in github source code of PointField https://github.com/Hipo/drf-extra-fields/blob/252e681765645322113f69131e786664f815b919/drf_extra_fields/geo_fields.py and created my own class class MyPointField(PointField): """ Intended to rename fields 'longitude' -> 'lng' 'latitude' -> 'lat' """ def to_representation(self, value): """ Transform POINT object to json. """ if value is None: return value if isinstance(value, GEOSGeometry): value = { "lat": value.y, "lng": value.x } if self.str_points: value['lng'] = smart_str(value.pop('lng')) value['lat'] = smart_str(value.pop('lat')) return value I am using this field in serializers.py class ConstructionSerializer(serializers.ModelSerializer): coordinates = MyPointField() But I have an error "coordinates": [ "Enter a valid location." ] How can I fix the error? -
having problem in mapping my geojson data on html page using Django
how can I show my shape files- polygons on my website? I want to show my polygons on map but I cannot find the way. what should I do? Could you Please help me? Thanks These are my codes : my polygons/view.py( I want to show the "master_plan_dataset" on map): from django.http import HttpResponse from django.shortcuts import render from django.views.generic import TemplateView from django.core import serializers from .models import master_plan from djgeojson.views import GeoJSONLayerView class HomepageView(TemplateView): template_name = "index1.html" def master_plan_dataset(request): master_plans = serializers.serialize('geojson', master_plan.objects.all()) return render(request, 'layers.html', {'master_plans': master_plans}) my polygons/urls.py: from django.conf.urls import include, url from djgeojson import views from . import views urlpatterns = [ url(r'^$', views.HomepageView.as_view(), name='home'), url(r'^master_plan_dataset/$', views.master_plan_dataset, name='master_plan') ] my polygons/models.py: class master_plan(models.Model): id = models.IntegerField(primary_key=True) Landuse = models.CharField(max_length=100) Shape_Area = models.FloatField(null=False) Name_per = models.CharField(max_length=100, default=None) geom = models.MultiPolygonField(srid=4326) def __str__(self): return self.Name_per def __unicode__(self): return self.Name_per class Meta: verbose_name_plural = 'master_plan' and also my Html template => layers.html: <!DOCTYPE html> <html lang="en"> {%load static%} {%load leaflet_tags%} <head> {%leaflet_js%} {%leaflet_css%} <meta charset="UTF-8"> <title>homepage</title> <style type="text/css"> #gis {width:80%;height:500px;} </style> <script type="text/javascript" src="{% static 'dist/leaflet.ajax.js' %}"> </script> </head> <body> <h3> THE WEB SPATIAL DATABASE </h3> <br> <div> <script type = "text/javascript"> function display_layers(map, options) { var … -
Traefik and Django on a Subpath
Following setup I want to achieve inside Docker with Traefik and Django: http://domain/app1 http://domain/app2 My docker-compose.yml contains the following labels for the containers: traefik.http.routers.app1.rule=Host(my.host.de) && PathPrefix(/app1) traefik.http.routers.app1.middlewares=app1 traefik.http.middlewares.app1.headers.customresponseheaders.SCRIPT_NAME=/app1 I did the same for app2. In the settings.py of both apps I set: FORCE_SCRIPT_NAME = env('FORCE_SCRIPT_NAME', default=None) which then should get resolved via the ENV File where I have FORCE_SCRIPT_NAME=/app1. On Django side I always get a 404 with the message that this path does not exist and I should choose from an existing one. Django recognizes the URL as http://my.host.de/app1 and tells me The current path, app1, didn't match any of these. -
Sending a text + HTML email with a calendar ICS attachment in Django or Python
I've been searching for a library or at least functional snippet of code that lets me send an e-mail from Django (or at least in Python) with text content, HTML content, and an ICS calendar attachment that is recognized by every major e-mail client. For my particular use case it's enough if the user is offered an 'add to calendar' button. I feel like this should be a solved problem by now, but I'm only finding answers that refer to libraries that aren't being maintained or that are outdated or incomplete in some other way. I've tested a couple of snippets that will attach an ICS file, but G-mail doesn't give me the option of adding it to the calendar like it usually does. Is there a ready made solution that I'm missing? -
face detection using Django, Python, OpenCV
i want to run the camera on the browser and to use the device's camera to be able to access the attendance for many students from my pc .. but openCV using the main device camera so when i try to run share it with other pc it opens my camera not the one who using it -
How do I add a search TextField in Django?
I am using Django as my WebFramework. I have a Database that we want to search through. To enable a search with auto-completion we use ElasticSearch as library. There we have a method that takes a string as input and returns a list of relevant similar strings. Now we want to add a TextField on our website that displays these suggestions. As soon as the user enters a character into the textfield the function mentioned above should be called and the strings that come as return parameter should be displayed. The input should be updated after each additional character entered. In the following I have a small graphic to better illustrate my desired behavior. Is there a nice way to implement such a thing in django? If it doesn't work with django I would be happy if you steer me in the right direction which tools etc. I have to use. -
Deploy web application that has a .data-00000-of-00001
I have a django project that is basically a API for a chatbot, the chatbot uses tensorflow and it uses a extremely large file that ends in .data-00000-of-00001. I can not upload it to github because it is really big. Anyone knows how can I deploy my web application with this kind of file? -
django orm multiple filter on same many to many field
class Book(models.Model): title = models.CharField(max_length=50) authors = models.ManyToManyField(Author) class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) Suppose I want to get books having atleast two author's whose first names are Test and Tester.So I will proceed with Book.objects.filter(first_name='Test').filter(first_name='Tester') What if I have multiple first name(long list) to check,apart from running a for loop and rawsqlquery are there other options? queryset = Book,objects.all() for i in ['test','tester']: queryset = queryset.filter(first_name=i) -
Callback URL mismatch. Django.Auth0
enter image description here enter image description here enter image description here Please,solve it -
Is there python library or way to read text and image at once from database such as excel and sql? [closed]
For example, my database table looks like: Name Image tiger -
Data changing when multiple users are logged in
I'm making a Django app with Discord OAuth2 so users can log in. When 2 users log in, the data appears on both screens. So if you log in, it'll show your data but if you reload the page, it'll show another user's data. Does anyone know why this happens? Urls.py from django.urls import path from home import views urlpatterns = [ path('', views.main, name='home'), path('/logout', views.discord_logout, name="logout"), path('/settings', views.guild_dashboard, name='guild_dashboard'), path('/settings/edit', views.edit, name='edit'), path('/session_expired', views.session_expired, name='session_expired'), path('/authorize/user', views.main, name='get_authenticated_user'), path('/oauth2/login', views.discord_login, name='oauth2_login'), path('/oauth2/login/redirect', views.discord_login_redirect, name='discord_login_redirect'), ] Views.py from django.shortcuts import render from django.http import HttpResponse, HttpRequest, JsonResponse, HttpResponseRedirect from django.shortcuts import redirect from django.contrib.auth import authenticate, login, logout import requests from django.contrib.auth.models import User from home.auth import DiscordAuthenticationBackend from django.contrib.auth.decorators import login_required from .forms import Prefix import psycopg2 import aiohttp import matplotlib.pyplot as plt import numpy as np import time client_id = "client_id" @login_required(login_url="app/oauth2/login") def main(request: HttpRequest): username = user['username'] guild = [guild for guild in guilds if int(guild["permissions"]) & 0x00000020 == 32] try: connection = connection except: print("ERROR: unable to connect to the database") db = connection.cursor() query = db.execute("select server_count from info") servers = db.fetchone() servers = servers[0] query = db.execute("select user_count from info") users = db.fetchone() … -
Django cannot login with email
I'm trying to login with the email instead of the username. I don't know what I did wrong here. I filtered the DB from the Player instance in models.py which uses AbstractUser. import requests from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt from .forms import PlayerCreationForm from .models import Player # REGISTER VIEW def register_view(request): if request.method != 'POST': form = PlayerCreationForm() else: form = PlayerCreationForm(request.POST) if form.is_valid(): form.save() requests.post('http://127.0.0.1:5000/credentials', json={'email': form.cleaned_data['email'], 'username': form.cleaned_data['username'], 'password': form.cleaned_data['password2']}) return redirect('/login') context = {'form': form} return render(request, "register.html", context) # LOGIN VIEW def login_view(request): if request.user.is_authenticated: return redirect('/') if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') user = Player.objects.filter(email=email, password=password) if user is not None: login(request, user) return redirect('/') else: messages.info(request, 'Incorrect email or password') return render(request, 'login.html') # LOGOUT VIEW def logout_view(request): logout(request) return redirect('/') # HOMEVIEW def home_view(request): return render(request, "base.html") I was given the error of Internal Server Error: /login/ Traceback (most recent call last): File "/home/stevek/.local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/stevek/.local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/stevek/Projects/Python/CRAFTMINE/web/accounts/views.py", line 39, …