Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
search data using ajax and django and redirect to related pages
I am building a website and I want to implement searching. I want the user to enter some text and want to show suggestions using ajax. when the user click on specific product or category I want to redirect the user to related page. Here is what I have done so far: $(function () { $("#search").autocomplete({ source: "{% url 'ajax-search' %}", select: function (event, ui) { //item selected AutoCompleteSelectHandler(event, ui) }, minLength: 5, }); }); <div class="search"> <label for="search"></label> <input type="text" oninput="" style="height: 36px" class="searchTerm" placeholder="What are you looking for?" name="searchtext" id="search"> <button type="submit" class="searchButton"> <i class="fa fa-search"></i> </button> </div> path('ajax/search', views.autocompleteModel, name='ajax-search'), def autocompleteModel(request): if request.is_ajax(): q = request.GET.get('term', '') lookups = Q(name__icontains=q) | Q(category__name__icontains=q) products = Product.objects.filter(lookups).distinct() results = [] for product in products: place_json = {} place_json = product.name product_url = 'prodcuts/product/' + str(product.id) results.append(place_json) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) -
Django REST Framework internal value
I have a simple serializer with a date field (not ModelSerializer). class MySerializer(Serializer): some_date = DateField() I'm trying to access the date object after deserialization. slz = MySerializer(data={"some_date": "2020-05-03"}) # I surely have a better error handling in my actual code assert slz.is_valid() some_extracted_date = slz.data["some_date"] I would like my variable some_extracted_date to be a datetime.date instance. But the value in the MySerializer.data dict is a string. Is there a way to get this datetime.date instance ? -
How to dynamically set the limit_value of the build-in MinValueValidator inside a Django 3.1 ModelForm
I'm trying to dynamically set the limit_value of the build-in MinValueValidator inside a Django 3.1 ModelForm. The below code works for a fixed limit_value of 10 (see line 21 in views.py). models.py from django.contrib.auth.models import AbstractUser from django.db import models class Bid(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="bids") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bids") bid = models.DecimalField(decimal_places=2, max_digits=9) views.py from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django import forms from .models import User, Listing, Category, Bid from django.db.models import Max from decimal import Decimal, DecimalException from django.core.validators import MaxValueValidator, MinValueValidator from django.core.exceptions import ValidationError class NewBidForm(forms.ModelForm): class Meta: model = Bid fields = '__all__' widgets = { 'user': forms.HiddenInput(), 'listing': forms.HiddenInput(), } def __init__(self, *args, **kwargs): super(NewBidForm, self).__init__(*args, **kwargs) self.fields['user'].show_hidden_initial=True self.fields['listing'].show_hidden_initial=True self.fields['bid'].validators=[MinValueValidator(10)] def clean(self): if 'user' in self.changed_data or 'listing' in self.changed_data: raise forms.ValidationError('Non editable field have changed!') return self.cleaned_data def index(request): listings = Listing.objects.all() return render(request, "auctions/index.html", { "listings" : listings, }) def listing(request, listing_id): if request.method == 'POST': data = request.POST form = NewBidForm(data) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("index")) else: listing = Listing.objects.get(pk=listing_id) bids = Bid.objects.filter(listing=listing) if bids: highest_bid = bids.aggregate(Max('bid'))['bid__max'] else: highest_bid … -
How to access form field in html class
I am building a BlogApp and I am trying to customize the FileUpload button. What i am trying to do I am trying to customize the File Upload button using CSS button , I am unable to access it with my model instance ( {{ form.file}} ) CSS .btn-upload { position: relative; overflow: hidden; display: inline-block; } .btn-upload input[type=file] { position: absolute; opacity: 0; z-index: 0; max-width: 100%; height: 100%; display: block; } .btn-upload .btn{ padding: 8px 20px; background: #337ab7; border: 1px solid #2e6da4; color: #fff; border: 0; } .btn-upload:hover .btn{ padding: 8px 20px; background: #2e6da4; color: #fff; border: 0; } #This is my image field by {{ form.image }} in template HTML {{ form.file}} What have i tried I tried using this <input type="file" name="file" class="btn-upload"> BUT it didn't worked for me. Any help would be really Appreciated. Thank You in Advance. I tried many time by adding classes and ids but none of them worked for me. I don't how can i -
Regarding Django runserver issue [closed]
My Django runserver does not start while start to create project and does not show any error messages also while I am using pyrated windows 10.Please help me resolve my problem. -
Dynamic Command for Kubernetes Jobs
So hopefully this makes sense to the non-Djangoers of the k8s community. I will try my best to explain the setup / reasoning. With Django, we have LOTS of what are called management commands that we can run within the scope and environment of our Django app that can really help development and deployment. I'm sure most other frameworks have similar, if not identical, concepts. An example would be the "python manage.py migrate" command that ensures our codebase (migration scripts) are applied to and reflect in the associated database. There are approx. 30 - 50 core commands we can run, we can also create our own, as well as apply those from any installed third party applications. Anyways. The most important takeaway is that there are a lot of commands we can and do run. Now, I have the following k8s Job to run the "migrate" command: apiVersion: batch/v1 kind: Job metadata: name: asencis-web-migrate-job spec: template: spec: containers: - name: asencis-web-migrate-job image: asencis/asencis-base:latest imagePullPolicy: Always command: ['python', 'manage.py', 'migrate'] envFrom: - configMapRef: name: asencis-config - secretRef: name: asencis-secret restartPolicy: Never backoffLimit: 5 This job essentially runs the python manage.py migrate command within the application scope/environment. It works like a charm: … -
Best way to re/use redis connections for prometheus django exporter
I am getting an error redis.exceptions.ConnectionError: Error 24 connecting to redis-service:6379. Too many open files. ... OSError: [Errno 24] Too many open files I know this can be fixed by increasing the ulimit but I don't think that's the issue here and also this is a service running on a container. The application starts up correctly works for 48 hours correctly and then I get the above error. Which implies that the connections are growing over time exponentially. What my application is basically doing background_task (ran using celery) -> collects data from postgres and sets it on redis prometheus reaches the app at '/metrics' which is a django view -> collects data from redis and serves the data using django prometheus exporter The code looks something like this views.py from prometheus_client.core import GaugeMetricFamily, REGISTRY from my_awesome_app.taskbroker.celery import app class SomeMetricCollector: def get_sample_metrics(self): with app.connection_or_acquire() as conn: client = conn.channel().client result = client.get('some_metric_key') return {'some_metric_key': result} def collect(self): sample_metrics = self.get_sample_metrics() for key, value in sample_metrics.items(): yield GaugeMetricFamily(key, 'This is a custom metric', value=value) REGISTRY.register(SomeMetricCollector()) tasks.py # This is my boilerplate taskbroker app from my_awesome_app.taskbroker.celery import app # How it's collecting data from postgres is trivial to this issue. from my_awesome_app.utility_app.utility … -
my code keeps showing me this error 404: the current path,get, didn't match any of these
this is my code I don't know where the error is coming from. It is telling me that Using the URLconf defined in ehiz.urls, Django tried these URL patterns, in this order: admin/ [name='home'] add/ [name='add'] The current path, get, didn't match any of these. Views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request,'base.html',{'name':'Gael'}) def add(request): val1 = int(request.GET['num1']) val2 = int(request.GET['num2']) res = val1 + val2 return render(request, 'result.html',{'result':res}) base.html {% extends 'main.html' %} {% block content %} <h1>hello {{name}}</h1> <form action="get"> <input type="text" name="num1" placeholder="Enter first number"><br> <input type="text" name="num2" placeholder="enter second number"><br> <input type="submit"> </form> {% endblock %} result.html {% extends 'main.html' %} {% block content %} the result is : {{result}} {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path('',views.home,name='home'), path('add/',views.add,name='add') ] -
How can I solve the error "page not found(404)" in my 1st django project?
I'm very new to django and I stuck in my first project the error says Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/about using the URLconf defined in emuhay.urls, Django tried these URL patterns, in this order: admin/ The current path, about, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I'm expecting "Contat page" but page not found displayed every time my code is below #Url code from django.contrib import admin from django.urls import path from django.http import HttpResponse def home(request): return HttpResponse('Home Page') def contact(request): return HttpResponse('Contact Page') urlpatterns = [ path('admin/', admin.site.urls), path('',home), path('about/',contact), ] #setting.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'yra+iwr3x_)@ssxj)e%h^7=m(te0mh!_4xx61g7j2j4y)o9z&$' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hihi', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = … -
django.core.exceptions.FieldError: Cannot compute Sum('<CombinedExpression: F() + F()): is an aggregate
I have a code: k = company.departments.all().annotate( net_pay_amount_sum=Sum('employees__payments__net_pay_amount'), earnings_sum=Sum('employees__payments__earnings__amount'), taxes_sum=Sum('employees__payments__taxes__amount'), ).annotate( total_sum=Coalesce(ExpressionWrapper( Sum(F('net_pay_amount_sum') + F('earnings_sum') + F('taxes_sum')), output_field=fields.DecimalField()), 0) ).values_list('name', 'total_sum') and when I run it I got exeption: django.core.exceptions.FieldError: Cannot compute Sum('<CombinedExpression: F(net_pay_amount_sum) + F(earnings_sum) + F(taxes_sum)>'): '<CombinedExpression: F(net_pay_amount_sum) + F(earnings_sum) + F(taxes_sum)>' is an aggregate Can someone tell me how can I sum this withot exeptions Sum(F('net_pay_amount_sum') + F('earnings_sum') + F('taxes_sum')), -
Django textarea form
i need to set rows and cols for a textarea in my HTML page from Django but it doesnt work. I already put rows and cols in mine form Views.py class EditForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={'name':'title'})) body = forms.CharField(widget=forms.Textarea(attrs={'name':'body', 'rows':3, 'cols':5})) def new(request): return render(request,"encyclopedia/handlepage.html", { "title": "CREATE NEW PAGE", "edit": False, "editpage": EditForm() }) handlepage.html {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} {% endblock %} {% block body %} <h1>{{title}}</h1> <a href="https://guides.github.com/features/mastering-markdown/">Markdown guides</a> {% if edit %} //Useless right now {% else %} <form method="POST" action="{% url 'save' %}"> <input type="submit" value="SAVE ENTRY"><br> {% csrf_token %} {{ editpage }} </form> {% endif %} {% endblock %} Then my page should have a small text area but it have the same size independent by its row and cols like this -
Object of type 'RecursionError' is not JSON serializable
Comparing length of two files and if not equal insert def compare(length, initial_val) i = initial_val if i == length: return 1 else: tags_extracted_from_template = re.findall(r'<[^>]+>', str(file1_list[i])) tags_extracted_from_user_form = re.findall(r'<[^>]+>', str(file2_list[i])) if "".join(tags_extracted_from_template) != "".join(tags_extracted_from_user_form): file2_list.insert(i, "".join(tags_extracted_from_template)) return compare(len(file2_list),0) print(file2_list) return compare(len(file2_list), i + 1) if len(file1_list) != len(file2_list): compare(len(file2_list), 0) print("Final Length", len(file2_list)) -
lauching pipenv shell creates a subshell in the wrong directory
MacBook-Pro-van-Ferry:voorbeeld ferryholzhaus$ pipenv shell Launching subshell in virtual environment... . /Users/ferryholzhaus/.local/share/virtualenvs/ferryholzhaus-AnfvKXxr/bin/activate Restored session: vr 19 mrt 2021 11:52:49 CET ferryholzhaus@MacBook-Pro-van-Ferry ~ % . /Users/ferryholzhaus/.local/share/virtualenvs/ferryholzhaus-AnfvKXxr/bin/activate (ferryholzhaus) ferryholzhaus@MacBook-Pro-van-Ferry ~ % -
django-taggit only allow current tags for users
I have not been able to find any related questions on this. I have a create-post page where i want users to only be able to pick between current tags(could be done using scroll-down button) and not be able to create their own tags when creating a post. my approach so far has been trying to set the tag field with values of the link im pressing in the scroll down button. Image 4 shows the tag options where i want to display the tag name on the tag model field when that specific tag name is pressed on the scroll down button. images of my code: [models.py][1] [form.py][2] [views.py][3] [my create post page][4] [1]: https://i.stack.imgur.com/YafQ3.png [2]: https://i.stack.imgur.com/OnQF9.png [3]: https://i.stack.imgur.com/K3M6Z.png [4]: https://i.stack.imgur.com/yA2I4.png -
Django project deploy on Heroku failed
After I successfully deployed my Django project to Heroku, the page didn't show anything but the application error. It suggest me use the command to find the problem: heroku logs --tail and it shows lines of error, and here's part of them: 2021-03-19T10:06:26.966003+00:00 app[web.1]: Traceback (most recent call last): 2021-03-19T10:06:26.966003+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2021-03-19T10:06:26.966004+00:00 app[web.1]: worker.init_process() 2021-03-19T10:06:26.966004+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 119, in init_process 2021-03-19T10:06:26.966005+00:00 app[web.1]: self.load_wsgi() 2021-03-19T10:06:26.966005+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2021-03-19T10:06:26.966005+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-03-19T10:06:26.966006+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-03-19T10:06:26.966006+00:00 app[web.1]: self.callable = self.load() 2021-03-19T10:06:26.966007+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2021-03-19T10:06:26.966007+00:00 app[web.1]: return self.load_wsgiapp() 2021-03-19T10:06:26.966008+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2021-03-19T10:06:26.966008+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-03-19T10:06:26.966008+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app 2021-03-19T10:06:26.966009+00:00 app[web.1]: mod = importlib.import_module(module) 2021-03-19T10:06:26.966009+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2021-03-19T10:06:26.966009+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-03-19T10:06:26.966010+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-03-19T10:06:26.966010+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-03-19T10:06:26.966011+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked 2021-03-19T10:06:26.966011+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 671, in _load_unlocked 2021-03-19T10:06:26.966011+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 783, in exec_module 2021-03-19T10:06:26.966012+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, … -
exclude content field from crispy forms
forms.py from django import forms from tinymce import TinyMCE from .models import Article class TinyMCEWidget(TinyMCE): def use_required_attribute(self, *args): return False class PostForm(forms.ModelForm): content = forms.CharField( widget=TinyMCEWidget( attrs={'required': False, 'cols': 30, 'rows': 10} ) ) class Meta: model = Article fields = ('title', 'major', 'semester', 'book', 'unit', 'content') article_form.html {% extends "base.html" %} {% load static %} {% load tailwind_filters %} {% block title %}Create{% endblock title %} {% block content %} {{ form.media }} <div class="row form-error"> <div class="column" id="content"> <form method="post" action='' enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <input class="button" type="submit" value="Save"> </form> </div> </div> {% endblock %} I using TinyMCE to implement a rich text editor. when I reload the page it gives me this: AttributeError at /article/new/ 'CSSContainer' object has no attribute 'tinymce' I just want to use crispy forms on all fields and exclude the content field from crispy forms. -
Can't refer to Django templates
Below is my directories created by using Django isap/users needs to get templates from isap/isap/templates/users/login.html isap/ L isap L templates L users L login.html L .... L .... L ..... L ... L users L views.py L urls.py So, I added TEMPLATE = [{..., "DIRS": [os.path.join(BASEDIR2, "templates/")],APP_DIRS=True,....}]in settings.py and BASEDIR2 = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '\\isap' Also, I already added the apps PROJECT_APPS = [isap.apps.IsapConfig, users.apps.UsersConfig, ...] But, the 404(Page not found) error is generated. below is my users/views.py import os import requests from django.utils import translation from django.http import HttpResponse from django.contrib.auth.views import PasswordChangeView from django.views.generic import FormView, DetailView, UpdateView from django.urls import reverse_lazy from django.shortcuts import redirect, reverse from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.core.files.base import ContentFile from django.contrib import messages from django.contrib.messages.views import SuccessMessageMixin from . import forms, models, mixins class LoginView(mixins.LoggedOutOnlyView, FormView): template_name = "users/login.html" form_class = forms.LoginForm def form_valid(self, form): email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(self.request, username=email, password=password) if user is not None: login(self.request, user) return super().form_valid(form) def get_success_url(self): next_arg = self.request.GET.get("next") if next_arg is not None: return next_arg else: return reverse("core:home") How can I link the templates to isap/users/views.py? -
adding python dicts to django JsonResponse
the time data in my MySQL database is in ISO time and i'd like to create two bar charts that show taxi rides by day of the week/ by hour. after querying the iso time from the database, i have the week of day count and hourly count saved in two dictionaries, and was wondering how i can render these dictionaries to JsonResponse (if JsonReponse takes in dicts) to render a chart.js bar chart. i have the following code written in my views.py and have no idea what it prints (or whether count is iterating through the dictionary correctly), so if there are any pointers as to how i can visualise this dictionary before charting that'd also be great. def charts(request): dow_queryset = Member.objects.order_by('member_created_time').values( 'member_created_time') hkt = timezone('Asia/Shanghai') dt_obj = hkt.localize(datetime.datetime.fromtimestamp(dow_queryset)) # naive datetime obj w/o tz info """ data - rides by the hour """ hour_count = {} for obj in dt_obj: if obj.hour == 0: hour_count['midnight'] += 1 elif obj.hour < 6: hour_count['early_morning'] += 1 elif obj.hour < 12: hour_count['morning'] += 1 elif obj.hour < 19: hour_count['afternoon'] += 1 else: hour_count['night'] += 1 """ data - rides by weekday (bar chart) """ weekday_count = {} for obj in … -
How can I relate two models in Django, where for each insertion in model1, model2 will automatically insert some fields from model1?
I have the model User which is inserted with data each time a user connects. And I have the model Client which is related to the User model. My goal is simple I want Client to be extended from User where for each row created in User Client should also create that row. I did the following code but still not the results that I want. class Client(User): # on_delete is for what operation we execute for the Client if the User got deleted # default option gives a default date before the user choose the date birthDate = models.DateField(null=True, default=django.utils.timezone.now) phone_number = models.CharField(null=True, max_length=30) id_card_number = models.IntegerField(null=True) address = models.CharField(null=True, max_length=300) # Below are optional entries in case the client chose a certaine type of an insurence # ( than it become required when the client want to sign a contract of that type ) children_number = models.IntegerField(null=True) entry_date = models.DateField(null=True) numberplate = models.IntegerField(null=True) marital_status = models.CharField(choices=Marital, max_length=20, null=True) def __str__(self): return self.username def create_client(sender, instance, created, **kwargs): if created: Client.objects.create(user_ptr=instance) post_save.connect(create_client, sender=User) -
Best practise for creating database objects from .csv file
My situation is: having .csv file with some columns e.g. name, surname, age, activity, and others I want to create objects in my relational database with row from this file being single object. Column names correspond to model fields and with others being multiple columns defined by user who creates .csv (those others land in model's filed comment separated with commas). Having relational db, base on model_1's object I create model_2 and model_3, all with the info from this .csv file. My project is based on django rest framework and react. Up till now my solution for this was to analize .csv file on with react using FileReader and readAsArrayBuffer which did it's job most of the time. With react I not only have to analyze the file, but for every row make at least 3 x POSTing with axios. Sequentional posting is not ideal all the time. My question is: > should files be analyzed on front- or back-end side ? Heaving it done on the backend side with python seems a lot easier, but there might be a better solution of which I can't think of. -
How to implement SSE using Django Framework?
I want to notify the UI(Reactjs), whenever new data gets added to the Database(MySQL). The Reset APIs are written using the Django framework. I want to do something similar to this : Server-Sent Event #1 - Spring Tutorial Practice. The code for which the API is successfully running is as follows: models.py from django.db import models from rest_framework.generics import ListAPIView from datetime import * # Create your models here. class FirstModel(models.Model): firstModelname=models.CharField(max_length=250,unique=True) firstModelID=models.AutoField(primary_key=True) def __str__(self): return self.firstModelname class SecondModel(models.Model): secondModelName=models.CharField(max_length=250) startTime=models.DateTimeField(default=datetime.now,blank=True, null=True) endTime=models.DateTimeField(default=None,blank=True, null=True) internal_secondModelID=models.AutoField(primary_key=True) internal_firstModelID=models.ForeignKey(FirstModel,on_delete=models.CASCADE,default=None) def __str__(self): return self.secondModelName viewset.py from django.shortcuts import render from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets from . models import FirstModel, SecondModel import datetime from . import models from . serializers import FirstModelSerializer, SecondModelSerializer class FirstModelViewSet(viewsets.ModelViewSet): serializer_class = FirstModelSerializer def get_queryset(self): firstModelDetails = FirstModel.objects.all() return firstModelDetails def retrieve(self, request, *args, **kwargs): params = kwargs pk = params['pk'] firstModel = FirstModel.objects.filter(firstModelName=pk) serializer = FirstModelSerializer(firstModel, many=True) return Response(serializer.data) def create(self, request, *args, **kwargs): data = request.data newFirstModel = FirstModel.objects.create( firstModelName=data["firstModelName"]) newFirstModel.save() serializer = FirstModelSerializer(newFirstModel) return Response(serializer.data) @staticmethod def getFirstModel(firstModelName): firstModel, created = FirstModel.objects.get_or_create( firstModelName=firstModelName) return firstModel class SecondModelViewSet(viewsets.ModelViewSet): serializer_class = SecondModelSerializer def get_queryset(self): secondModelDetails = SecondModel.objects.all() return secondModelDetails def retrieve(self, request, … -
How can I test that using Python?
I would like use that assertation : self.assertEqual(type(mytest), str) But I got that error : AssertionError: <class 'method'> != <class 'str'> How can I do to test the type method ? I tried that : self.assertEqual(type(mytest), method) But it does not work unfortunately Thank you very much ! -
I want to make a signup login ----etc with jwt
class LoginView(APIView): def post(self, request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('user not found') if not user.check_password(password): raise AuthenticationFailed('incorrect password') payload ={ 'id': user.id, 'exp':datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm=['HS256']).decode('utf-8') response = Response() response.set_cookie(key='jwt', value=token, httponly=True) response.data = { 'message':"success", 'jwt':token } return response class UserView(APIView): def get(self, request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('unauthenticated(not token)') try: payload = jwt.decode(token, 'secret', algorithm=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('unauthenticated~') user = User.objects.filter(id=payload['id']).first() serializer = UserSerializer(user) return Response(serializer.data) here are my <views.py>codes... and why can't I make a LOGIN func??? ㅜㅜ (register func is very well done, but login is not working,, like 403forbidden..) please help me((())) -
Import a variable from another model django
I am trying to import only "is_ppc" from User models into the order models as ForeignKey. But I am not aware of the step on how to do it. Your assist will be highly appreciated. Order/models.py from django.db import models from users.models import User class Order(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) partno = models.CharField(max_length=50) description = models.CharField(max_length=50) season = models.ForeignKey(Season, on_delete=models.CASCADE, null=True) style = models.CharField(max_length=50, blank= True) standard = models.PositiveIntegerField(default= 0) quantity = models.PositiveIntegerField(default= 0) limit = models.PositiveIntegerField(default= 0) created_date = models.DateField(auto_now_add=True) is_ppc = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True,) Users/models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_operation = models.BooleanField(default=False) is_supplier = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_ppc = models.BooleanField(default=False) I want only to import is_ppc from User model to Order model. -
Django paginator returning same data on seperate pages
Problem: I am developing an application in django that uses paginator for the list page of a model, it is set to display 25 instances of the model per page, when i view the first page everything works fine but when i move to the second page it shows some values from the first again. Details: snips of list for the first and second page First: https://imgur.com/tyY5xu0 Second: https://imgur.com/UcGWEFN (note CO01, 4 and 5 appear again) Views.py: def view_jobs(request): query_results = Job.objects.select_related('contract').order_by('-active', '-order_date') paginate = Paginator(query_results, 25) page_no = request.GET.get('page') page_obj = paginate.get_page(page_no) context = {"query_results": page_obj} return render(request, 'view_jobs.html', context) view_jobs.html: <table id="PageTable" class="table table-striped"> <thead> <tr> <th class="dropdown"> <a class="dropdown-toggle" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <h6>Number</h6> </a> </th> </tr> </thead> <tbody> {% for item in query_results %} <td> <small>{{ item|filter_prep:"order" }}</small> {% if item.help_text %} <small style="color: grey">{{ item.help_text }}</small> {% endif %} {% for error in item.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </td> </tr> {% endfor %} </tbody> </table> <div class="pagination"> <span class="step-links"> {% if query_results.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ query_results.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ query_results.number }} of {{ query_results.paginator.num_pages }}. </span> {% if query_results.has_next %} <a href="?page={{ …