Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best index for a Django model when filtering on one field and ordering on another field
I use Django 2.2 linked to PostgreSQL and would like to optimise my database queries. Given the following simplified model: class Person(model.Models): name = models.CharField() age = models.Integerfield() on which I have to do the following query, say, Person.objects.filter(age__gt=20, age__lt=30).order_by('name') What would be the best way to define the index in the model Meta field? Which of these four options would be best? class Meta indexes = [models.Index(fields=['age','name']), models.Index(fields=['name','age']), models.Index(fields=['name']), models.Index(fields=['age'])] Thank you. -
Read sqlite from request body in Django
I want to read the sqlite database from request body without saving it into temporary file. The request has been sent by: curl -X POST --data-binary @mydb.sqlite3 -H "Content-Type: application/octet-stream" "http://localhost:8000/upload_sqlite" My view function like this: def upload_sqlite(request): print(request.body.decode('utf-8')) conn = sqlite3.connect(request.body) cursor = conn.cursor() cursor.execute("SELECT * FROM table") # do something cursor.close() conn.close() return HttpResponse(status=200) And the console output is here: b'SQLite format 3\x00\x04\x00\x01\x01\x00@ \x00\x00\x00\x18\x00\x00\x00\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x0...' ...ignored... File "/path/to/views.py", line 208, in upload_sqlite conn = sqlite3.connect(request.body) ValueError: embedded null byte -
What are the cons of using mysql's reserved keywords as fields with django?
I have a Django model as: Class DataFile(models.Model): file = models.FileField(upload_to=get_file_upload_path) But, file is a reserved keyword in MySQL. I know that we can use any reserved keyword as column name by wrapping it in ``. My senior advised me not to use reserved keywords and use something which is nearly meaningful other than just file. What are the cons? -
django - Way to avoid custom manager for specific queries
I have the following issue: I am working on a grown project which uses the pattern of overriding the get_queryset() method in the manager. # Model declaration class MyModel(models.Model): ... objects = MyModelManager() # Manager declaration class MyModelManager(models.Manager): def get_queryset(self): return super(MyModelManager, self).get_queryset().exclude(is_visible=False) This causes some records to become basically invisible when you using the django ORM. I need now in certain edge cases to use the base get_queryset() method and NOT to use the custom one. I could clean up and change all the code but this is a lot of work. So my question: Is there a way to make a query like this MyModel.objects.all() and avoid using the custom manager method? Hope I made my point clear enought. Thx Ron -
Django: Getting a list of meetings that a certain user is in
I am new to Django and I am trying to get a list of meetings that a user is in, so that I can display them on a calendar. I have the following in models.py: class CustomUser(AbstractUser): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=70, null=True, unique=True) password = models.CharField(max_length=50, null=True) class Meeting(models.Model): id = models.AutoField(primary_key=True) admin = models.ForeignKey(CustomUser, on_delete=models.CASCADE) name = models.CharField(max_length=20, null=True) location = models.CharField(max_length=200, null=True) start_date = models.DateTimeField(default=None, null=True) end_date = models.DateTimeField(default=None, null=True) description = models.CharField(max_length=2000, null=True) class Member(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) meeting = models.ForeignKey(Meeting, on_delete=models.CASCADE) Essentially, a user and a meeting are linked in the Member model. I have the following function in database.py, which creates a new Meeting: def createMeeting(name, location, admin, start_date, end_date, description): new = Meeting(name=name, location=location, admin=admin, start_date=start_date, end_date=end_date, description=description) if not duplicate(Meeting, new): new.save() membership = Member(user=admin, meeting=new) if not duplicate(Member, membership): membership.save() For a certain user that is logged in, I want to be able to get a list of all the meetings that they are a member of. I know that I will need to use the Member model, but I am not sure what is the best method to get all the meetings a user … -
Return JsonResponse from function in Django REST
I have a query in which all fields are required. I want to make sure they're full. It turns out a lot of duplicate code. So I decided to create a function to which I pass values from a field. But the request continues rather than sending a response code 400. My views.py def pay(request): body = request.body.decode('utf-8') if not body: return JsonResponse({ 'status': 'failed', 'errors': { 'code': 400, 'message': 'empty query' }, }) body = json.loads(body) phone = body.get('phone') amount = body.get('amount') merch_name = body.get('merchant_name') #check_field(phone) if not phone: return JsonResponse({ 'status': 'failed', 'errors': { 'code': 400, 'message': 'phone field is empty' }, }) if not amount: return JsonResponse({ 'status': 'failed', 'errors': { 'code': 400, 'message': 'amount field is empty' }, }) if not merch_name: return JsonResponse({ 'status': 'failed', 'errors': { 'code': 400, 'message': 'merch_name field is empty' }, }) My function: def check_field(field): if not field: logger.info('its work') return JsonResponse({ 'status': 'failed', 'errors': { 'code': 400, 'message': '{} field is empty'.format(field) }, }) How i can fix it? -
Django Javascript not working in HTML to Ajax call
I'm trying to detect changes in a Form to change the following parameters depending on the previous one. Concretely when I change id_send_to(Client) it shows a list of companies from the client. I think that this should be done with Ajax Call. This is the code and when I check in the inspector I cannot see the console.log {% extends "helpdesk/base.html" %} {% load i18n bootstrap %} <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#id_send_to").change(function () { console.log( $(this).val() ); }); }); </script> Any Idea ? -
Django-models Change format of dateField as "DD-MM-YYY"
I am using django-model's-dateField in my django-project and wanna change my dateFields format in admin view. Currently (default) django gives format in YYYY-MM-DD but i want to modify that and in need of DD-MM-YYYY I've been struggled too much in this and till no solution. Also providing my code, may help.. my settings.py have: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True models.py: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='User_Profile') mobile = models.BigIntegerField() alternative_number = models.BigIntegerField() DOB = models.DateField() and then i register it in admin output on admin as you can see in my admin page there is a dateField with format 2019-11-04 but i want in form of DD-MM-YYYY as 04-11-2019. I tried LANGUAGE_CODE = 'de-at' that would work for me but the problem is it changes the local language also. -
Django view - template returned as bytestring (b'')
i have a strange problem with Django templates after merging recent changes. I migrated my application from Django 2.0.5 to 2.1.7, had some places in code to correct but nothing related with existing templates. After rebuild and deploy my templates are returned as bytestring in HTTP response body: b'<!DOCTYPE html>\n\n<html lang="en">\n <head ... Django settings charset is set to default utf-8 (i have some polish signs in page body) and files are encoded as: text/html; charset=us-ascii As far as i know us-ascii is subset of UTF-8 so it should be good. My base template is visible by template loader under common_app/base.html: <!DOCTYPE html> {% load pipeline navigation_tags i18n %} <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>XXX {% block title %}{% endblock title %}</title> {% stylesheet 'common' %} {% javascript 'common' %} {% block header %} {% endblock %} {% stylesheet 'sb-admin' %} {% javascript 'sb-admin' %} ... </head> <body> {% block body %} ... {% if user.is_authenticated %} ... {% render_navigation %} ... {% endif %} ... {% if error %} ... {% else %} {% block content %} {% endblock %} {% endif %} ... {% block footer %} {% endblock footer %} … -
Django reverse() method still throwing NoReverseMatch exception error even after adding the application name space
This is my urls.py file with my route names. from django.urls import path from . import views app_name = "procurement" urlpatterns = [ path('', views.index, name='index'), path('my_redirect/',views.my_redirect, name="my_redirect"), path('members/', views.members, name="members"), path('addMember/', views.addMember, name="addMember"), path('removeMember/', views.removeMember, name="removeMember"), path('requisition/', views.new_requisition, name="new_requisition"), path('user_department', views.user_department, name="user_department"), path('part1_requisition', views.part1_requisition, name="part1_requisition"), path('back_to_requisition_part1/', views.back_to_requisition_part1, name="back_to_requisition_part1"), path('part2_requisition/', views.part2_requisition, name="part2_requisition"), path('part3_requisition/', views.part3_requisition, name="part3_requisition"), path('ajax_filter', views.ajax_filter, name="ajax_filter"), path('pdu', views.pdu, name="pdu"), path('accounting_officer', views.accounting_officer, name="accounting_officer") ] And in my views.py file, I have something like this: @login_required def ajax_filter(request): """ Filter's ajax requests. """ if request.is_ajax(): first_name = "Byenkya" if first_name: return JsonResponse({ "success": True, "url": reverse('procurement:part3_requisition', args=[first_name]), }) return JsonResponse({ "success": False }) I really don't know why the reverse function is still raising the exception even after adding the namespace. Please someone help am new to django. -
how to delete record from django?
I have looked for alot of forums on how to do it but it just doesnt work, it seems like I could not get the button to link to the views method. views: item_id = int(item_id) p = Item.objects.get(item_id=item_id) p.delete() return redirect('viewproducts') viewproducts.html:(only taking the important parts out, also ignore the edit button) <tr> <td>{{i.item_id}}</td> <td>{{i.type}}</td> <td>{{i.name}}</td> <td>{{i.price}}</td> <td>{{i.description}}</td> <td>{{i.supplier}}</td> <td> <button onclick="/edit/{{item}}" type="button" class="btn btn-success"> Edit</button> <a href="/razer/deleteproducts/{{i.item_id}}" id={{i.item_id}}> Delete</a> </td> {% endfor %} urls.py: url('home/', home, name = 'Home Page'), url('addmembers/', addmembers, name = 'Add new members'), url('addproducts/', addproducts, name = 'Add new products'), url('members/', viewmembers, name = 'View all members'), url('products/', viewproducts, name = 'View all products'), url('deleteproducts/<int:item_id>', deleteproducts) ) all it doesis that it takes me to the same page as products, but with the link as http://127.0.0.1:8000/razer/deleteproducts/000999 Can someone help me please? Want to figure things out. -
How to run two requests parallel in django rest
I have two requests, which are called from react front end, one request is running in a loop which is returning image per request, now the other request is registering a user, both are working perfect, but when the images request is running in a loop, at the same time I register user from other tab,but that request status shows pending, if I stops the images request then user registered,How can I run them parallel at the same time. urls.py url(r'^create_user/$', views.CreateUser.as_view(), name='CreateAbout'), url(r'^process_image/$', views.AcceptImages.as_view(), name='AcceptImage'), Views.py class CreateUser(APIView): def get(self,request): return Response([UserSerializer(dat).data for dat in User.objects.all()]) def post(self,request): payload=request.data serializer = UserSerializer(data=payload) if serializer.is_valid(): instance = serializer.save() instance.set_password(instance.password) instance.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class AcceptImages(APIView): def post(self,request): global video stat, img = video.read() frame = img retval, buffer_img = cv2.imencode('.jpg', frame) resdata = base64.b64encode(buffer_img) return Response(resdata) These endpoints I am calling from react,the second endpoint is being calling in a loop and the same time from other tab I register user but it shows status pending and If I stop the image endpoint it then register the user,how can I make these two request run parallel. I have researched a lot but can't find appropriate solution, there … -
Writing javascript code in Django templates I got an error " Uncaught TypeError: Cannot set property 'innerHTML' of null"
This error is occurring in my console in the below line. function updateCart(cart) { for (var item in cart) { document.getElementById("div"+item).innerHTML = "- " + cart[item] + " + "; } localStorage.setItem('cart', JSON.stringify(cart)); document.getElementById('cart').innerHTML = Object.keys(cart).length; console.log(cart); } -
Can I redirect with method POST?
On my website the user can answer questions. If the user clicks (GET request) on a question the question_detail view is called and rendes the question_detail.html template with a question object. If the user clicks on a submit button a POST request is sent to the same question_detail view that renders question_detail_solution.html. On this template the user can submit a comment form that is handled by the add_comment_to_question view. Once the comment is submitted I want the user to be redirected back to the same question_detail_solution.html template. It is important that the same context is passed into the template. Can I do a redirect with method POST from add_comment_to_question and is this best practice? Or should I define another view that renders question_detail_solution.html and redirect from question_detail (POST) and add_comment_to_question to this view? Or something else? Thank you for your answer! def question_detail(request, pk): question = get_object_or_404(Question, pk=pk) user_profile = Profile.objects.get(user=request.user) solved_questions = user_profile.solved_questions.all() if request.method == 'GET': context = {'question':question} return render(request, 'question_detail.html', context) else: try: answer = int(request.POST['choice']) is_correct = question.choice_set.get(id=answer).correct if is_correct: user_profile.solved_questions.add(question) form = CommentForm() context = {'question':question, 'answer':answer, 'correct':is_correct, 'form':form} return render(request, 'question_detail_solution.html', context) except KeyError: messages.error(request, "Please make a choice!") context = {'question': question} … -
Django button class forloop trigger javascript
i have forloop in Django template and want to make button for elements if condition contains true to show additional info as infobox, or popup. Best way to do this is javascript, but how to trigger each one separately? I dont know how many buttons will be. I could use forloop counter, but how to activate js then? {% for hist in histor %} <a class="trigger_popup_{{ forloop.counter }}"><img src='{% static "images/info.PNG" %}'></a> {% if hist.ikona == 1 %} <img src='{% static "images/hist/108.png" %}'> {% elif hist.ikona == 2 %} <img src='{% static "images/hist/154.png" %}'> {% elif hist.ikona == 8 %} <img src='{% static "images/hist/499.png" %}'> {% endif %} {% endfor %} What to add in this: var modal = document.getElementById("trigger_popup_"); button / link class may be trigger_popup_4, trigger_popup_5, trigger_popup_88 How to manage this? -
Click a button and run a python function from views.py with JS/ajax in django
I've been reading this days about how can I call a python function when I press a button and I'm very confused. One of the things that I saw is that I have to use ajax and most of the people use jquery to do it. If I understood correctly the structure has to be similar to this, $(document).ready(function() { $.ajax({ url: '', type: '', data: {'A':0}, datatype:'', success: function(resp){ console.log(resp); } }); }); With this information, my final code is, views.py def vista_sumar(request): if request.method == 'POST': a = request.POST['a'] b = request.POST['b'] c = a + b ctx = {'Result':c} return render(request,'main.html',ctx) urls.py from project.views import vista_sumar urlpatterns = [ path('prueba/',vista_sumar), ] main.html <input type="button" value="PRUEBA" class="boton"> <script src="{% static '/js/jquery-3.4.1.min.js' %}"></script> <script type="text/javascript" src="{% static '/js/filters.js' %}"></script> filters.js (the big fail) $('#prueba').click(function() { alert('boton is working') a =1; b =3; $.ajax({ method: 'POST', url: '/../../prueba/', data: { 'a': a, 'b': b, }, dataType: "json", success: function(response) { alert(response.Result); } }); }); I know the button is working because the first alert is working. The problem is when I use ajax. The code error is 403=Forbbiden and is failing in the ajax.send() Can somebody help me? Thank you … -
Renamed Django directory root - ImportError: cannot import name 'python_implementation' from 'platform'
I renamed my project and my directory using Pycharm refactor functions, and now it's broken. I changed all the dependencies I could find, however there seems to be some funky stuff going on with the error and I absolutely cannot figure it out. The error message: Traceback (most recent call last): File "C:/Users/user1/Projects/platform_back/manage.py", line 21, in <module> main() File "C:/Users/user1/Projects/platform_back/manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\user1\Projects\platform_back\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\user1\Projects\platform_back\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user1\Projects\platform_back\venv\lib\site-packages\django\core\management\__init__.py", line 244, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\user1\Projects\platform_back\venv\lib\site-packages\django\core\management\__init__.py", line 37, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "C:\Users\user1\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\user1\Projects\platform_back\venv\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 3, in <module> from django.core.management.commands.runserver import ( File "C:\Users\user1\Projects\platform_back\venv\lib\site-packages\django\core\management\commands\runserver.py", line 10, in <module> from django.core.servers.basehttp import ( File "C:\Users\user1\Projects\platform_back\venv\lib\site-packages\django\core\servers\basehttp.py", line 14, in <module> from wsgiref import simple_server File "C:\Users\user1\AppData\Local\Programs\Python\Python37\lib\wsgiref\simple_server.py", line 17, in <module> from platform import python_implementation ImportError: cannot import name 'python_implementation' from 'platform' … -
How to use slug in django-rest-framework?
I am very new to django rest framework.I was using slug instead of pk in the django application.Now in DRF I also want to use the slug.Before I was using autoslug from django-autoslug package and which was working fine but I am just wondering is django-autoslug can be used in Django Rest Framework also? models.py class A(models.Model): field = models.CharField(max_length=255) slug = AutoSlugField(populate_from='field') Can I implement slug like this in my DRF also? -
How to return data in custom json format?
Models class Transaction(models.Model): created_at = models.DateTimeField() transaction_type = models.ForeignKey( TransactionType, on_delete=models.CASCADE ) class TransferSerializer(serializers.ModelSerializer): class Meta: model = Transfer fields = ('transfer_type', 'debit', 'credit', 'amount', 'currency_code') Serializers class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = '__all__' class Transfer(models.Model): transaction_id = models.ForeignKey( Transaction, on_delete=models.CASCADE ) debit = models.ForeignKey( Account, on_delete=models.CASCADE, related_name='debit' ) Views class TransactionViewSet(viewsets.ModelViewSet): queryset = Transaction.objects.all() serializer_class = TransactionSerializer pagination_class = LimitOffsetPagination How to return data with following json format? What is the best approach? { "created_at": "2019-08-18", "transaction_type_id": "1", "transfers": {"debit": "100"}, } -
There is e-government system is open source?
I need open source in GitHub , written in modern language like #python , please give me best systems ^__^; -
How to normalize and load pandas DataFrame into Django backend
I have found a lot of code samples looking to load a pandas DataFrame into a Django backend as a whole table ( not breaking up the table and normalizing the data into separate tables with foreign key relationships ). I am not sure that this is the most efficient way to store pandas DataFrame tables in a db. I believe it should be broken down into separate tables and connected via a ForeignKey. Is there any python library that will do this for you ? What would be a good approach to achieve this ? -
I have problems installing Django
I installed everything that was needed for installing Django with these commands: sudo apt-get install python3 python3-pip pip install Django pip --version pip 19.1.1 from /home/ion/anaconda3/lib/python3.7/site-packages/pip (python 3.7) And I tried to install with pip3 install Django pip3 --version pip 9.0.1 from /usr/lib/python3/dist-packages (python 3.6) But when I run django-admin --version Cannot find installed version of python-django or python3-django. I tried again to install django: pip install Django==2.2.7 Requirement already satisfied: Django==2.2.7 in /home/ion/anaconda3/lib/python3.7/site-packages (2.2.7) Requirement already satisfied: sqlparse in /home/ion/anaconda3/lib/python3.7/site-packages (from Django==2.2.7) (0.3.0) Requirement already satisfied: pytz in /home/ion/anaconda3/lib/python3.7/site-packages (from Django==2.2.7) (2019.1) What can be the problem? -
Django: Relational view in template [many-to-one relationship]
I have a many-to-one relationship in my models. And I want to view the data of my child table in html table related to the parent table. Here's my models.py: class DataCollection(models.Model): default_name = models.CharField(max_length=100) class NameHistory(models.Model): old_name = models.CharField(max_length=100) collection_data = models.ForeignKey(DataCollection, on_delete=models.CASCADE, null=True) And here's my views.py: def dashboard(request): foo = ( DataCollection.objects .annotate( first_old_name=Window( expression=FirstValue('namehistory__old_name'), partition_by=[F('id'), ], order_by=F('namehistory__id').desc() ) ) .values_list('first_old_name', flat=True) .distinct() ) context = { 'sample': foo, 'dashboard': DataCollection.objects.all(), 'title':'Dashboard' } return render(request, 'dashboard/dashboard_form.html', context) My problem is, how can I view the data of this key sample in the template which is related to id of DataCollection table. Here's a sample data in my models, DataCollection: Here's a sample data for NameHistory: So in my html table it should be something like this: I tried this kind of code but I don't know why is it always returning the No Name: <tbody> {% for data in dashboard %} <tr> <td>{{ data.default_name }}</td> {% for item in sample.namehistory_set.all %} <td>{{ item.old_name }}</td> {% empty %} <td> No Name </td> {% endfor %} </tr> {% endfor %} </tbody> -
Django recive incomming GET request
i need to create simple callback function for incoming GET data from sms Api in Django. The incoming data is comma separated. The example php callback looks like below: <?php if($_GET['MsgId'] && $_GET['status'] ) { mysqli_select_db('database_name',mysqli_connect('localhost','login','password')); $arIds = explode(',',$_GET['MsgId']); $arStatus = explode(',',$_GET['status']); $arIdx = explode(',',$_GET['idx']); if($arIds){ foreach($arIds as $k => $v){ mysqli_query("UPDATE sms SET sms_status = '".mysqli_real_escape_string($arStatus[$k])."', sms_index = '".mysqli_real_escape_string($arIdx[$k])."' WHERE sms_id ='".mysqli_real_escape_string($v)."' LIMIT 1"); } mysqli_close(); echo"OK"; } ?> For now i try to setup proper function to collect response data. My attempt: from django.views.decorators.http import require_GET from django.http import HttpResponse @require_GET def callback(request): raw_data = request.body return HttpResponse(status=200) Questions: The receiving function need to by in views.py file, and specified in urls.py? Is the above function properly created for receiving this data? Thank You for all suggestions. -
Django edit table row by clicking button
I can create table with modal form. Now i want to edit and delete the row. Here i found how to update records. But i'm new in django and didn't understand how to release it in view and template. P.S Users must be logged in to see own table. view.py: @login_required(login_url='/accounts/login/') def viewpost(request): person_list = Persona.objects.filter(user_id=request.user) user_filter = UserFilter(request.GET, queryset=person_list) if request.method == 'POST': if request.POST.get('name') and request.POST.get('surname') and request.POST.get('address'): person = Persona() person.name = request.POST.get('name') person.surname = request.POST.get('surname') person.address = request.POST.get('address') person.age = request.POST.get('age') person.payDate = request.POST.get('payDate') person.cover = request.FILES['cover'] person.user = request.user person.save() return HttpResponseRedirect('/viewpost') else: return render(request, 'mysite/viewpost.html', {'persons': person_list, 'filter': user_filter})