Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django import adding Many-to-Many relationship based on value non-model field
I'm using django-import-export to import an xls. In the xls is a boolean field is_senior which is not a model field. In the model I have a Many-to-Many relationship to a Model Level which has junior, senior etc. If is_senior is True I want to: senior = Level.objects.filter(name__icontains = 'senior').first() instance.level.add(senior) But the problem is: before_import_row knows the non-model field, but can't add m2m relationships after_save_instance doesn't have the non-model field any ideas? -
im using git and if try to push changes i get error which says the branches have diverged
I was working with a project in that I made a mistake so I restored my last commit in my local rep I don't know how to do it on the remote repo , no if I try to push my changes I get a error , that the branches have diverged , what should I do should I delete the remote repo and then again push ? -
Is there a reason why django doesn't pass site header context to password reset form?
I'm trying to set the site header of the password reset form but doing the admin.site.site_header = "Site header" changes the header for all other forms other than the password reset form. Is this by design and if so why? The only way I can find to fix this right now is https://stackoverflow.com/a/53572673/5562041 -
How to create a drop-down menu with database objects?
I'm trying to make a website with many categories. I want staff to be able to add categories via the back-end admin page. Then I need to display those categories and display them to the to the user on a drop-down menu. They will then select a category and submit the result. All I need help with is the models. #for back end class create_listing_category(models.Model): category = models.CharField(blank=False, max_length=20) categories = ??? class create_listing_sub_category(models.Model): category = models.CharField(max_length=25, choices=categories) #categories will be the list contents sub_category = models.CharField(blank=False, max_length=20) Thank you for helping your fellow noob out -
Django ORM exclude records using an array of dictionaries
I have similar code that return all entries from a table: all_entries = Entry.objects.all() and I have the following array: exclusion_list = [ { "username": "Tom", "start_date": 01/03/2019, "end_date": 29/02/2020, }, { "username": "Mark", "start_date": 01/02/2020, "end_date": 29/02/2020, }, { "username": "Pam", "start_date": 01/03/2019, "end_date": 29/02/2020, } ] I want to exclude all Tom's records from "01/03/2019" to "29/02/2020", all "Mark" records from "01/02/2020" to "29/02/2020" and all Pam's record from "01/03/2019" to "29/02/2020" I want to do that in a loop, so I believe i should do something like: for entry in all_entries: filtered_entry = all_entries.exclude(username=entry.username).filter(date__gte=entry.start_date, date__lte=entry.end_date) Is this correct. I am new to Django ORM. Is there a better and more efficient solution? Thank you for your help -
Working Directory not configuring Visual Studio 2019
I am creating a django site and I have created django project inside an app folder of the root directory. My folder structure looks like this . ├── .gitignore ├── .travis.yml ├── .vs │ ├── PythonSettings.json │ ├── VSWorkspaceState.json │ ├── launch.vs.json │ ├── recipe-app-api │ │ └── v16 │ │ └── .suo │ └── slnx.sqlite ├── Dockerfile ├── LICENSE ├── README.md ├── app │ ├── app │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-37.pyc │ │ │ ├── calc.cpython-37.pyc │ │ │ ├── settings.cpython-37.pyc │ │ │ ├── tests.cpython-37.pyc │ │ │ └── urls.cpython-37.pyc │ │ ├── calc.py │ │ ├── settings.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── wsgi.py │ └── manage.py ├── docker-compose.yml └── requirements.txt I have configured my launch.vs.json file like this { "version": "0.2.1", "defaults": {}, "configurations": [ { "type": "python", "interpreter": "(default)", "interpreterArguments": "", "scriptArguments": "", "env": {}, "nativeDebug": false, "webBrowserUrl": "", "project": "app\\manage.py", "name": "manage.py", "workingDirectory": "app" } ] } The problem still is that Visual Studio 2019 cannot detect that my working directory is the app folder. That's why it showing the python import is unresolved. Image of the error here Am I … -
django best way to manage CRUD in a single view
I am performing a way to Delete/update/get in a same view like class APICRUDVIEW(APIView): def get(self,request,id): .... def put(self,request,id): .... def delete(self,request,id): .... So that thing doesn't violate SRP (Single Responsibility Principle ). Like according to that a class strictly should perform a single task. Or its best way to include all these in a class in django ? -
'django' is not recognized after installing it
I'm trying to install Django. But then it seems not to be recognized: C:\Users\antoi\Documents\Programming\Learning\Django\password_generator>pip3 install django Requirement already satisfied: django in c:\python36\lib\site-packages (3.1.1) Requirement already satisfied: sqlparse>=0.2.2 in c:\python36\lib\site-packages (from django) (0.3.1) Requirement already satisfied: asgiref~=3.2.10 in c:\python36\lib\site-packages (from django) (3.2.10) Requirement already satisfied: pytz in c:\python36\lib\site-packages (from django) (2018.7) C:\Users\antoi\Documents\Programming\Learning\Django\password_generator>django -V 'django' is not recognized as an internal or external command, operable program or batch file. C:\Users\antoi\Documents\Programming\Learning\Django\password_generator>django -v 'django' is not recognized as an internal or external command, operable program or batch file. When I try to execute some commands I get nothing: C:\Users\antoi\Documents\Programming\Learning\Django\password_generator>python3 manage.py runserver -
Is it possible to use react and django with firebase
I want to use react as frontend, django for its urls(multi page system), and firebase for realtime database and hosting. Is it possible to use all the three together? -
Multipart-form with Django Rest Framework
I want to post an image along JSON from axios to Django Rest Framework, I'm using multipart-form as mentioned in the documentation but nothing is working. need your help. -
Django model set field default to another field
I've spent some time reading through other questions but I feel like my problem is different, so here it is: class myModel(models.Model): foo = models.DecimalField(decimal_places=2) bar = models.DecimalField(decimal_places=2, default=foo) I would like bar to take foo as a default value but I get a TypeError: conversion from DecimalField to Decimal is not supported What should I do? Should I use the override function, as suggested in other posts? Thank you in advance! -
Django2.2.14 request.META just have only "REMOTE_ADDR" to get ip
I have an application running.I want get client ip.But when I use request.META,this dict just have only one key can get client IP,"REMOTE_ADDR",not like the other say many keys like "X-Forwarded-For","HTTP_X_FORWARDED_FOR" and so on.My environment is Django==2.2.14 and Python==3.7. When I print request.META. print(request.META.keys()) The result is like. dict_keys(['ALLUSERSPROFILE', 'APPDATA', 'COMMONPROGRAMFILES', 'COMMONPROGRAMFILES(X86)', 'COMMONPROGRAMW6432', 'COMPUTERNAME', 'COMSPEC', 'DRIVERDATA', 'FPS_BROWSER_APP_PROFILE_STRING', 'FPS_BROWSER_USER_PROFILE_STRING', 'HOMEDRIVE', 'HOMEPATH', 'LOCALAPPDATA', 'LOGONSERVER', 'NUMBER_OF_PROCESSORS', 'ONEDRIVE', 'OS', 'PATH', 'PATHEXT', 'PROCESSOR_ARCHITECTURE', 'PROCESSOR_IDENTIFIER', 'PROCESSOR_LEVEL', 'PROCESSOR_REVISION', 'PROGRAMDATA', 'PROGRAMFILES', 'PROGRAMFILES(X86)', 'PROGRAMW6432', 'PROMPT', 'PSMODULEPATH', 'PUBLIC', 'PYCHARM_HOSTED', 'PYTHONIOENCODING', 'PYTHONPATH', 'PYTHONUNBUFFERED', 'SESSIONNAME', 'SYSTEMDRIVE', 'SYSTEMROOT', 'TEMP', 'TMP', 'USERDOMAIN', 'USERDOMAIN_ROAMINGPROFILE', 'USERNAME', 'USERPROFILE', 'VIRTUAL_ENV', 'WINDIR', '_OLD_VIRTUAL_PATH', '_OLD_VIRTUAL_PROMPT', 'DJANGO_SETTINGS_MODULE', 'RUN_MAIN', 'SERVER_NAME', 'GATEWAY_INTERFACE', 'SERVER_PORT', 'REMOTE_HOST', 'CONTENT_LENGTH', 'SCRIPT_NAME', 'SERVER_PROTOCOL', 'SERVER_SOFTWARE', 'REQUEST_METHOD', 'PATH_INFO', 'QUERY_STRING', 'REMOTE_ADDR', 'CONTENT_TYPE', 'HTTP_HOST', 'HTTP_CACHE_CONTROL', 'HTTP_UPGRADE_INSECURE_REQUESTS', 'HTTP_USER_AGENT', 'HTTP_ACCEPT', 'HTTP_ACCEPT_ENCODING', 'HTTP_ACCEPT_LANGUAGE', 'HTTP_COOKIE', 'HTTP_CONNECTION', 'wsgi.input', 'wsgi.errors', 'wsgi.version', 'wsgi.run_once', 'wsgi.url_scheme', 'wsgi.multithread', 'wsgi.multiprocess', 'wsgi.file_wrapper', 'CSRF_COOKIE']) And Iam very sure just one key about client ip,"REMOTE_ADDR". Where the another keys about client ip goes,and there is another function to get client ip? -
Django : fetch template from a parallel directory
in my project, my template folder is as follows. In both the folders, i have a template named results.html templates |--customer_site | |--results.html | |backoffice |--results.html for the customer facing site, my settings file contains TEMPLATES = [{ ... 'DIRS': ['templates/customer_site'], }] in one particular function in customer facing site, i need to access the template named results.html which is in backoffice. def some_function(request): .... .... return render(request, 'results.html') this returns the results.html page of customer facing site, but i want the results.html page available in backoffice folder. -
How to use Django Filters to filter for many values for the same field?
Hi i am trying to do a filter using django filter and i can do filter like below # function to do filter class EmailFilter(django_filters.FilterSet): email_ml_recommendation = filters.CharFilter(method='filter_by_decision') email_broker = django_filters.CharFilter(field_name="email_broker", lookup_expr='icontains') class Meta: model = submission fields = '__all__' def filter_by_decision(self, qs, name, value): if ',' in value: # filter for multiple selection if value.count(',') == 1: print('inside --') v_1 = value.split(',')[0] v_2 = value.split(',')[1] return qs.filter( Q(email_ml_recommendation__icontains=v_1) | Q(email_ml_recommendation__icontains=v_2) ) elif value.count(',') == 2: v_1 = value.split(',')[0] v_2 = value.split(',')[1] v_3 = value.split(',')[2] return qs.filter( Q(email_ml_recommendation__icontains=v_1) | Q(email_ml_recommendation__icontains=v_2)| Q(email_ml_recommendation__icontains=v_3) ) else: return qs.filter( Q(email_ml_recommendation__icontains=value) ) And calling my filter in below class class SUBMISSIONFILTERVIEWSET(viewsets.ModelViewSet): queryset = submission.objects.all().filter(email_today_mail=1).order_by('-email_last_updated') serializer_class = SubmissionsSerializer filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter,) filterset_class = EmailFilter OrderingFilter() # ordering_fields = ('broker_name') ordering = ('-email_last_updated') # default ordering can be overridden using ordering fields the problme is i can filter on multiple values on the same field but for that i need to increase my Q parameter what i mean in order to do multi value filter for the same filed(email_ml_recommendation) i have to create a custom method filter_by_decision and inside that i have to use Q parameter same number of time as the value i get … -
how to fix curl django rest framework?
how to fix curl django rest framework , I get error like this rest_framework.exceptions.ParseError: JSON parse error - Expecting value: line 1 column 1 (char 0) this my curl curl -X POST http://127.0.0.1:8000/api/signup -H "Content-Type: application/json" -d '{"username":"indah","password":"indah123"} and this my code , @csrf_exempt def signup(request): if request.method == 'POST': try: data = JSONParser().parse(request) user = User.objects.create_user(data['username'], password=data['password']) user.save() token = Token.objects.create(user=user) return JsonResponse({'token':str(token)}, status=201) except IntegrityError: return JsonResponse({'error':'That username has already been taken. Please choose a new username'}, status=400) and get error in line data = JSONParser().parse(request) I using cmd windows for curl what wrong with curl? -
Empty python request body
I am sending the below payload to the test api as shown but am getting an empty body. Please help. I have checked and I cant see where the problem is. import requests #(version 2.20.1) requests.post('http://127.0.0.1:8000/api/test/', json={'event_ref_id': 'PZpHoGrGKbIEv', 'member_no': 'mb001', 'action': 'course_registration'}, headers={'Content-Type': 'application/json'}) My Django endpoint is very simple as shown below but an getting an empty body @api_view(['POST']) def get_test(request): print(request.body) body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) print(body) return Response(status=status.HTTP_200_OK) Why API print body is b'{}' {} -
How can I provide the initial value for form field that will be created using Jquery?
I have a form in a Django web site. When the form is shown, I create a new field using jQuery. Something like: $("#field_defined_in_form").after( '<input class="numberinput" type="number" step="1" id="id_new_field" name="new_field">' ) I can save the information provided in "#id_new_field" to the database with POST. However, when I want to edit the information in the DB, I need to provide the initial value for "#id_new_field". 1 - How can I provide the initial value for a form field that will be created using Jquery? I tried: initial = { 'new_field': 'Initial_value', } form = TheFormClass(initial=initial) But this does not work. 2 - Is there any way to access the form initial values using jQuery? I guess not, but I ask just in case. I could also pass the value to jQuery through the template like: <script> window.pageData = { new_field : '{{new_field_value}}', } </script> The real life problem includes a non-fixed number of new_field so I tried to pass the whole initial dict. <script> window.pageData = { initial : '{{initial}}', } </script> This does not work because initial is turned into a string not an object. So: 3 - How can I pass the python dict initial to a jQuery object, … -
I want to change the value of AutoField
class DoctorList(models.Model): d_code = models.AutoField(primary_key=True) name = models.CharField(max_length=300) position = models.CharField(max_length=200) code = models.ForeignKey(HospitalList, on_delete=models.CASCADE, db_column="code") def __str__(self): return str(self.d_code) I want to change the AutoField of d_code to D_1, D_2, D_3 ... not 1,2,3 ... I've seen many examples here but couldn't understand. How do you organize your code to get what you want? -
Django manage.py loaddata : 'ManyToOneRel' object has no attribute 'to_python'
I'm trying to import data from json file using manage.py loaddata. getting below error while importing. File "/opt/virtualenvs/python3/lib/python3.8/site-packages/django/core/serializers/python.py", line 144, in Deserializer raise base.DeserializationError.WithData(e, d['model'], d.get('pk'), field_value) django.core.serializers.base.DeserializationError: Problem installing fixture '/home/runner/BookShop/bookShopAPI/inventory/fixtures/seed_data.json': 'ManyToOneRel' object has no attribute 'to_python': (inventory.author:pk=2) field_value was '[1]' models.py class Genre(models.Model): # TAG Choices FICTION = 'F' GRAPHIC_NOVEL = 'GN' # add more tag options if required TAG = ( (FICTION, 'Fiction'), (GRAPHIC_NOVEL, 'Graphic Novel'), ) # write implementation tag = models.CharField(max_length=15,choices=TAG) description = models.TextField(max_length=100) author = models.ForeignKey(Author,on_delete=models.CASCADE,related_name='genre',null=True, blank=True) book = models.ForeignKey('Book',on_delete=models.CASCADE,related_name='genre',null=True, blank=True) class Author(models.Model): # write implementation first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) author_bio = models.TextField(max_length=100) book = models.ForeignKey('Book',on_delete=models.CASCADE,related_name='author',null=True, blank=True) json file [ { "model":"inventory.genre", "pk":"1", "fields":{ "tag":"fiction", "description":"Fiction is the telling of stories which are not real. More specifically, fiction is an imaginative form of narrative, one of the four basic rhetorical modes. Although the word fiction is derived from the Latin fingo, fingere, finxi, fictum, works of fiction need not be entirely imaginary and may include real people, places, and events. Fiction may be either written or oral. Although not all fiction is necessarily artistic, fiction is largely perceived as a form of art or entertainment. The ability to create fiction and other … -
How to add django variable name inside a href attribute?
I need to add dynamic images to a page but it doesn’t work. I'm getting an error: <img src="{% static 'geonode/img/layers/{{layer.title}}.png' %}" class="add-layer-img d-block"/> <span class="base-layer-title d-block">{{layer.title}}</span> but the title works fine. -
How to populate table based on the condition of another table's column value
I am kinda new in django and I am stuck. I am building and app to store equipment registry. I have done a model for equipment list and i have a status values as "available", "booked", "maintenance" I also have a model for all equipment that are not available. not in my html in the "not available registry" i want to show only details of equipment in the list that are marked as "booked" and "maintenance" -
How to delete uploaded image after running test in django?
Is this proper way to test image upload in django?? After i run test there is image files of test. How can i delete images after test finish running? my tests.py class CreateImageTest(APITestCase): def setUp(self): photo_file = self.generate_photo_file() self.image = { 'image': photo_file, 'alt_text': 'test_alt_txt' } def generate_photo_file(self): file = io.BytesIO() image = Image.new('RGBA', size=(100, 100), color=(155, 0, 0)) image.save(file, 'png') file.name = 'test.png' file.seek(0) return file def test_create_image(self): url = reverse('package:list_create_galleryimage') response = self.client.post(url,self.image, format='multipart') self.assertEqual(response.status_code, status.HTTP_201_CREATED) -
Having too many uwsgi OSError messages
Running a Django 3 python 3.6 application with uwsgi & nginx is throwing too many of these! I have been spending way too much time trying to figure it out, so any help is welcome. There are defintely not client disconnections. When looking online I find many uwsgi ini configurations and tried many of them, but to no avail. Most of them are HEAD requests from a country that has no business visiting the site, but there are many normal requests also getting this error. The messages look like this: Uwsgi log: Tue Sep 22 08:52:16 2020 - SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request / (ip x.xx.xx.xx) !!! Tue Sep 22 08:52:16 2020 - uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 306] during GET / (x.xx.xx.xx) OSError: write error [pid: 9852|app: 0|req: 6262/18763] x.xx.xx.xx () {46 vars in 981 bytes} [Tue Sep 22 08:52:15 2020] GET / => generated 0 bytes in 313 msecs (HTTP/1.1 200) 7 headers in 0 bytes (0 switches on core 0) Nginx access log: x.xx.xx.xx - - [22/Sep/2020:08:52:16 +0200] "GET / HTTP/1.1" 499 0 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.2 Mobile/15E148 … -
How to get the file object from a Django Post Request without using a form and save it to a model?
I am using a new FormData() and appending jsonvalue and a file to be sent in a POST request to Django backend . I can see the json data but not the file object in the backend. I am using Fetch API to post the request. <input id='fileid' type='file' hidden name="" @change="onFileChange"/> <textarea class="form-control" rows="3" placeholder="Add comments .." v-model="activeChatArea"></textarea> async replyComment(request_id) { var data = this.activeChatArea var attachment = this.activeFile console.log(attachment) this.activeChatArea = "" console.log(data) const csrfToken = this.getCookie('csrftoken') var formData = new FormData(); var file = $('#fileid').prop('files')[0]; console.log("FILE....") console.log(file) var jsonData = JSON.stringify({ request_id: request_id, comment: data, }) formData.append("fileData", file) formData.append("textData", jsonData) var response = await fetch("http://127.0.0.1:8000/comments/", { method: "POST", body: formData, headers: { 'X-CSRFToken': csrfToken }, }); var data = await response.json(); console.log("got comments") if (response.ok) { this.loadActiveChatMessages(request_id) console.log("COMMENT is OK") console.log(data) } else { console.log(response) } }, When I do a print(request.POST) then i can see the data like this : <QueryDict: {'textData': ['{"request_id":"8769c452-53f1-4f14-80b0-7d2818e133e6","comment":"sdfsdfsdfsdfsdf"}']}> When I do a print(request._files) then I can see something like this: <MultiValueDict: {'fileData': [<InMemoryUploadedFile: icons8-search-16.png (image/png)>]}> What I actually want to do is : I would manually like to create the model object and save it MyModel.objects.create(file=fileRecivedfromRequest,text=textRecvdfromRequest) -
NoReverseMatch: Reverse for 'RPA_tool' with arguments '('',)' not found. 1 pattern(s) tried: ['admin_tool/RPA_tool/(?P<Policy_Number>[^/]+)/$']
I am trying to create a dynamic URL in my Django App to redirect from the Search Page to RPA_Tool/<Policy_Number> When I attempt to load the search page, I receive the error Reverse for 'RPA_tool' with arguments '('',)' not found. 1 pattern(s) tried: ['admin_tool/RPA_tool/(?P<Policy_Number>[^/]+)/$'] I've tried swapping it to use datadisplay.Policy_ID, and that has successfully redirected to Policy_ID. However, when I change the hyperlink to datadisplay.Policy_Number, I receive the error. here is the HTML: <input type="text" id="myInput" onkeyup="searchTable()" placeholder="Search for Policy.."> <table class = "table"> <tr class="header"> <th>Policy ID</th> <th>Policy Numbers</th> </tr> <tbody id="myTable"> {% for datadisplay in Policies %} <tr> <td>{{datadisplay.Policy_ID}}</td> <td>{{datadisplay.Policy_Number}}</td> <td> <a class="btn btn-sm btn-info" href="{% url 'RPA_tool' datadisplay.Policy_Number %}"> Update </a> </td> </tr> {% endfor %} </tbody> </table> Views.py: def searchPolicies(request): Policies = getPolicyNumbers() myfilter = PoliciesFilter() context = {'myfilter': myfilter} return render(request, 'admin_tool/search.html', {'Policies':Policies, 'myfilter': myfilter}) def RPA_tool(request): if request.method == 'POST': form = RPA_tool_form(request.POST) if form.is_valid(): policyNumber = form.cleaned_data.get('Policy_Number') messages.success(request, f'{policyNumber} Saved') editRPADetails(form) return redirect('/admin_tool/') else: form = RPA_tool_form(initial={'Policy_Number':'Test'}) return render(request, 'admin_tool/RPA_tool.html', {'form':form}) urls.py: from django.urls import path from . import views # from users import views as user_views urlpatterns = [ # path('admin/', admin.site.urls), path('', views.home, name='UW-home'), path('admin_tool/', views.admin_tool, name ='admin_tool'), path('RPA_tool/<str:Policy_Number>/', views.RPA_tool, …