Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to generate a a value for a field based on other field on Django models?
I want to generate a value for name field based on the file field. class Files(models.Model): name = models.CharField(max_length=100, blank=True, null=True) file = models.FileField( upload_to=settings.RAW_IMAGE_UPLOAD_PATH, null=True, max_length=500 ) def name(self): return os.path.basename(self.file.name) def __str__(self): return self.name I am not successful when doing some Serialization/Deserialization. -
How to communicate with an external server using django application?
Currently I have a requirement,I need to communicate with external server using django application. The server is already up,Next section is the data transfer. I need some time samples and values from server and I need to send responses back to server. How django port can listen to external server.? How it can response back? I need asynchronous communication and REST responses -
Django dynamic URL tree
I'm new in Django and can't find a solution for my problem. How to make a dynamic URL tree in Django like - site.com/{categoryName}/{itemName}/ Now I have this URL tree: site.com/item/{itemSlug}/ site.com/category/{itemCategorySlug}/ But I need: site.com/{itemCategorySlug}/{itemSlug}/ How can I crate this URL tree without installing 3rd party plugins? Models from django.db import models from django.shortcuts import reverse from services.slug.generator import generate_slug class Category(models.Model): name = models.CharField(max_length=400, unique=True) description = models.TextField(max_length=1000, unique=True) slug = models.SlugField(max_length=500, unique=True, blank=True) seo_title = models.CharField(max_length=180, unique=True) seo_description = models.TextField(max_length=280, unique=True) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def get_absolute_url(self): return reverse('progress_category_url', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.id: self.slug = generate_slug(self.name) super().save(*args, **kwargs) def __str__(self): return self.name class Progress(models.Model): name = models.CharField(max_length=400, unique=True) description = models.TextField(max_length=1000, unique=True) slug = models.SlugField(max_length=500, unique=True, blank=True) seo_title = models.CharField(max_length=180, unique=True) seo_description = models.TextField(max_length=280, unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) tags = models.ManyToManyField(Tag) date = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=False) is_verified = models.BooleanField(default=False) profile = models.ForeignKey(Profile, on_delete=models.CASCADE, blank=True, null=True) promo_image = models.ImageField(upload_to='progress/promo_images/', null=True, blank=True) class Meta: verbose_name = 'progress' verbose_name_plural = 'progresses' def get_absolute_url(self): return reverse('progress_url', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.id: self.slug = generate_slug(self.name) super().save(*args, **kwargs) def __str__(self): return self.name Views from django.views.generic.list import ListView from … -
Django AUTH_LDAP_GROUP_SEARCH ObjectClass values from none to overkill
I have lil bit problem with my LDAP groups. i have: AUTH_LDAP_GROUP_SEARCH = LDAPSearchUnion( LDAPSearch("OU=U3,OU=UserGroups,OU=U1,OU=CompanyUsers,DC=ad,DC=net", ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)"), LDAPSearch("OU=Apps,OU=Security Groups,OU=Groups,OU=B2,OU=Tenants,DC=ad,DC=net", ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)")) ... AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() AUTH_LDAP_REQUIRE_GROUP = ( LDAPGroupQuery("CN=ENGINEER,OU=U3,OU=UserGroups,OU=U1,OU=CompanyUsers,DC=ad,DC=net") | LDAPGroupQuery("CN=READER,OU=U3,OU=UserGroups,OU=U1,OU=CompanyUsers,DC=ad,DC=net") | LDAPGroupQuery("CN=ADMIN,OU=Apps,OU=Security Groups,OU=Groups,OU=B2,OU=Tenants,DC=ad,DC=net")) AUTH_LDAP_USER_ATTR_MAP = {"first_name": "givenName", "last_name": "sn", "email": "mail"} I can login via LDAP user but it does not populating my groups (in admin view) Now when i change code to: AUTH_LDAP_GROUP_SEARCH = LDAPSearchUnion( LDAPSearch("OU=U3,OU=UserGroups,OU=U1,OU=CompanyUsers,DC=ad,DC=net", ldap.SCOPE_SUBTREE, "(objectClass=group)"), LDAPSearch("OU=Apps,OU=Security Groups,OU=Groups,OU=B2,OU=Tenants,DC=ad,DC=net", ldap.SCOPE_SUBTREE, "(objectClass=group)")) ... AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() AUTH_LDAP_REQUIRE_GROUP = ( LDAPGroupQuery("CN=ENGINEER,OU=U3,OU=UserGroups,OU=U1,OU=CompanyUsers,DC=ad,DC=net") | LDAPGroupQuery("CN=READER,OU=U3,OU=UserGroups,OU=U1,OU=CompanyUsers,DC=ad,DC=net") | LDAPGroupQuery("CN=ADMIN,OU=Apps,OU=Security Groups,OU=Groups,OU=B2,OU=Tenants,DC=ad,DC=net")) AUTH_LDAP_USER_ATTR_MAP = {"first_name": "givenName", "last_name": "sn", "email": "mail"} Itpopulates my groups with ALL groups in LDAP where member exists, we don;t want to do that, we only need to consider those 3 mentioned groups. Tried also with objectClass=top and it also populate with all LDAP groups that user has assigned. AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="CN") changes nothing in both cases -
How can one pass a json as a filter to a django query?
In below query, project_name contained in list ["ABC", "XYZ"], is coded as ('exact', 'in') query abcd { ple_presets { all_preset (filter: {project_name__in: ["ABC", "XYZ"], extra: {context1: a, context2:b}}) { edges { node { ...fields } } } } } Question is, for a json to be passed as a filter - 'extra', what should come here <==== class PlePreset(DjangoObjectType): class Meta: model = presets.Preset interfaces = (Node,) filter_fields = { 'project_name': ('exact', 'in',), 'extra': (.....) <===== } -
Django Rest Framework, TypeError: __init__() takes 1 positional argument but 2 were given
Models.py: class Bookmark(models.Model): """Bookmar for a quiz""" quiz = models.ForeignKey( Quiz, on_delete=models.PROTECT, verbose_name='Викторина', related_name='bookmarks' ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='Пользователь', related_name='bookmarks' ) date = models.DateTimeField(auto_now_add=True, verbose_name='Дата добавления') def __str__(self): return f'{self.user} - {self.quiz}' Urls.py: urlpatterns = [ path('quiz/bookmark/create-remove/<slug:slug>/', views.CreateRemoveBookmarkAPI, name="bookmark-create-remove-api"), ] Views.py: class CreateRemoveBookmarkAPI(APIView): """API for create or remove quiz bookmark. Get a quiz slug, and create or remove bookmark at it """ permission_classes = (IsAuthenticated,) def post(self, request, slug): quiz = get_object_or_404(Quiz, slug=slug) bookmark = Bookmark.objects.filter(quiz=quiz, user=request.user) data = {} if bookmark.exists(): bookmark.delete() data['bookmarked'] = False else: Bookmark.objects.create(quiz=quiz, user=request.user) data['bookmarked'] = True data['bookmarks'] = quiz.get_bookmarks_count() return Response(data, status=status.HTTP_200_OK) I got it: Internal Server Error: /api/quiz/bookmark/create-remove/dd-69/ Traceback (most recent call last): File "C:\Users\user\Desktop\quizapp\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\user\Desktop\quizapp\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\user\Desktop\quizapp\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: __init__() takes 1 positional argument but 2 were given [05/Mar/2020 12:04:33] "POST /api/quiz/bookmark/create-remove/dd-69/ HTTP/1.1" 500 21733 In front-end, I just send ajax request. The data attribute is empty because it doesn't matter. I don't know why it doesn't work. Please help me. gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg -
Pass uploaded excel file data to python via ajax
I currently have a choose file option in which a user can upload an excel file. Following is the code. HTML <div class="col-md-6"> Upload excel <input type="file" id="file_upload" class="file_upload"> <button type="button" id="upload_submit" class="btn btn-primary upload_submit">Upload</button> </div> JS $("body").on("click", ".upload_submit", function () { // debugger var filepath = $("#file_upload").val() }) I am trying to extract the file-path and send the path to python so that i can do my operations in the back end. but I am getting the path as 'C:\fakepath\dummy_data.xls' After some googling, I came to know that latest browsers restrict revealing the users directory from the client side. So, Pls suggest, how do i send this excel data to my python function in the back end? -
Django: how to set pagination?
here i tried django default pagination in my views but that's does not worked for me. i want to make a custom pagination as per my code. it would be great if anybody could help me where i made mistake in my code. from rest_framework.pagination import PageNumberPagination class DefaultResultsSetPagination(PageNumberPagination): page_size = 2 page_size_query_param = 'page_size' max_page_size = 100000 class Order_ListAPIView(APIView): pagination_class = DefaultResultsSetPagination def get(self,request,format=None): if request.method == 'GET': cur,conn = connection() order_query = ''' SELECT * FROM orders''' order_detail_query = ''' SELECT * FROM order_details''' ... ... #rest_code ... return Response({"order_data":order_data},status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) -
Query regarding django forms
I'm trying to make a form using Django which consists of a question and different possible answers(radio button options). So my question is how can I give weightage(score) to different options and store it in the database? -
django return render popup message
i have this code in my views.py that inserting record to the database for desc in request.POST.getlist('coredescription'): coredescription = CoreValuesDescription(id=desc) V_insert_data = StudentsCoreValuesDescription( Teacher=teacher, . . . ) V_insert_data.save() m=+1 **return render (messages.success(request, 'Profile details updated.'))** this is my html {% if messages %} <ul class="messages"> {% for message in messages %} <li>{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} I just want that if the user add record, popup message appeard -
filter and edit model_set of object and return query set of that object in one to many relation in django
Overview: I have two models that there is one-to-many relationship between them.I want to get a search QuerySet of Exams that has questions with text that contains 'Question1' but question_set of these Exams should be limited to my search value;it means that questions with text 'Question2' should not appear in question_set of these Exams.(I mean question_set of these Exams should be filtered or edited too) my models are : models.py : class Exam(models.Model): name = models.CharField(max_length=50) level = models.CharField(max_length=10) type = models.CharField(max_length=20) city = models.ForeignKey(City, on_delete=models.CASCADE) class Question(models.Model): text = models.CharField(max_length=400, default='how are you?') exam = models.ForeignKey(Exam, on_delete=models.CASCADE) In Database , text of Question object contains only 'Question1' or 'Question2' now I want to get Exams that text of questions in question_set of them contains 'Question1' so I use this code : Exam.objects.filter(question__question_text__icontains='Question1') If I use this code I get Exams but in question_set of these Exams also there is some questions with question_text that constains 'Qusetion2' but I want just questions that contains 'Question1' so It's not correct result. I need to filter question_set of Exams too. so I used this code: Exam.objects.filter(question__question_text__icontains='Question1')[i].question_set.all().filter(question_text__icontains='Question1') But the problem is that the output of this code is QuerySet of Question model but … -
How to get Django LoginRequiredMixin working?
I'm working with Django 3 and I would like to restrict my views only to logged-in users. So I decided to implement Djangos method of LoginRequiredMixin, to controll access to my whole view. But this is not working in my view. class UsersView(LoginRequiredMixin, View): def user_list(request): users = adg_users.objects.all() return render(request, 'care/user/users.html', {'users': users}) The view is still open, although I'm not logged in. What could be the problem here? What do I have to do to make it working? -
Not Able to load my static files after connecting Gcloud bucket with Django App
I have a Django App on which i have set the default file storage to my bucket in my google cloud console and also set the other required environment variables in my settings.py like this DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'agevent-269406.appspot.com' STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_ACCESS_KEY_ID = 'GOOG1EZ5NIIEKVXTIEUN44APX3R5RQZBKPCY2QZLKNVVWO4CXKS4CUBGNDJCI' GS_SECRET_ACCESS_KEY = 'u92B3tGHGgul8sOzkQ40hIgKBsVAZw7N5UxlrsRP' GS_CREDENTIALS = service_account.Credentials.from_service_account_file( "agevent-518288d70053.json" ) And i have also manually uploaded my static folder (inlcluding all files) to my bucket. Currently im using these variables in my settings.py for static files STATIC_URL = 'https://storage.googleapis.com/agevent-269406.appspot.com/face_detector/static/' STATIC_ROOT = 'static' and in my app.yaml im using these values for static - url: /static static_dir: https://storage.googleapis.com/agevent-269406.appspot.com/face_detector/static/ But the problem is when my django app loads on the GAE server, my static files do not load neither the images nor the styling files. I am quite a rookie in python and gae so please suggest me some basic answers for all those steps i have done, i followed the following link https://django-storages.readthedocs.io/en/latest/backends/gcloud.html#installation -
Django MongoDB SQLDecodeError at /admin
I'm getting SQLDecodeError in Django admin panel when I'm trying to view any model or trying to create document in the collection. I'm using - MongoDB - v3.6.3 django - v3.0.4 djongo - v1.3.1 sqlparse - v0.3.1 I have tried different versions of sqlparse but nothing seemed to work. How can i make this work ? -
How to communicate with an external server using django application?
Currently I have a requirement,I need to communicate with external server using django application. The server is already up,Next section is the data transfer. I need some time samples and values from server and I need to send responses back to server. How django port can listen to external server.? How it can response back continuosly? -
django rest, forbidden 403 error in ajax call
I am going to post data via ajax but it returns an error with 403 status code. i am using rest api for this My Create View class CityCreateAPIView(generics.CreateAPIView): queryset = models.City.objects.all() serializer_class = serializers.CitySerializer In template <form action="" method="post"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="form-group"> <label for="">name (en)</label> <input id="name_en" type="text" name="name_ru" class="form-control"> </div> <div class="form-group"> <label for="">name (ru)</label> <input id="name_ru" type="text" name="name_ru" class="form-control"> </div> </div> <div class="modal-footer"> <button id="saveButton" data-api="{% url 'city-create-api' %}" type="button" class="btn btn-primary">Save changes </button> </div> </form> JavaScript $("#saveButton").click(function (event) { event.preventDefault(); let cityFormData = new FormData(); cityFormData.append(`name_en`, $('#name_en').val()); cityFormData.append(`name_ru`, $('#name_ru').val()); $.ajax({ url: $(this).data('api'), data: cityFormData, processData: false, contentType: false, type: "POST", success: function (data) { }, error: function (data) { } }); }); Here i have tried so far but again I am taking an error. How can i solve this issue? Thanks in advance! P.S I looked at possible solutions and tried some of them but they did not help me -
mysql not connecting into django
I am working on django. it is working good. but now i have to connect mysql database into django. in local system i install all things realted packages. but in virtual enviornment I am getting so much error. I am working on django. it is working good. but now i have to connect mysql database into django. in local system i install all things realted packages. but in virtual enviornment I am getting so much error. I used this command and getting same errors. pip install mysqlclient pip3 install mysqlclient can you suggest me how can i fixed this errors. (venv) palwesh@wg-palwesh:~/Workplace/learn/task2$ pip3 install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.4.6.tar.gz (85 kB) Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/webgen-palwesh/Workplace/learn/venv/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-xd1syfgb/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-xd1syfgb/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-la3lzm0o cwd: /tmp/pip-install-xd1syfgb/mysqlclient/ Complete output (31 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.6/MySQLdb copying … -
AttributeError: 'NoneType' object has no attribute 'find' - Apache Django
I am trying to run a django framework application from apache but getting the error AttributeError: 'NoneType' object has no attribute 'find' The connection is working fine from virtual environment but from apache there is intermittent db connection issue File "/TomCatWeb/app/projects/GDM/customer/db.py", line 13, in connection [Thu Mar 05 06:45:12.194252 2020] [wsgi:error] [pid 68520] try: [Thu Mar 05 06:45:12.194258 2020] [wsgi:error] [pid 68520] AttributeError: 'NoneType' object has no attribute 'find' below is the code for db connection import logging import os import cx_Oracle logging.basicConfig(filename='/TomCatWeb/app/projects/GDM/customer/db.log', filemode='w', format='%(asctime)s - %(message)s', level=logging.DEBUG) os.environ['GDM_CUSTOMERS']="<host details>" def connection(): try: host = os.getenv('GDM_CUSTOMERS') con = cx_Oracle.connect(host) driver = con.cursor() return driver except cx_Oracle.DatabaseError as e: logging.debug(e) return 0 -
Get functionality of form in include tag of django template
I have been trying to render the a form in multiple templates. In one of my trials I used include tag to render the form. Below is my function for the form- It sends a mail once the form is submitted. views.py def myformfunction(request): if request.method == 'GET': form = myform() else: form = myform(request.POST) if form.is_valid(): subject='form Details' mobile = form.cleaned_data['mobile'] email = form.cleaned_data['email'] dummy = '\nMobile: '+mobile+'\nEmail: '+email' try: send_mail(subject, dummy, 'dummy@gmail.com', ['dummy1@gmail.com', 'dummy2@gmail.com']) messages.success( request, " Thank you !! For contacting.') except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('email') return render(request, "my_app/email.html", {'form': form}) In one of my templates I am calling the the above as include tag. Below is the code. template1.html <form method="post" action="{% url 'frform' %}"> #if I am not adding the action, I am unable to finish the action of sending the mail {% include 'my_app/email.html' %} </form> email.html <div class="p-4 shadow-lg rounded-lg bg-white"> {% if messages %} <ul class="messages"> {% for message in messages %} {% if message.tags %} <script>alert("{{ message }}")</script> <a href="{{request.META.HTTP_REFERER|escape}}">Back</a>{% endif %} {% endfor %} </ul> {% else %} <h5 class="h6 mb-4">Create test Form</h5> <form method="post" action="{% url 'frform' %}"> {% csrf_token %} {{ form }} <button type="submit" … -
Django Routing caused Module not found error
While defining path from Django project (eitan) to Djnago app (users_and_auth) I get this below mentioned error. app/eitan/__init__.py changed, reloading. eitan-application_1 | Watching for file changes with StatReloader eitan-application_1 | Performing system checks... eitan-application_1 | eitan-application_1 | Exception in thread django-main-thread: eitan-application_1 | Traceback (most recent call last): eitan-application_1 | File "/usr/local/lib/python3.7/threading.py", line 926, in _bootstrap_inner eitan-application_1 | self.run() eitan-application_1 | File "/usr/local/lib/python3.7/threading.py", line 870, in run eitan-application_1 | self._target(*self._args, **self._kwargs) eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper eitan-application_1 | fn(*args, **kwargs) eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run eitan-application_1 | self.check(display_num_errors=True) eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 395, in check eitan-application_1 | include_deployment_checks=include_deployment_checks, eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 382, in _run_checks eitan-application_1 | return checks.run_checks(**kwargs) eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks eitan-application_1 | new_errors = check(app_configs=app_configs) eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config eitan-application_1 | return check_resolver(resolver) eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver eitan-application_1 | return check_method() eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 406, in check eitan-application_1 | for pattern in self.url_patterns: eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ eitan-application_1 | res = instance.__dict__[self.name] = self.func(instance) eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 587, in url_patterns eitan-application_1 | patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) eitan-application_1 | … -
Django: how to show name as per user_id?
class Order_ListAPIView(APIView): def get(self,request,format=None): totalData=[] if request.method == 'GET': cur,conn = connection() order_query = ''' SELECT * FROM orders ''' order_detail_query = ''' SELECT * FROM order_details ''' user_query = ''' SELECT * FROM users ''' with conn.cursor(MySQLdb.cursors.DictCursor) as cursor: cursor.execute(order_detail_query) order_detail_result = cursor.fetchall() order_detail_data = list(order_detail_result) # print(order_detail_data) cursor.execute(order_query) order_result = cursor.fetchall() order_data = list(order_result) cursor.execute(user_query) user_result = cursor.fetchall() user_data = list(user_result) dic = {} def merge_order_data_and_detail(order_data, order_detail_data): for d in order_detail_data: if d['order_id'] not in dic: dic[d['order_id']] = [] dic[d['order_id']].append(d) for o in order_data: if o['order_id'] in dic: o['order_detail_data'] = dic[o['order_id']] merge_order_data_and_detail(order_data, order_detail_data) # totalData.append({"order_data":order_data, }) return Response({"order_data":order_data, "user_data":user_data},status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) Output: { "order_data": [ { "order_id": 1, "payment_method_id": 1, "delivery_id": 2, "user_id": 3, "txnid": "584ffb7fd622eca10a6d", "order_no": "1-1583152683-0005", "order_total": 1.0, "payment_status": "Paid", "payuMoneyId": "306043618", "mihpayid": "9956109007", "order_detail_data": [ { "order_detail_id": 1, "order_id": 1, "user_id": 3, "qty": 1, "product_price": 1.0, "order_item_status": "Placed", "feedback": "" } ] }, { "order_id": 2, "payment_method_id": 2, "delivery_id": 2, "user_id": 2, "txnid": "", "order_no": "1-1583152785-0010", "order_total": 1.0, "payment_status": "Unpaid", "payuMoneyId": "", "mihpayid": "", "order_detail_data": [ { "order_detail_id": 2, "order_id": 2, "user_id": 2, "qty": 1, "product_price": 1.0, "order_item_status": "Cancelled", "feedback": "0" } ] }, { "order_id": 3, "payment_method_id": 1, "delivery_id": 2, "user_id": 1, "txnid": … -
GeoDjango field in admin not show the street name, how to enable it?
I am integration the map display into django admin by using GeoDjango plugin. model.py class Listing(gismodels.Model): #... geolocation = gismodels.PointField() Latitude = models.DecimalField(max_digits=10, decimal_places=6, default=11.5627939) Longitude = models.DecimalField(max_digits=10, decimal_places=6, default=104.9210989) objects = GeoManager() admin.py class ListingAdmin(admin.GeoModelAdmin): list_display = ('id', 'title', 'is_published', 'price', 'list_date', 'realtor') list_display_links = ('id', 'title') list_filter = ('realtor',) list_editable = ('is_published',) search_fields = ('title', 'description', 'address', 'city', 'state', 'zipcode', 'price') list_per_page = 25 default_lon = 104.9210989 default_lat = 11.5627939 default_zoom = 13 readonly_fields = ('Latitude', 'Longitude') admin.site.register(Listing, ListingAdmin) But I got the output like this (no street or address name in the mape) : -
Scope of returned resource highly depandant on user role encoded in JWT token - is it RESTful?
I'm working on API that tries to stay in RESTful principles, although one requirement keeps bugging me. We use JWT based authentication. Inside JWT claims we store roles of the user. Now our main GET endpoint (let's call it ListAllOffers for simplicity) behaves differently depending on what role the user have: if API recognizes admin via JWT it responds with full list of Offers if API recognizes ordinary user via JWT it responds with narrowed list of Offers (depending on relation in DB) My concerns is: is it ok according to REST principles or any unwritten REST practices? I am used to modify response object according to argument from url, params from querystring or alternatively via header values. Altering JSON response basing JWT seems not explicit enough that is feels some kinda strange. Bonus question: is it against any of REST principles how should this requirement be implemented. -
Which is good? django-tenants vs django-tenant-schemas
Hey guys I just came up with 2 different tenant management libs in Django https://github.com/bernardopires/django-tenant-schemas and https://github.com/tomturner/django-tenants. Which one will be better? Is any other libs better than these two? -
countdown in django using keith wood countdown timer
I am using keith wood countdown, How do i set the default countdown to (14 days) and it will start when after the user login to their profile, and the countdown will still continue even if the user logout or leave the page? <div id="defaultCountdown"></div> <script> $(function () { var austDay = new Date(); austDay = new Date(austDay.getFullYear() + 1, 1 - 1, 26); $('#defaultCountdown').countdown({until: austDay}); $('#year').text(austDay.getFullYear()); }); </script>