Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Render Django ForeignKey relation on Datatables Serverside
Im stuck for days, im using plugin django-datatables-view and I need to render ForeignKey related value in serverside datatables, it's like: {{data.pasien_id.name}} in typical django template. but that way not work with serverside datatables, and there is no documentation anywhere to achieve that. the code shown below. Models.py class Pasien(models.Model): nama = models.CharField(max_length=40, null=True) class Log_book(models.Model): pasien = models.ForeignKey(Pasien, on_delete=models.PROTECT, null=True) Views.py class logbook_json(BaseDatatableView): model = Log_book columns = ['id', 'pasien_id'] order_columns = ['id','pasien_id'] def render_column(self, row, column): if column == 'id': return escape('{0}'.format(row.id)) else: return super(logbook_json, self).render_column(row, column) def filter_queryset(self, qs): filter_customer = self.request.GET.get('search[value]', None) if filter_customer: customer_parts = filter_customer.split(' ') qs_params = None for part in customer_parts: q = Q(id__icontains=part) | Q(pasien_id__icontains=part) qs_params = qs_params | q if qs_params else q qs = qs.filter(qs_params) return qs templates.html datatables load, <script class="init" type="text/javascript"> $(document).ready(function () { $('#responsive-datatablex').DataTable({ // ... searching: true, processing: true, serverSide: true, stateSave: true, "ajax": "{% url 'logbook_json' %}", }); }); </script> -
Why after moving a .js script from html to .js file, it does not load the values?
I have a dropdown box which whenever I change its values, a js script forwards its responses to another dropdown. This script works when is inside the .html file, but once I move it to a seprate .js file it does not work. this is the code: $("#id_subtag-tags").change(function () { var tagId = $(this).val(); // get the selected tag ID from the HTML input console.log(tagId); $("#displaytags").html(''); $.ajax({ // initialize an AJAX request url: '{% url "ajax_load_subtags" %}', // set the url of the request (= localhost:8000/app/ajax/load_subtags/) data: { 'tags': tagId // add the tag id to the GET parameters }, success: function (data) { // `data` is the return of the `load_subtags` view function $("#id_subtag-subtags").html(data); // replace the contents of the subtags input with the data that came from the server } }); }); There is another function in the same file which is properly is being loaded to that html file, so I think problem is not in loading. I don't know what is causing this bug. The error I receive is: GET failed, ajax_load_subtags 404 (Not Found), url.py: path('myapp/post/ajax/ajax_load_subtags', load_subtags, name='ajax_load_subtags'), -
generate client_secret for sign in with apple using python 2.7 and django 1.9, giving me " JWSError: Could not deserialize key data"
login.py how i geberate client secret def generate_apple_client_secret(): secret = settings.SOCIAL_AUTH_APPLE_PRIVATE_KEY year = new_date_time.now().year month = new_date_time.now().month day = new_date_time.now().day now = int(datetime.datetime(year, month, day).strftime('%s')) headers = {"alg": 'ES256', "kid": settings.SOCIAL_AUTH_APPLE_KEY_ID} claims = { "iss": settings.SOCIAL_AUTH_APPLE_TEAM_ID, "iat": now, "exp": now + int(datetime.timedelta(days=180).total_seconds()), "aud": "https://appleid.apple.com", "sub": settings.CLIENT_ID } client_secret = jwt.encode( headers=headers, claims=claims, key=secret, algorithm='ES256' ) return client_secret Internal Server Error: /ar/api/social-login/ Traceback (most recent call last): File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/rest_framework/views.py", line 477, in dispatch response = self.handle_exception(exc) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/rest_framework/views.py", line 437, in handle_exception self.raise_uncaught_exception(exc) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/rest_framework/views.py", line 474, in dispatch response = handler(request, *args, **kwargs) File "/home/omar/PycharmProjects/Aswaq/oscarapi/views/login.py", line 285, in post user = self.login_with_apple(ser.instance.token) File "/home/omar/PycharmProjects/Aswaq/oscarapi/views/login.py", line 474, in login_with_apple client_secret = generate_apple_client_secret() File "/home/omar/PycharmProjects/Aswaq/oscarapi/views/login.py", line 649, in generate_apple_client_secret headers=headers, claims=claims, key=secret, algorithm='ES256' File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/jose/jwt.py", line 64, in encode return jws.sign(claims, key, headers=headers, algorithm=algorithm) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/jose/jws.py", line 50, in sign signed_output = _sign_header_and_claims(encoded_header, encoded_payload, algorithm, key) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/jose/jws.py", line 172, in _sign_header_and_claims raise … -
Bitbucket-Pipeline: How to automatically build and deploy a Django app docker image to Heroku or VPS
I'm new to docker and bitbucket pipelines so things a bit confusing at the moment when it comes to the practical implementation. I am looking for an existing walk-through (in a forum, book, article etc) about: "Bitbucket-Pipeline: How to deploy a docker image to Heroku" or, even better a source dealing with: "step by step: how to dockerize and deploy your django app via bitbucket pipelines to heroku and vps" I found one online using "Springbook" link and a shell script but I couldn't generalise it into django and docker-compose. Some posts say you cannot use docker-compose in bitbucket, and do I need to use a shell script? Any type of help or direction would be much appreciated at this stage of learning. -
Uncaught TypeError: $(...).select2 is not a function--Slect2 not working
I have include below listed js file in the head tag on an html page(index.html), after loading that page on a button click I append an html page to the current page(index.html) which contain an select box. but when i call select2 in his appended page am getting below error, Uncaught TypeError: $(...).select2 is not a function Please help to sove the issue. <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <script src="{% static 'reports/assets/plugins/bootstrap/popper.min.js' %}"></script> <script src="{% static 'reports/assets/plugins/bootstrap/js/bootstrap.min.js' %}"></script> <script src="{% static 'reports/assets/plugins/jquery-slimscroll/jquery.slimscroll.min.js' %}"></script> <script src="{% static 'reports/assets/plugins/chartjs/chart.min.js' %}"></script> <script src="{% static 'reports/assets/plugins/apexcharts/dist/apexcharts.min.js' %}"></script> <script src="{% static 'reports/assets/plugins/toastr/toastr.min.js' %}"></script> <script src="{% static 'reports/assets/js/lime.min.js' %}"></script> <script src="{% static 'reports/assets/js/pages/dashboard.js' %}"></script> <script src="{% static 'reports/assets/js/chart.js' %}"></script> <script src="{% static 'reports/assets/js/pages/charts.js' %}"></script> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/v/dt/jszip-2.5.0/dt-1.10.18/af-2.3.0/b-1.5.2/b-colvis-1.5.2/b-flash-1.5.2/b-html5-1.5.2/b-print-1.5.2/cr-1.5.0/fh-3.1.4/r-2.2.2/datatables.min.js"></script> <!-- needed to use moment.js for our date sorting--> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script> <!-- <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js" ></script> --> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.8/js/select2.min.js" ></script> <script src="{% static 'js/form_validate/jquery_validate.js' %}"></script> select2 initialized in the appended page, $(document).ajaxComplete(function() { $("select").select2(); }); Also this iisue was not there when am using select box directly in the main page itself. -
How to display a single form with Foreign Key and choices in a Django Form?
My goal is display a form with all theses fields, I'm stuck to display city and description field from City model, the first one needs to display a select box with all cities choices and the other just a text field. So, I need to display a form with this format: city (With selected box from all choices) description date status CITIES_CHOICES = (('RJ', 'Rio de Janeiro'), ('NY', 'New York'), ('PIT', 'Pittsburgh')) class City(models.Model): city = models.CharField(max_length=50, choices=CITIES_CHOICES) description = models.TextField() def __str__(self): return self.city class Checkin(models.Model): destination = models.ForeignKey(City, on_delete=models.SET_NULL) date = models.DateTimeField() status = models.BooleanField() I had create a form using Modelform but how can I display the fields from City model instead display de city object properly? Any idea where I need to go now? forms.py class DocumentForm(forms.ModelForm): class Meta: model = Checkin -
Use Prometheus next to Django and Gunicorn socket
I've deployed a Django project using gunicorn and Nginx following the Digital Ocean tutorial. Now, I'm trying to add Prometheus to monitor the performance of my application, but I'm not sure how to access the /metrics endpoint because using as a target ['localhost/metrics'] or ['localhost:8000/metrics'] values does not work. Can anyone help me, please? -
How to filter dates by range in Django Admin
class ExampleFunction(admin.ModelAdmin): list_display = ('user', 'date', 'task') list_filter = ('date',) The problem is that the builtin date filter don't let me insert a custom date, just pick some preset values like: Today, Last 7 days, ... -
Why did my Django app stop building in App Engine environment
Recently my app's deployment has stopped building and I cannot figure out why. My app is a simple app that does some calculations, I've followed deployment instructions and have the same settings from GC tutorial here. I am successfully pushing deployments but I think it is not building and launching Django. I have the Cloud Build API enabled. Any ideas on troubleshooting this would be appreciated -
I am facing issue to check answer and update user score card. my question(Objective or Descriptive type)
I am rendering one by one question from DB and using pagination for next(skip). In this model in add question ,customer and attempt question. Scoreboard models is class QuizTakers(models.Model): customer = models.ForeignKey(User, verbose_name=_("Customer"), null=True, on_delete=models.SET_NULL) questions = models.ForeignKey(Questions, verbose_name=_("Question"), on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, verbose_name=_("quiz"), on_delete=models.CASCADE) attempt = models.PositiveIntegerField() total_correct = models.PositiveIntegerField() question_type = models.TextField(blank=True) flag_question = models.TextField(blank=True) create_date = models.DateTimeField(_("Created timestamp"), auto_now_add=True) update_date = models.DateTimeField(_("Last update timestamp"), auto_now=True) question quiz view is: Maybe I am doing wrong in my view file because when i hit on post request then quiz page refresh and question start again.Please advise how to check every pagination next on answer and update on score board. def Quizsession(request): quiz = Quiz.objects.get(pk=request.session['quiz']) queries = [Q(topics__id=value.id) for value in quiz.topic.all()] query = queries.pop() for item in queries: query |= item ques_query = Questions.objects.filter(query).order_by('?')[:quiz.no_of_question] questions = ques_query count=questions.count() # PAGINATION =============================== page = request.GET.get('page', 1) paginator = Paginator(questions, 1) try: questions = paginator.page(page) except PageNotAnInteger: questions = paginator.page(1) except EmptyPage: questions = paginator.page(paginator.num_pages) context={ 'object_list': questions, 'page_obj': questions, 'count': count } if request.method =='POST': return redirect(reverse_lazy('forntend_panel:customer_quiz_start')) return render(request, 'test.html', context) -
Django-oscar manage users via dashboard
I'm not able on a fresh project with django-oscar to manage users using the dashboard(editing/deleting) - as superadmin I'm able only to see user details and also send reset password email. I didn't find any information about this. Also, I checked Django Oscar Dashboard User app and I don't see any view for this purpose. It's an easy way to handle editing/deleting users via the oscar dashboard? I can see the solution as creating a custom view for that but then I think having it just in the Django Admin will more efficient :) -
Authentication Creditial were not provided error in Django
I'm pretty new in django, especially django rest framework. so i tried to follow some instruction in the internet. but when I test it using Postman, it gives an error that says "detail": "Authentication credentials were not provided." in the json file. so what did I do wrong to be exact? -
Django : Type Error 'NoneType' object is not subscriptable
im making a product checkout page and im trying to access my cart items from the following util.py file. I have seen that lot of sites saying that the 'NoneType' object is not subscriptable error, means that i attempted to index an object that doesn't have that functionality. But i cant figure out what is wrong. The error occurs in the cartData function views.py from .utils import cartData def checkout(request): #call method from utils.py data =cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = { 'items': items, 'order': order, 'cartItems': cartItems } return render(request, 'store/checkout.html', context) utils.py def cookieCart(request): try: cart = json.loads(request.COOKIES['cart']) except: cart = {} print('Cart', cart) items = [] order = {'get_cart_total': 0, 'get_cart_items': 0, 'shipping': False} cartItems = order['get_cart_items'] for i in cart: # check if product exists try: cartItems += cart[i]['quantity'] product = Product.objects.get(id=i) total = (product.price * cart[i]['quantity']) order['get_cart_total'] += total order['get_cart_items'] += cart[i]['quantity'] item = { 'product': { 'id': product.id, 'name': product.name, 'price': product.price, 'imageURL': product.imageURL, }, 'quantity': cart[i]['quantity'], 'get_total': total } items.append(item) if product.digital == False: order['shipping'] = True except: pass return{'cartItems': cartItems, 'order': order, 'items': items} def cartData(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create( customer=customer, … -
Filter unique data in Django
Im having a trouble how to filter unique value in Django, let say I have this data from my database and I just want to filter the unique value Expected output should like this, and to filter this data to my select option China Denver Manila Tokyo Japan Usa Australia Brazil views.py def sample(request): country= Country.objects.all() formats = {'filter':country} return render (request,'sample.html',formats ) Is there any expert know about this? -
How to get and return a model instance by id using Django ModelForm when there is too many instances?
I have a ModelForm for an Inline and I am trying to accept an id of an instance and then get the instance and 'return it to the field' as the field is a ForeignKey field. I cannot use (Model)choicefield as there are thousands of instances which means it takes ages to load. Neither I can take for example a slice of the most recent objects and choose from those as it results in a cannot filter the queryset once a slice has been taken error. I have tried working around with the save method but I couldn't make it so far. (but it is my bet that this will be the way to go) I would like the form to take three ids and then get those instances by model.objects.get(id=id) and then somehow create a new instance. the code looks as follows; class AgregatorCrossSaleProductForm(forms.ModelForm): IsShown = forms.BooleanField(required=False) ParrentProductId = forms.IntegerField() ChildProductId_id = forms.IntegerField() CrossSaleProductTypeId = forms.IntegerField() class Meta: model = AgregatorCrossSaleProduct exclude = [] class AgregatorCrossSaleProductInline(admin.TabularInline): model = AgregatorCrossSaleProduct form = AgregatorCrossSaleProductForm ... Any tip would be much appreciated. Thank you in advance -
AttributeError 'tuple' object has no attribute 'get'
I have a Django application. But i have an error which i have been struggling with for some time now. Exception Value: 'tuple' object has no attribute 'get' Exception Location: C:\ProgramData\Anaconda3\lib\site-packages\django\middleware\clickjacking.py, line 26, in process_response Traceback django has provided me : File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\deprecation.py", line 116, in __call__ response = self.process_response(request, response) File "C:\ProgramData\Anaconda3\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: My View File : https://hasteb.in/ayafusug.py -
Cannot assign "<Customer: Customer object (2)>": "Order.customer" must be a "Product" instance
I am building an e-commerce website using django.Whenever i try to fill the checkout form and submit the form it shows me this error: "Cannot assign "<Customer: Customer object (2)>": "Order.customer" must be a "Product" instance." I am really confuse here I got stuck here Here is my Views.py for checkout : class Checkout(View): def post(self, request): fname = request.POST.get('fname') phone = request.POST.get('phone') address = request.POST.get('address') cart = request.session.get('cart') customer = request.session.get('customer') products = Product.get_products_id(list(cart.keys())) #print(fname, phone, address, products, cart, customer) for product in products: order = Order(customer=Customer(id=customer),product=product,fname=fname, price=product.price,phone=phone, address=address, quantity=cart.get(str(product.id))) order.save() request.session['cart'] = {} return redirect('cart') Here is my Models.py: from django.db import models import datetime # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name @staticmethod def get_categories(): return Category.objects.all() class Brand(models.Model): name= models.CharField(max_length=100) def __str__(self): return self.name def get_brands(): return Brand.objects.all() class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, default='UNCATEGORIZED') brand = models.ForeignKey(Brand, on_delete=models.CASCADE, default='NoBrand') price = models.FloatField() @staticmethod def get_all_products(): return Product.objects.all() @staticmethod def get_products_by_category(category_id): if category_id: return Product.objects.filter(category=category_id) else: return Product.get_all_products() @staticmethod def get_brands_by_products(brand_id): if brand_id: return Product.objects.filter(brand=brand_id) else: return Product.get_all_products() @staticmethod def get_products_id(ids): return Product.objects.filter(id__in=ids) class Customer(models.Model): phone_number = models.CharField(max_length=100, default=1) email = models.EmailField( default=1) password = models.CharField(max_length=100, default=1) … -
Why js script does not load ajax response? [duplicate]
I have a dropdown box which whenever I change its values, a js script forwards its responses to another dropdown. This script works when is inside the .html file, but once I move it to a seprate .js file it does not work. this is the code: $("#id_subtag-tags").change(function () { var tagId = $(this).val(); // get the selected tag ID from the HTML input console.log(tagId); $("#displaytags").html(''); $.ajax({ // initialize an AJAX request url: '{% url "ajax_load_subtags" %}', // set the url of the request (= localhost:8000/app/ajax/load_subtags/) data: { 'tags': tagId // add the tag id to the GET parameters }, success: function (data) { // `data` is the return of the `load_subtags` view function $("#id_subtag-subtags").html(data); // replace the contents of the subtags input with the data that came from the server } }); }); There is another function in the same file which is properly is being loaded to that html file, so I think problem is not in loading. I don't know what is causing this bug. The error I receive is: GET failed, ajax_load_subtags 404 (Not Found), -
Django throws MultiValueDictKeyError(key) error while recieving data with POST method
When I tried to pass the data using POST method. Django throws an error. The error is raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'fulldesc' I used postman to send post request. The data I have sent is as below IPHONE: 700 SAMSUNG: 600 ============= WALMART IPHONE: 699 =========== ALIBABA SONY: 500 ======``` The code I used is as below. What is the reason for error? def addData(request): if(request.method =='POST'): fulldesc = str(request.POST['fulldesc']) return HttpResponse('Done') -
Django throws MultiValueDictKeyError(key) error while recieving data with POST method
When I tried to pass the data using POST method. Django throws an error. The error is raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'fulldesc' I used postman to send post request. The data I have sent is as below IPHONE: 700 SAMSUNG: 600 ============= WALMART IPHONE: 699 =========== ALIBABA SONY: 500 ======``` The code I used is as below. What is the reason for error? def addData(request): if(request.method =='POST'): fulldesc = str(request.POST['fulldesc']) return HttpResponse('Done') -
unable to find some .py files of apps in django project
I want to ask about how can I access all ".py files" of all apps in my Django project. Actually, my developer is not responding to me I don't know why the last time he gave me my Django project in zip file. I have installed it successfully in my mac but now he is not responding to me but I have to work on the project by myself so I am worried about my Project. I have taken a screenshot of my project directory structure enter image description here installed apps portion of base.py file of settings looks like this. DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.humanize', ] THIRD_PARTY_APPS = [ 'rest_framework', 'polymorphic', #'django_extensions', 'apps.cabinet_extension.apps.CabinetConfig', #'cabinet', 'imagefield', 'easy_thumbnails', 'ckeditor', 'ckeditor_uploader', 'nested_inline', ] PROJECT_APPS = [ 'apps.core', 'apps.blog', 'apps.faq', 'apps.carty', 'apps.cart', 'apps.accounts.apps.UserConfig', ] INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + PROJECT_APPS And the URL pattern of urls.py file of azapp looks like this path('super-admin/', admin.site.urls), path('accounts/login/', auth_views.LoginView.as_view()), path('ckeditor/', include('ckeditor_uploader.urls')), path('', include('apps.core.urls')), path('blog/', include('apps.blog.urls')), path('faqs/', include('apps.faq.urls')), path('product/', include('apps.carty.urls')), path('cart/', include('apps.cart.urls')), please help me I am so worried about it Thanking in advance! -
Django unit-Testing authorization for API
I am using Django==3.0.3 djangorestframework==3.11.0 python ==3.6.8 django-oauth-toolkit==1.3.2 I already write my rest APIs . Now I want to write my Unit Test case but while writing test cases it showing unauthorized error Here my code tests.py import unittest from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse # Models imported from django.utils import timezone from end_device.models import Employee from oauth2_provider.models import Application, AccessToken, RefreshToken from rest_framework import status from django.test import Client class MyTestCase(TestCase): def setUp(self): self.client = Client() self.create_employee = Employee.objects.create(EmployeeName="Testcase2", EmployeeCode="1005", Security=0) self.user = User.objects.create_superuser(username="fdp", password="user12345") self.user_staff = User.objects.create_user(username="user", password="user12345") self.application = Application.objects.create( name="Test Application", user=self.user, client_id="123", client_secret="12345abc", client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_PASSWORD, ) self.access_token = AccessToken.objects.create( user=self.user_staff, scope="read write groups", expires=timezone.now() + timezone.timedelta(seconds=3000), token="123efrwasdd", application=self.application ) self.refresh_token = RefreshToken.objects.create( user=self.user_staff, token="refresh_token", application=self.application, access_token=self.access_token ) def test_employee(self): inputData = { "EmployeeName": "TestEmp", "EmployeeCode": "1007", "Security": 0 } header = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + format(self.access_token.token), } url = reverse('employee_entry') resp = self.client.post(url, data=inputData, headers=header) self.assertEqual(resp.status_code, status.HTTP_200_OK) My views.py @api_view(['POST']) @permission_classes([IsAuthenticated]) def employee_entry(request): try: login = User.objects.get(pk=request.user.id) validationmsg = '' emp_data = request.data employee = Employee( EmployeeName=emp_data["EmployeeName"].strip(), EmployeeCode=emp_data["EmployeeCode"].strip(), Security=emp_data["Security"], CreatedDate=date.today(), CreatedUser=login, ) employee.save() return Response({"EmployeeId": employee.EmployeeId}, status=status.HTTP_200_OK) except Exception as ex: logging.getLogger("error_logger").exception(repr(ex)) return Response({msg: validation["FDP23"]}, status=status.HTTP_400_BAD_REQUEST) … -
Paginator in a view function Django
I'm trying to add the paginate option on my posts page from my blog website. I want to implement the paginator on my view function that renders the page and I found this exemple from Django's doc but it doesn't work. Any help ? view function: def blog(request): posts = Post.objects.all().order_by('-date_posted') paginator = Paginator(posts, 2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'posts': posts, 'page_obj': page_obj, 'title': 'Blog', 'banner_page_title': 'Blog', 'page_location': 'Home / Blog' } return render(request, 'blog/blog.html', context) html rendering <nav class="blog-pagination justify-content-center d-flex"> <ul class="pagination"> {% if is_paginated %} {% if page_obj.has_previous %} <li class="page-item"> <a href="?page={{ page_obj.previous_page_number }}" class="page-link" aria-label="Previous"> <span aria-hidden="true"> <span class="ti-arrow-left"></span> </span> </a> </li> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <li class="page-item active"> <a href="?page={{ num }}" class="page-link">{{ num }}</a> </li> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <li class="page-item"> <a href="?page={{ num }}" class="page-link">{{ num }}</a> </li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li class="page-item"> <a href="?page={{ page_obj.next_page_number }}" class="page-link" aria-label="Next"> <span aria-hidden="true"> <span class="ti-arrow-right"></span> </span> </a> </li> {% endif %} {% endif %} </ul> </nav> the url route path('blog/', blog, name='blog'), -
Django createview m2m not saving
Trying to add the creator of team to the members automatically. Team model has a m2m relationship with UserProfile as members, here is the code: class CreateTeamView(generic.CreateView): model = Team template_name = 'team_create.html' fields = ('title', 'code', 'coordinator', 'description', 'members') success_url = '/teams' def form_valid(self, form): instance = form.save(commit=False) if not instance.creator: instance.creator = self.request.user.userprofile instance.save() instance.members.add(instance.creator) form.save_m2m() return super().form_valid(form) But it doesn't work. Team gets created and also the creator is assigned but doesn't get added to members. Please enlighten me. -
Django-admin start project <name> creates old version django project
I created a directory "DjangoProject1" and in it created django project through the terminal with the line $ django-admin startproject project As I was expected, there were created two things in the directory "project": file "manage.py" and another directory "project". The problem is that in that directory "project" there were: {init, setting, urls, wsgi}.py, but there wasn't file "asgi.py". From there I understood that there was created an old version django project. Again! I checked it one more time in "urls.py" file and I saw this: urlpatterns = [ url(r'^admin/', admin.site.urls), ] instead of this: urlpatterns = [ path('admin/', admin.site.urls), ] So it is definitely an old version of django project. I don't know why this problem occurs, as I installed a new version of django, and I was able to create new version django project, though I don't remember how I was doing that. Can anyone help me to liquidate this problem so that only new version django projects would be created? (PS before new version maybe I installed an old version, and probably in my computer now there are both: new and old versions of Django)