Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot import objects in Django test class
In a testing class, I want to get all the objects of a given type; this alwaus give an emty set: from Dictionnaire.models import Entree class Test(TestCase): def setUp(self): ... Q=Entree.objects.all() print(Q.count()) <------always get 0. Why ? -
How to handle login credentials in Django ? How can I use middleware for the same?
I need to handle login to the web page based on users. Which will be the better way to do that in Django ? How middleware can be used for the same ? -
Apply csv reader to uploaded file
I get an error when parsing an uploaded file as csv file. _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?) I know that there is already an answer to that which seem to work if you load a file from local storage. But opening a file in text mode doesn't seem to work with uploaded files. import csv def form_valid(self, form): csv_reader = csv.reader(self.request.FILES['csvfile'], delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row)}') line_count += 1 else: print(f'Data: {", ".join(row)}') line_count += 1 print(f'Processed {line_count} lines.') return super().form_valid(form) So I have to find a way to convert the uploaded file from a byte stream to a text stream. -
how to filter a django model using IN for a list that includes None
I have a view based on a model where the user can filter the items model based on the categories field using: Items.objects.filter(categories__in=[‘A’, ’B’, ‘C’]) However in come cases the categories field is NULL, and the user may would like to see the list of NULL and A categories. So I have tried: Items.objects.filter(categories__in=[None, ‘A’]) But this does not see to work and my result only shows for A,B and C This is, of course, a simplified view of the issue as the list is dynamic and there are so many other filters as well. But the principle is the same, how can include None in the list of IN operation Thanks -
test_func is not working in django project
in the contacts section in dashboard of my projects, saved contacts are only visible to author but previously they are visible to everyone because I forgot to include UserPassesTestMixin in CBV. I included but browser showed me the error named NotImplemented test_func, I also implemented test_func views.py class ContactListView(LoginRequiredMixin, UserPassesTestMixin, ListView): model = ClientContact template_name = 'site/contacts.html' context_object_name = 'contacts' ordering = ['created_at', '-updated_at'] def test_func(self): contact = self.get_object() if self.request.user == contact.author: return True return False it says again NotImplemented test_func as well as get_oject is unresolved ref in ListView I am sure I am doing something wrong but I cannot find my mistake. Please if anyone who know this, correct me! Thank you -
Why do I get this error after adding mysql to settings of django project and while running?
When I try to run the django project, I get this error: django.db.utils.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: /usr/lib64/mysql/plugin/caching_sha2_password.so: cannot open shared object file: No such file or directory") -
How to customize django default admin to send mail to the users
I want send mail(Reply) action instead of save option in django admin page.How can i send mail to the user's respective email who sends message from contact form Contact.py class Contact(models.Model): name = models.CharField(max_length=50) email = models.EmailField() phone = models.CharField(max_length=15) subject = models.CharField(max_length=100) message = models.TextField() def __str__(self): return self.subject admin.py class ContactAdmin(admin.ModelAdmin): readonly_fields =['name','email','phone','subject','message'] actions = [ 'Reply' ] admin.site.register(Contact,ContactAdmin) views.py def contact(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): contact = form.save(commit=False) contact.save() messages.success(request,'Message Sent.') else: messages.error(request,'Error in Form') else: form = ContactForm() return render(request,'shop/contact.html',{'form':form}) forms.py class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ['name','phone','email','subject','message'] -
Cant update the Cropped PDF using pypdf
I need to crop a pdf and merge it with another pdf. i can crop the pdf and save it seperately. but when i tried to merge it another pdf after cropping, the old pdf is merging.(the cropped image is not getting merged). i am using python and pypdf existing_pdf = PdfFileReader(file(path, "rb")) output = PdfFileWriter() page = existing_pdf.getPage(0) page.cropBox.lowerLeft = (287.996, 163) page.cropBox.upperRight = (0, 0) pamphlet_pdf = PdfFileReader(file("pamphlet.pdf", "rb")) page_pamplet = pamphlet_pdf.getPage(0) page_pamplet.mergePage(page) output.addPage(page_pamplet) outputStream = file("output.pdf", "wb") output.write(outputStream) outputStream.close() -
checking if data from input from react matches with any data in the backend django
im using django as my backend. I want an efficient way to check if a data from an input exist in my database. Initially im fetching the all the objects i have in my database to the fronetend then comparing it. But now the data in the database has increased and fetching all to the frontend isnt efficient. help please -
Error after running the django webapp using selenium again?
I have an app which runs on django using selenium and python. When i run the app first time it runs perfectly fine but when i refresh it and run it again then it gives me error shown below. Error is at line -> driver.get("site").I'm being driven crazy by this error.Please help me with this? urllib3.exceptions.NewConnectionError: : Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it Max retries exceeded with url: /session/1223258a26f0f75fd39b6abe973af52b/url -
What is the best way to create PDF reports on Django?
I would like to create PDF reports based on demands and automatically for every week or month etc. There are several libraries and apps that can be useful. But my page contains 4 chart(using Chart.js), 1 Svg file and 2 Datatable(filling it server-side). I need to answer these requirements; -User could export to pdf the current page. -Every week or month page should be sent to selected user with mail automatically I've been able to create PDF's using some libraries on django. But none of them satisfied me. Because most of them are not supporting javascripts. Then I've used Selenium and headless Firefox to render page on background and generate PDF but it seems headless Firefox still doesn't support native PDF generating. So my question is what should I use to generate PDF reports on demand and automatically. Should I do it with seperate technologies or is there a way to create them -
How to assign every PointField with latitude and longitude in update() using F expression?
so I am writing migration which will assign latitude and longitude values to PointField in every record of database. I have one solution which works but it is too slow for a 10 000 000 records of database. So I can update every record in for loop by simply assigning lat and long to a point and then save a record. But I wanted to use Django's .update() method to do this much faster. class Listing(AirbnbModel): latitude = models.DecimalField() longitude = models.DecimalField() point = PointField(srid=4326, geography=True, null=True) # new field This works but takes too much time and it is almost impossible to do this for 10 000 000 records for listing in Listing.objects.all(): listing.point = Point(float(listing.latitude), float(listing.longitude)) listing.save() Here is what I tried to do but I got an error. Listing.objects.all().update(point=ExpressionWrapper(F('latitude'), F('longitude') , output_field=PointField())) I tried this as well Listing.objects.all().update(point=ExpressionWrapper(Point(Value('latitude'), Value('longitude')), output_field=PointField())) But this does not work at all. -
Unable to embed JSON Bokeh Plot in Django template
I have a script which takes uploaded data, munges it together, turns it into a plot (using Bokeh) and then exports it to a directory as JSON. At some point in the future a user can hit the right url and the appropriate plot should be displayed to the user as part of the html template. I can generate the plot. I can save it as JSON. I can get the url to retrieve it as JSON, but I cannot get the JSON plot to render within the template. I've had a dig around the Bokeh documentation and examples, but they all seem to use a flask app to serve the pages. I think I'm on the right track, using views.py to find and return json as part of a render() response, and then have Bokeh.embed.embed_items() do the work in the template to make it look right, but it's not working out - everything but the plot is displayed. 1) Create the plot and puts it in the directory for later use (app/results/1) create plot.py import os import json from django.conf import settings from bokeh.embed import json_item from bokeh.plotting import figure x=[1,2,3,4,5] y=[0,-1,-2,3,4] p=figure(title="test_example") p.line(x, y) json_export = json_item(p, "result") … -
django : don't return cookie for a particular endpoint
I need to return a response from Django without returning a cookie. I'm trying to implement a webhook client API that requires: the use of https response within 5 seconds no body in the response no cookies in the response headers a 401 unauthorised status code for invalid hmac signatures I'm working on Django 1.10 (soon to be upgraded to 2.x) where the rest of the app is protected by user validation via sessions. Part of the endpoint view is as follows: response200 = HttpResponse(status=200) response401 = HttpResponse(status=401) response401.close() # attempt not to set cookie signature = request.META.get('HTTP_WEBHOOK_SIGNATURE') if not request.method == 'POST': return response401 if not signature: return response401 and so on. However my attempt to avoid setting the session using response401.close() doesn't work. I've also tried del response401['Set-Cookie']see Django docs The cookie LocalTest... is still set in this curl session: $ curl -d "param1=value1&param2=value2" \ -H "webhook-signature: $SIGVAL" \ -H "Content-Type: application/x-www-form-urlencoded" \ -X POST http://127.0.0.1:8000/invoices/webhookendpoint \ -w "\n" -v ... * Connected to 127.0.0.1 (127.0.0.1) port 8000 (#0) > POST /invoices/webhookendpoint HTTP/1.1 > Host: 127.0.0.1:8000 > User-Agent: curl/7.52.1 > Accept: */* > x-xero-signature: ZSlYlcsLbYmas53uHNrBFiVL0bLbIKetQI6x8JausfA=n > Content-Type: application/x-www-form-urlencoded > Content-Length: 27 > * upload completely sent off: 27 … -
Problem in loading data in django database using 'loaddata'
I have done this in my views: from django.core.management import call_command @login_required @product_1_activation def company_upload(request): if request.method == 'POST': new_company = request.FILES['myfile'] call_command('loaddata', new_company, verbosity=0) return render(request, 'company/import.html') Its similar to python manage.py loaddata. But when I try to execute this I get the following error: No fixture named 'Primium Shipment-2019-04-11 14_01_24.254460' found. Can anyone tell me why this is happening? Thank you -
Problems with uploading my blog to pythonanywhere. Need some revision of my code
I´m trying for days now to upload my blog to pythonanywhere. I have done all the steps they described and other described all over the internet. But nothing works for me. I wanted to ask for some help, i think i have a problem in my structure or in my code. My GitHub https: https://github.com/UrosDobricic/my-blog.git I can also give you my LogIn to pythonanywhere so you can test it if you want. Please help, i can´t figure it out. Regards -
How would I implement jquery into my existing dropdown listings
I want to implement this jquery into my existing dropdown list. The one I want to intergrate is https://codepen.io/Carike/pen/QyEQeN Ive placed this code into my template and its working fine. But I just would want to integrate with my own dropdown. How would I do that? Here's my Code: <div class="col-12 col-md-4 col-lg-3"> <div class="form-group"> <select class="form-control" id="governorate" name="governorate"> <option selected="true" disabled="disabled">{% trans 'Governorate' %}</option> <option value="{{ governorate.name_ar }}" data-governorate="{{governorate.id}}">{{ governorate.name_ar }}</option> </select> </div> </div> Here's the actual code I want to integrate its functionalities with my tags. <div> <ul class="dropdown"> <li><a href="#">Kinda Tall Menu</a> <ul class="sub_menu"> <li><a href="#">Artificial Turf</a></li> <li><a href="#">Benches &amp; Bleachers</a></li> <li><a href="#">Communication Devices</a></li> <li><a href="#">Dugouts</a></li> <li><a href="#">Fencing &amp; Windscreen</a></li> <li><a href="#">Floor Protectors</a></li> <li><a href="#">Foul Poles</a></li> <li><a href="#">Netting</a></li> <li><a href="#">Outdoor Furniture &amp; Storage</a></li> </ul> </div> Basically, my code is just retreiving the data and listing them on the basis of the feilds mentioned there such as governorate.name_ar. It is listing all the governorate names in a listing form or dropdown. I just want to have the same functionality into my listings. Thank you in advance :D -
Using encode UTF-8 on File.read()
I am trying to upload a csv file to a postgresql database and it is stuck with a error you see at the end of my question. The reason is there are unicode characters in the file and it is encoded in windows-1252. This is the line where I decode the file with UTF-8. However I would like to basically accept every encoding and decode it as UTF-8 or set the encoding to UTF-8 when reading the file and then decode with the line down below. I am not using open because I had problems with it, instead I am using InMemoryUploadedFile.read() (https://docs.djangoproject.com/en/2.2/ref/files/uploads/#django.core.files.uploadedfile.UploadedFile.read) csv_file.seek(0) file = csv_file.read().decode('utf-8').splitlines() reader = csv.reader(file) This is the error and it is because of this Character: d�mpe 'utf-8' codec can't decode byte 0xb3 in position 13969: invalid start byte Any help would be appreciated. -
Numbered of questions in a quiz - how should I do it?
I'm trying to make a quiz app using Django and PostgreSQL. I want to numeber the questions but I don't know how to because python doesn't use a counter in for loops (e.g. for exercise in exercises - no for loop here) I've tried to change the for loop (for exercise in exercises) so it has a counter (for x in myrange) and defining myrange in views.py to be a range(1, len(exercitii+1)) but after that I didn't know how to access the elements inside the Jinja template. I tried to access the exercises with {exercitii.x-1.intrebare}} but it didn't work. html template {% extends 'base.html' %} {% load static %} {% block content %} </div> <div id="middle-section" class="container-fluid container-fluid-margin"> <div class="content-quiz"> <form action="{% url 'exercitiu' lectii.id %}" method="POST" id="quiz"> {% for exercitiu in exercitii %} <div class="row content-block"> <div class="col-lg-10 text-card"> {% csrf_token %} <div class="card card-custom"> <div class="card-body"> <h5 class="card-title">{{exercitiu.id}} - {{exercitiu.intrebare}}</h5> <div class="card-text"> <input type="radio" name="question-{{exercitiu.id}}-answers" id="question-{{exercitiu.id}}-answers-A" value="A" /> <label for="question-{{exercitiu.id}}-answers-A">A) {{exercitiu.variante.0}} </label> </div> <div class="card-text"> <input type="radio" name="question-{{exercitiu.id}}-answers" id="question-{{exercitiu.id}}-answers-B" value="B" /> <label for="question-{{exercitiu.id}}-answers-B">B) {{exercitiu.variante.1}} </label> </div> <div class="card-text"> <input type="radio" name="question-{{exercitiu.id}}-answers" id="question-{{exercitiu.id}}-answers-C" value="C" /> <label for="question-{{exercitiu.id}}-answers-C">C) {{exercitiu.variante.2}} </label> </div> <div class="card-text"> <input type="radio" name="question-{{exercitiu.id}}-answers" id="question-{{exercitiu.id}}-answers-D" value="D" /> <label … -
Is it possible to wait until celery group done?
I am trying to do group tasks and wait until all the group subtasks finished then run the last task. But when I call task it calls group and last tasks but the last task finished before group finish. Is it possible to wait until all the tasks inside group finish? @shared_task(name="print") def print_order(): print("PRINT #1") mylist = [(1, 2), (4, 6), (1, 4)] group([(add.s(*i) | order_id_print.s()) for i in mylist]).delay() @shared_task(name="print.add") def add(x,y): print("ADD #2") chain(add_task1.s(x, y, 'task id') | add_task2.si(x, y, "task_id")).delay() return x+y @shared_task(name="add_task_1") def add_task1(order_id, ftype, task_id): print("ADD task #2-1") print("add tasks task1 order_id {} {} {}".format(order_id, ftype, task_id)) @shared_task(name="add_task_2") def add_task2(order_id, ftype, task_id): print("ADD task #2-2") print("add tasks task2 order_id {} {} {}".format(order_id, ftype, task_id)) @shared_task(name="print.order_id_print") def order_id_print(id): print("ORDER #3") print("order id is {}".format(id)) -
MultiValueDictKeyError at /students/exam/1/ 'choice_pk2'
I loop through a radio button in order to get the value of the picked option. But, whenever, an option is not picked I will get this error. How do, I send the unpick option to null or False. try: choice_pk = [request.POST['choice_pk{}'.format(q)] for q in question_pk] except MultiValueDictKeyError: choice_pk = False if request.method == 'POST': question_pk = request.POST.getlist('question_pk', False) choice_pk = [request.POST['choice_pk{}'.format(q)] for q in question_pk] ''' try: choice_pk = [request.POST['choice_pk{}'.format(q)] for q in question_pk] except MultiValueDictKeyError: choice_pk = False ''' #print(marks_obtainable.marks_obtained) #zipped = zip(question_pk, choice_pk) with transaction.atomic():[enter image description here][1] -
Django: first time wizard of the site?
There is a demand that, when the site has just been deployed and launched, whoever visits it should be directed to a configuration wizard page where they can do some initialization work, like creating the first usergroup and the first admin account. Once this is finished, the site is back to "normal mode" and anyone accessing it will be asked for a login or registration. Any idea on how to achieve this? -
ORA2 Customization Not able to find tables
Recently I am assigned with Openedx-ORA2 Customization. But I am not able to find Assigment table and Question table . Like I am able to find Rubric table and criteria etc. But How is rubric linked to questions and where can I find assignment Id of each assignment I create . Please help me out I am stuck :/ enter image description here -
How to to access Ajax POST request from Javascript in Django
I am sending an Ajax POST request to Django from a Javascript modal. The csrf token is included correctly (after much headache...) but for whatever reason, I cannot 'fetch' the request data in my views.py. I have added some comments in the code to indicate what seems to be working I have been reading everything I could find on this, but still couldn't find the error so any input would be highly appreciated. Thanks! Javascript function getMenuItem(id){ console.log(id); // menuitem id prints correctly // Open request to get menuitem const request = new XMLHttpRequest(); request.open('POST', '/menuitem'); // Include csrf token in header so Django will accept the request const header = "X-CSRFToken" const token = Cookies.get('csrftoken'); // Using the js-cookie library console.log(token); // token prints correctly request.setRequestHeader(header, token); // Send request request.send(id); //Once request is received parse it and insert result in DOM request.onload = () => { const received = request.responseText; console.log(received); // Prints the debug message from Django const parsed = JSON.parse(received); document.getElementById('menuItem').innerHTML = parsed; }; }; views.py def menuitem(request): if request.method == 'POST': id = request.body # I have also tried HttpRequest.body print(id) # Does not print menuitem = MenuConfiguration.objects.filter(id=id).all() menuitem = serializers.serialize('json', menuitem) menuitem = json.loads(menuitem) … -
dictonaries inside while loop giving unexpected output
In python ide, dictionaries inside while loop giving the correct output but the same code in Django giving the wrong output. a9={} i9=0 while i9<10: a9.update({i9:i9}) i9=i9+1 Expected result : {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9} Actual result : 10