Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting Input From a Form in Django and Saving to Database
For a project I'm making a weather app where a user can type a city into a form, and an API is called (with Javascript) that returns weather info. I want to take only the name of the city that is entered into the form, and save that city name into the database in Django. I don't need to save the API info that's returned, just the city name they entered. For some reason, I can get it to either call the API correctly and it doesn't save to the database. Or I can save the city to the database, but the API doesn't get called. It just depends on which html I use, so I think the issue is in my html. My Javascript was working totally fine until I started trying to save info to the database and started using the form tag in html. Maybe there's an issue with the Django form also? I don't get any errors. I'm not sure how to write it, to both call the API and take the form input and save it ot the database. HTML that works for correctly returning Javascript API info, but doesn't save info to database: <div … -
What hosting services can I use for a Django web app using postgres?
Can I use any hosting service? I'm confused as to whether the type of database restricts the hosting services available. -
How do I decode a DRF response object's content to a Python String?
I have the following route in Django Rest Framework: from rest_framework.viewsets import ModelViewSet from rest_framework.renderers import JSONRenderer from rest_framework.response import Response class MainViewset(ModelViewSet): renderer_classes = [JSONRenderer] authentication_classes = [] permission_classes = [] def alive(self, request): return Response("API is Alive", 200) I have a Django test that calls this API route, expecting the JSON string: def test_base_route(self): c = Client() response = c.get('/budget/alive') self.assertTrue(response.status_code == 200) self.assertEqual(response.content.decode("UTF-8"), "API is Alive") However, I get the following error: def test_base_route(self): c = Client() response = c.get('/budget/alive') self.assertTrue(response.status_code == 200) > self.assertEqual(response.content.decode("UTF-8"), "API is Alive") E AssertionError: '"API is Alive"' != 'API is Alive' E - "API is Alive" E ? - - E + API is Alive I find this strange since I decoded the string. I know it's a simple thing to trim off quotation marks, but what is the right way to serialize a single string as a response and get it back in the content of a response in DRF when sending JSON? -
How to Query Django ORM for Each Data for Certain Time Interval?
I am trying to query set of data sparse across a certain interval. For example, when I query with an interval of one day for one year chart data, I'd like the result to be picked one raw per day. No two raws per day. When I query with an interval of 10 minutes for one day chart data, I'd like the result to be picked one raw per 10 minutes. If there are not enough data per interval, I'd like the next data to be as close as possible. For example, if there was data for 12:00, 12:01, 12:02, 12:03 but none at 12:10, but 12:11, I'd like to pick 12:11 and the next next data would be picked with DateTime of 12:21. Will there be any way to do this using Django ORM? -
How to assign value to Modelform field if request data doesn't contain that
I have a Model with 5 fields. I create a ModelForm on top of that model, now I intialize the form with request data containing 4 fields. The reason of 4 fields in request data is the checkbox on frontend that isn't passed using jquery FormData when unchecked. Now the problem is, I want to set a default value of the 5th field at the time of form initialization if checkbox is not passed in request data. What would be the best thing to do, set default value in ModelForm or Form or use default value from Model or I can set the value of a specific field. Sugesstions are welcome. TIA. -
Django smart_str writer.writerow
How can I handle Nonetype in smart_str writer.writerow?, this is how i export data to excel, I used smart_str response = HttpResponse(content_type='text/csv') # decide the file name response['Content-Disposition'] = 'attachment; filename="StudentRecord.csv"' writer = csv.writer(response, csv.excel) response.write(u'\ufeff'.encode('utf8')) # write the headers writer.writerow([ smart_str(u"Birthday"), smart_str(u"Citizenship"), // some data are Nonetype smart_str(u"Religion"), ]) reports = StudentsEnrollmentRecord.objects.filter(School_Year=yearid).order_by('Education_Levels','-Date_Time') print(reports) for report in reports: writer.writerow([ smart_str(report.id), smart_str(report.Student_Users.Birthday), smart_str(report.Student_Users.Citizenship), // some data are Nonetype smart_str(report.Student_Users.Religions), -
Django set_cookie is not working on Safari
setcookie server: Django client : React When I set cookies at my server as an response, It works well in Chrome, Edge but not is Safari. According to the samesite policy in Safari, I put "samesite=none, secure=True" at the header of the response and CSRF_COOKIE_SAMESITE = None SESSION_COOKIE_SAMESITE = None at the settings.py How can I solve this problem? -
html pages come scattered betwehten pages when i print them with html2pdf library in javascript
html2pdf is printing a pdf but the write is choppy between pages how to solve? html2pdf is printing a pdf but the write is choppy between pages how to solve? html2pdf is printing a pdf but the write is choppy between pages how to solve? html2pdf is printing a pdf but the write is choppy between pages how to solve? <script> window.onload = function () { document.getElementById("download") .addEventListener("click", () => { const invoice = this.document.getElementById("invoice"); console.log(invoice); console.log(window); var opt = { margin: 1, filename: 'myfile.pdf', image: { type: 'png', quality: 0.98 }, html2canvas: { scale: 2 }, jsPDF: { unit: 'pt', format: 'a4', orientation: 'landscape' ,dimension:\[205, 155\] } // p\init : pt unit: 'in', format: 'letter', orientation: 'landscape' }; html2pdf().from(invoice).set(opt).save(); }) } </script> ] -
Django form: Form iss validated but does not populate database
I am banging my head on the wall for a while now and can't find out the key to the error I must be making. I have a modelform in templates that does not output any error, it redirects normally, but nothing makes it through the database. I reviewed a ton of posts about similar issues here but nothing seem to solve my problem. Here is what my code look like: models.py class Sales(models.Model): SaleID = models.AutoField(max_length=100, primary_key=True) SaleProductName= models.ForeignKey(Products, related_name='products_catalogue', on_delete=models.CASCADE, blank=True, null=True) SalePartnersName = models.ForeignKey(Partners, related_name='partner_name', on_delete=models.CASCADE, blank=True, null=True) SalePartnerBusinessName = models.CharField(max_length=100,default="NA") SaleQuantity = models.FloatField(max_length=100,default="NA") SaleUnit = models.CharField(max_length=100,default="NA") SaleNetAmount = models.FloatField(max_length=100) SalesBroker = models.CharField(max_length=100,default="Not Involved") SalePartnerCommission = models.FloatField(max_length=100) SaleDate = models.DateField(default=datetime.date.today) SaleStatus = models.CharField(max_length=100,default="Ongoing") views.py def RecordNewDealView(request): if request.method == 'POST': form = RecordNewDealForm(request.POST) if form.is_valid(): form.save() return redirect('my_deals.html') else: form = RecordNewDealForm() context = {'form': form,} return render(request, 'record_new_deal.html', context) forms.py class RecordNewDealForm(forms.ModelForm): SaleID = forms.CharField(label='Sale ID') SaleStatus = forms.CharField(widget=forms.Select(choices=SALE_STATUS_CHOICES), label='Status') SalesBroker = forms.CharField(widget=forms.Select(choices=CHOICES_OF_BROKERS), label='Broker') SaleProductName = forms.ModelChoiceField(queryset=Products.objects.all(),label='Product Name') SalePartnersName = forms.ModelChoiceField(queryset=Partners.objects.all(), label='Contact') SaleUnit = forms.CharField(widget=forms.Select(choices=CHOICE_OF_UNITS), label='Unit') SalePartnerBusinessName = forms.CharField(label='Customer Name') SaleQuantity = forms.FloatField(label='Quantity') SaleNetAmount = forms.FloatField(label='Net Amount') SaleDate = forms.CharField(label="Date Created") SalePartnerCommission = forms.CharField(label="Commission") class Meta: model = Sales fields = ("SaleID", "SaleProductName", "SalePartnerBusinessName", "SaleQuantity", "SaleUnit","SaleNetAmount", … -
no se como solucionarlo 'QuerySet' object has no attribute '_meta' me devuelve ese error cuando intento hacer un post a esa tabla
hola tengo un problema con mi cpdigo, estoy viendo un tutorial y segui todos los pasos, pero no me estaria funcionando el metodo post, funciona bien el get, recibo los datos de dos directores que agregue por medio del admin. abajo les dejo el codigo, soy principiante, me gustaria recibir ayuda models.py from django.db import models # Create your models here. class Director(models.Model): nombre = models.CharField(max_length=50) def __str__(self): return self.nombre serialisers.py from rest_framework import serializers from .models import (Director, Pelicula) #selializadores class DirectorSerializer(serializers.ModelSerializer): #serializador del director class Meta(): model = Director fields = '__all__' views.py from django.shortcuts import render from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from .models import (Director, Pelicula,) from .serializers import(DirectorSerializer, PeliculaConDatosDelDirectorAsociadosSerializer, PeliculaSerializer,) # Create your views here. class DirectorListado(APIView): # vista de todos los directores listados def get(self, request): director = Director.objects.all() serialezer = DirectorSerializer(director, many=True) return Response(serialezer.data) class DirectorBuscarPorId(APIView): #vista del director buscado por id def get(self, request, pk): director = Director.objects.filter(id=pk) serializer = DirectorSerializer(director, many=True) return Response(serializer.data) class DirectorRegistrar(APIView): #vista para registrar un director def post(self, request): director = Director.objects.all() serializer = DirectorSerializer(director, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.error) class DirectorEditar(APIView): #vista para editar al director … -
Get current user in Django not working in tests
I have a couple of views in my Django app that perform and action and record who did the action in the DB, something like: def my_view(request): # do some stuff here first current_user = MyCustomUserObject.objects.filter(django_user_id=request.user.id).first() model_i_did_something_to_above.last_modified_by = current_user model.save() And this actually works fine if I run the server and call it via postman. However, when I do a Unit test: class MyTests(TestCase): def setUp(self): self.tokens = json.loads(self.client.post(reverse('authenticate'), data={'username': 'myusername', 'password': 'abcd'}, content_type='application/json').content) def test_stuff(self): self.client.delete(reverse('nameoftheurl'), {data: 'stuff'}, content_type='application/json', **{'HTTP_AUTHORIZATION': self.tokens['access']}) And it reaches the view, it says that request.user.id is None. Why does this happen? Is there a way around this? -
How to deploy a BERT model in a chatting app?
I am looking for to build a chatting app with React/Django/Flask which could use the power of NLP to block any abusive words. I am thinking to use pre-trained BERT and then train it for my use case. After that I want to deploy the model in the chatting App such that when anyone sends a abusive message, it will auto-detect and remove the message followed by warning the user. Any ideas for how to proceed with or deploy it? -
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?