Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: too many values to unpack (expected 2)... how to fix that?
Here is my View.py def rule_assignment(request): # print("check") rules = list(assignmentRule.objects.values_list('id','Developer','Epic')) # print(rules) for rule in rules: assignmentRuleItems = list(assignmentRuleItem.objects.values_list('Jira_Column', 'RelationalOperators', 'Jira_Value').filter(Rule_No = rule[0])) # print(assignmentRuleItems) AR = len(assignmentRuleItems) # print(AR) myString = '' for i in range(AR): if myString == "": myString = myString +assignmentRuleItems[i][0]+ " " + assignmentRuleItems[i][1]+ " "+"'" +assignmentRuleItems[i][2] + "'" else: myString = myString+","+ " " +assignmentRuleItems[i][0]+ " " + assignmentRuleItems[i][1]+ " "+"'" +assignmentRuleItems[i][2] + "'" print(myString) js = jira.objects.filter(myString) print(js) return HttpResponseRedirect('/DependencyManagement') js = jira.objects.filter(myString) in this line i'm getting too many values to unpack (expected 2) this error. here myString value is Epic = 'DevOps', Sprint = 'DX4C Sprint 18' for that myString value i'm getting error but when I type that output manually instead of myString variable that time i'm not getting any error. can some help me to solve this? -
Cannot assign, must be an instance -- Django
Iam using Django and Rest Framework to POST data into an API, but while assigning a Form data of a foreign key using another table's primary key it throws an error "Cannot assign "'12345'": "ResourceSection.resourceId" must be a "MasterResource" instance." Note: 12345 does exist (created it for testing purpose) Models.py class MasterResource(models.Model): route_name = models.CharField(max_length=100) resourceId = models.CharField(primary_key=True, max_length=100) class ResourceSection(models.Model): resourceId = models.ForeignKey(MasterResource, on_delete=models.CASCADE, default=1) resource_name = models.CharField(max_length=100) sectionId = models.CharField(primary_key=True, max_length=100) Views.py def create_resource_section(request): if request.method == "POST": sectionId = int(datetime.now(tz=timezone.utc).timestamp()*1000) resource_name = request.POST.get("resource_name") resourceId = request.POST.get("resourceId") try: section_object = ResourceSection( resourceId = resourceId, resource_name = resource_name, sectionId = sectionId ) section_object.save() return HttpResponse(str(sectionId) + ' Section is successfully created') except Exception as e: return HttpResponseServerError(e) Why the POST data couldnt set resourceId from MasterResource? What am I doing wrong? -
Django: resizing the height of the Forms Textarea using only the rows parameter
I'm trying to adjust the height of a Django form with the following code: class EntryForm(forms.Form): text = forms.CharField(widget=Textarea(attrs={'rows' : 10}), label="Text") The 'rows' : 10 parameter does not seem to have any effect on the height of the text box. However, I get the desired behavior when I pass the following: text = forms.CharField(widget=Textarea(attrs={'class': 'form-control col-md-10 col-lg-10','rows' : 15}), label="Text") Is it possible to resize the height of the text box using only the native rows parameter and without introducing the Bootstrap form control CSS? Thanks in advance! -
How to delete an item that is connected to a foreignkey django?
I have a problem adding a delete functionality to my simple django project which is a todoapp. The problem is when i press the delete button it redirect me to the same page but the item is not deleted. Can someone explain to me what is happening on my code? This is my code solution but still does not work. This is my views.py def index(request, id): ls = ToDoList.objects.get(id=id) p = request.POST if request.method == "POST": if p.get("save"): for item in ls.item_set.all(): item_id = str(item.id) if "clicked" == p.get("c" + item_id): item.complete = True else: item.complete = False if p.get("text" + item_id) in p: item.text = p.get("text" + item_id) if p.get("d" + item_id) == "delete": # Solution item.delete() return HttpResponseRedirect("/%i" % ls.id) item.save() elif p.get("add"): new_item = p.get("new") if new_item: ls.item_set.create(text=new_item) else: return HttpResponse("<strong>Invalid Input</strong>") return render(request, "todoapp/index.html", {"ls": ls}) models.py from django.db import models class ToDoList(models.Model): date = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=200) def __str__(self): return self.name class Item(models.Model): toDoList = models.ForeignKey(ToDoList, on_delete=models.CASCADE) text = models.CharField(max_length=500) complete = models.BooleanField(default=False) def __str__(self): return self.text index.html {% extends 'todoapp/base.html' %} {% block title %}View List{% endblock %} {% block content %} <h2>{{ls.name}}</h2> <form method="post", action="#"> {% csrf_token %} {% for item … -
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)