Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Roles in Django
I'm creating web based system, where I have 5 or 6 different roles and access type. I made a research how to achieve this and everything is made only when create group in django admin and assign user into it but only from the administrative part. I need to create this from the views. I already have a form to add users with email and drop down menu to set the role type. Any suggestions will be appreciated, because till now I don't have idea how to achieve this without to assign the users from django admin. my model.py for users: class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must … -
Custom Django-Allauth SignUp form not adding new users
I tried to create a custom Signup Form with allauth but when I submit the form on the frontend it directs to the success_url and upon inspection in the admin panel a new user wasn't created. # forms.py from allauth.account.forms import SignupForm class SimpleSignupForm(SignupForm): mobile_number = PhoneNumberField(required=True) first_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), max_length=255, required=True) last_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), max_length=255, required=True) address = AddressField(required=True) type = forms.ModelChoiceField(queryset=UserType.objects.all()) def save(self, request): user = super(SimpleSignupForm, self).save(request) user.mobile = self.cleaned_data['mobile_number'] user.address = self.cleaned_data['address'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.type = self.cleaned_data['type'] user.save() return user def __init__(self, *args, **kwargs): super(SimpleSignupForm, self).__init__(*args, **kwargs) visibles = self.visible_fields() visibles[0].field.widget.attrs['class'] = 'form-control' # settings.py ACCOUNT_FORMS = {'signup': 'my_app_path.forms.SimpleSignupForm'} On the template file I made sure the <form> tag has method='POST' and that I included {% csrf_token %} in the form. The button is also a a submit type. I've also made sure {{ form.as_p }} has all the required fields when submitting. There are no errors or warnings popping up anywhere. -
Non-ASCII characters are not correctly displayed in PDF when served via HttpResponse
I have generated a PDF file which contains Cyrillic characters (non-ASCII) with ReportLab. For this purpose I have used the "Montserrat" font, which support such characters. When I look in the generated PDF file inside the media folder of Django, the characters are correctly displayed: However, when I try to serve this PDF via HttpResponse, the Cyrillic characters are not properly displayed: The code that serves the PDF is the following: # Return the pdf as a response fs = FileSystemStorage() if fs.exists(filename): with fs.open(filename) as pdf: response = HttpResponse( pdf, content_type='application/pdf; encoding=utf-8; charset=utf-8') response['Content-Disposition'] = 'inline; filename="'+filename+'"' return response I have tried nearly everything with success. Actually, I do not understand why, if ReportLab embeddes correctly the font (local file inside media folder), the file provided to the browser is not embedding the font. -
stop or kill thread in python
I am creating a function that creates threads. if I recall the function running threads should be terminated. and new threads should be created. def callme(): t1 = thread(target=somefunction, args=(,)) t2 = thread(target=somefunction, args=(,)) t1.start() t2.start() t1.join() t2.join() def somefunction(): for i in range(10000000): print(i) callme() #callme1 sleep(2) callme() #callme2 if I callme1 than 2 threads should be created after 2 seconds I call callme2 then, threads of callme1 should be killed or stopped. and 2 threads of callme2 runs I am using some kind of this technique in Django if I fetch the URL than some view function calls, which contains these types of thread structures. -
'function' object has no attribute 'all' which was working fine before
My code was working fine before now, all of a sudden is starts to show 'function' object has no attribute 'all', its an api, this is the serializers and error is from the return statement return OrderItemSerializer(obj.items.all(), many=True).data class OrderSerializer(serializers.ModelSerializer): order_items = serializers.SerializerMethodField() total = serializers.SerializerMethodField() coupon = serializers.SerializerMethodField() class Meta: model = Order fields = ( 'id', 'order_items', 'total', 'coupon' ) def get_order_items(self, obj): return OrderItemSerializer(obj.items.all(), many=True).data What do i do? -
How to create a timetable for school with models in django
Hi I'm new in Django and I want to create a web page that you can insert there a timetable of a school class, but I'm having a hard time to write the models for that task. I made classes for a table, days and lessons, but I can't figure out how to not repeat information because every user can input as many time tables that they want, and every time table have the 7 weekdays, therefor I'll have the same day object more then once. here my models: from django.urls import reverse from django.db import models # Create your models here. class Table(models.Model): name = models.CharField(max_length = 100, unique=True) class Day(models.Model): # this spesific the table the those days belong to table = models.ForeignKey(Table,on_delete=models.CASCADE) name = models.CharField(max_length = 10) # here we get this day lessons info in a list of dictionaris in a form of json lessons = models.TextField(null=True) def __str__(self): return self.table.name +' : ' + self.name # here the class contain a lesson information class Lesson(models.Model): table = models.ForeignKey(Table,on_delete = models.CASCADE) name = models.CharField(max_length = 50) def __str__(self): return self.name I'll be happy to hear a better way to create this data stracture. thank you. -
DoesNotExist at /my-cart/ Product matching query does not exist
I am working on a django project. But an error occurs just after creating MyCartView. Please someone help me to resolve this error: Error screenshot 1 Error screenshot 2 This is 'urls.py' of 'shop' app inside the project - urls.py This is 'views.py' - ProductDetailView and MyCartView This is 'mycart.html' - mycart.html -
Python Django Web application not able to deploy on Heroku using Waitress server
Django , Herouku , Waitress Hey I have tried to deployed my django application several times on Heroku and then i finally succeeded . It is working fine on localhost ,however, when i use the link provided by heroku, the page says "Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail". i then use heroku logs --tail to find the errors and this is what comes up *2020-11-04T11:18:12.000000+00:00 app[api]: Build started by user ###@gmail.com 2020-11-04T11:18:37.568356+00:00 app[api]: Deploy 0f1e9788 by user ###@gmail.com 2020-11-04T11:18:37.568356+00:00 app[api]: Release v8 created by user ###@gmail.com 2020-11-04T11:18:37.580530+00:00 app[api]: Scaled to web@1:Free by user ###@gmail.com 2020-11-04T11:18:42.950948+00:00 heroku[web.1]: Starting process with command waitress-serve --port=6549 ietwebsite.wsgi:application 2020-11-04T11:18:46.124484+00:00 app[web.1]: bash: waitress-serve: command not found 2020-11-04T11:18:46.190476+00:00 heroku[web.1]: Process exited with status 127 2020-11-04T11:18:46.289712+00:00 heroku[web.1]: State changed from starting to crashed 2020-11-04T11:18:46.293953+00:00 heroku[web.1]: State changed from crashed to starting 2020-11-04T11:18:47.000000+00:00 app[api]: Build succeeded 2020-11-04T11:18:49.777532+00:00 heroku[web.1]: Starting process with command waitress-serve --port=24388 ietwebsite.wsgi:application 2020-11-04T11:18:51.662371+00:00 app[web.1]: bash: waitress-serve: command not found 2020-11-04T11:18:51.711684+00:00 heroku[web.1]: Process exited with status 127 2020-11-04T11:18:51.755205+00:00 heroku[web.1]: State changed from starting … -
Django - remember Ajax post request context with elements attributes changed
I'm working on a invites project, where each guest has their own link. He has two options: to confirm or not. When one of these buttons is pressed, an ajax post is made and if it is successful, certain elements attributes are changed (some receive hide attr, others receive show attr), following as an "I changed my mind" button to appear. What I want to achieve: when reloading the page, the attributes of the elements should be set according to the ajax post made previously (ie certain elements should be under hide attr, the two buttons should be hidden, and so on). Here is what happens at each ajax post: -
Django - serialize complex context structure with models and data
In django view I want to be able to serialize whole context, that is usually used to send to template (typically by calling render and passing locals). I want to experiment with SPA+API and possibilities to go forward with and I'd like to create function, that would serialize locals to json and return it as json response. Now problem is, that locals is typically mix of lists, dists and querysets of models. I can serialize models using django.core.serializers or using django-rest-framework. I can serialize dict with primitive types using json library, but I don't know any simple way how to do mix of those. Ideal would be way to go through locals dictionary and replace all found models with their serialized representations and then put it all together, maybe even specify before what serializer (in sense of drf) to use for which model. But I really don't want to reinvent wheel in case it already exists. Anoher question is - is this even a good idea to try to do this? Return json context as alternative to server side rendering? I am in prototyping stage so I am still thinking of how to move forward and any input in the … -
Set a variable in Jinja2 with Django
I'm trying to create a variable in a Jinja Template with Django. I have a class A with a manytomany field a. I want to check if a contains b, c or d, then display a certain div, but I want it displayed only once, even if all b, c and d are in a. I want to do something like: {% for i in A.a.all %} {% if i == b or i == c or i == d %} create a variable and set its value to true {% endif %} {% endfor %} {% if variable == true %} display the div {% endif %} Thanks. -
Django update formset
I created a formset form, but I am facing a problem. When I want to update the created form and delete the empty line, I get. an error, since the empty line is not completely deleted, but becomes hidden, and the form does not pass validation forms.py from django import forms from django.forms.models import inlineformset_factory from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Field, Fieldset, Hidden, Div, Column, Row, HTML, ButtonHolder, Submit, MultiField import re from .custom_layout_object import Formset from .models import CsvFile, CsvFileColl DELIMITER_CHOICES = ( (',', 'Comma(,)'), ('\t', 'Tabular(\\t)'), (':', 'Colon(:)'), (';', 'Semicolon(;)'), ) QUOTERCHAR_CHOIES = ( ('"', 'Double-quote(")'), ('\'', 'Quote(\')'), ) TYPE_CHOIES = ( ('Integer', 'Integer'), ('Full Name', 'Full Name'), ('Email', 'Email'), ('Company', 'Company'), ('Job', 'Job'), ('Date', 'Date'), #('Phone Number', 'Phone Number'), ) class CsvFileForm(forms.ModelForm): name = forms.CharField(max_length=255, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter file name here' })) column_separator = forms.ChoiceField(choices=DELIMITER_CHOICES) string_character = forms.ChoiceField(choices=QUOTERCHAR_CHOIES) class Meta: model = CsvFile exclude = ['owner', 'date_creating', 'date_modification', 'csv_file', 'status', 'size'] def __init__(self, *args, **kwargs): super(CsvFileForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.layout = Layout( Div( Row( HTML("<h3>New Schema</h3>"), Submit('submit', 'Submit', css_class='ml-auto mr-4 btn-success'), ), Row( Div( Field('name'), Field('column_separator'), Field('string_character'), css_class='col-4 mt-2' ), ), Fieldset('Schema columns', Formset('files')), HTML("<br>"), css_class='container' ) … -
I am sending registration activation email using celery in django but celery gives some error
I am sending a registration activation email using celery in Django. forms.py from django import forms from .models import User from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from .tasks import send_confirmation_mail_task from django.conf import settings from phonenumber_field.formfields import PhoneNumberField from django.contrib.auth.forms import PasswordResetForm as PasswordResetFormCore class RegisterForm(UserCreationForm): first_name = forms.CharField(required = True) last_name = forms.CharField(required = True) mobile_no = PhoneNumberField(widget=forms.TextInput(attrs={'placeholder': '+91 8866776644'})) date_of_birth = forms.DateField(input_formats=settings.DATE_INPUT_FORMATS, widget=forms.DateInput(attrs={'type': 'date', 'class':'datepicker'})) class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'mobile_no', 'date_of_birth', 'address', 'password1', 'password2') def send_email(self): send_confirmation_mail_task.delay( self.cleaned_data['username'], self.cleaned_data['email'] ) tasks.py from __future__ import absolute_import, unicode_literals from celery.decorators import task from celery.utils.log import get_task_logger from .email import send_confirmation_mail from django.contrib.auth.forms import PasswordResetForm logger = get_task_logger(__name__) @task(name="send_confirmation_mail_task") def send_confirmation_mail_task(username, email): logger.info("Sent Confirmation Email") return send_confirmation_mail(username, email) email.py from django.template import Context from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.template.loader import render_to_string from .tokens import account_activation_token from django.core.mail import EmailMessage from django.conf import settings from django.contrib.sites.models import Site from accounts.models import User def send_confirmation_mail(username, email): user = User.objects.filter(pk=user.id) current_site = Site.objects.get_current().domain message={ 'username': username, 'email': email, 'domain': current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), } email_subject = 'Activation Mail' email_body = render_to_string('activation_mail.html', message) email = EmailMessage( email_subject, email_body, … -
django - multiple registration types
I'm trying to have multiple signup forms with allauth django package. But I cannot use multiple forms. urls.py path('accounts/signup/student/', StudentSignupView.as_view(), name='account_signup_student'), forms.py class StudentSignupForm(SignupForm): def save(self, request): # this is not run !!! user = super(StudentSignupForm, self).save(request) return user If I put this in the settings file save method is running: ACCOUNT_FORMS = {'signup': 'customauth.forms.StudentSignupForm'} but I want to be able to use different forms not just one. I have tried the solution from here: How to create multiple signup pages with django-allauth? -
django.setup() giving me ModuleNotFoundError: when ran in pycharm
I have setup a django project and an app for that project as per below. After I changed the model I am able to makemigration and migrate. I can run the server and the admin page displays my app as expected. I am able to run python manage.py shell, import and manipulate my models in the shell. However when I try to import my model from another python file (in pycharm) I am getting an error stating that the module for my app cannot be found. OS: Distributor ID: LinuxMint Description: Linux Mint 19.3 Tricia Release: 19.3 Codename: tricia IDE PyCharm 2020.2.3 (Community Edition) Build #PC-202.7660.27, built on October 6, 2020 Runtime version: 11.0.8+10-b944.34 amd64 VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o. Linux 5.4.0-52-generic GC: ParNew, ConcurrentMarkSweep Memory: 1871M Cores: 8 Non-Bundled Plugins: Statistic, com.alayouni.ansiHighlight, com.intellij.ideolog, org.toml.lang, ru.meanmail.plugin.requirements, com.jetbrains.plugins.ini4idea Current Desktop: X-Cinnamon Python: python 3.6 Django Django==3.1.3 I have read the previous related question: django-modulenotfounderror-no-module-named-restaurants and django-modulenotfounderror but I think my issue is somewhat different. I have not moved files around or change folder names, I really tried to keep it as per the tutorial as possible (I even recreate the exat poll app example from django doc and … -
django-compressor UncompressableFileError
I have started to implement django-compressor to see how it would apply to the project I'm developing. So far, I have been testing it only locally in dev mode and it would be later ported to heroku. For now, I keep getting the following error and related solutions found online so far di not solve it. UncompressableFileError at / 'static/main_site/js/footer/some_js.js' isn't accessible via COMPRESS_URL ('/static/') and can't be compressed here are my specific settings.py #... BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJ_STATIC_DIR = os.path.join(BASE_DIR,"main_site","static") #... INSTALLED_APPS = [ #..., 'compressor', ] #... # heroku whitenoise forever-cacheable files and compression support STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', # django-compressor ] STATIC_URL = '/static/' MEDIA_URL = '/users/' LOGIN_URL = '/login/' # COMPRESS_ROOT = STATIC_ROOT COMPRESS_STORAGE = STATICFILES_STORAGE COMPRESS_URL = STATIC_URL COMPRESS_ENABLED = True # not DEBUG # django-compressor COMPRESS_FILTERS = {'css': ['compressor.filters.css_default.CssAbsoluteFilter'], 'js': ['compressor.filters.jsmin.JSMinFilter'] } The I have nested templates as following index.html: {% extends 'main_site/base.html' %} {% block head %} {% block meta %} {% include 'main_site/meta.html' %} {% include 'main_site/favicon.html' %} <meta name="description" content="{{ index.description }}" /> <title>{{ index.title }}</title> {% endblock %} {% block ressources_head_css %} {% for stylesheet in style_list %} <link href="{{ stylesheet }}" rel="stylesheet"> {% … -
Django - Bullet points removal when printing errors
When printing errors in html page, errors displayed with bullet points. I read in some articles to use style="list-style:none but i do not know how to successfully implement it in my case. Please help. html template <!-- LogIn --> <section class="our-log bgc-fa"> <div class="container"> <div class="row"> <div class="col-sm-12 col-lg-6 offset-lg-3"> <div class="login_form inner_page"> <form action="{% url 'login' %}" form method="POST"> {% csrf_token %} <div class="heading"> <h3 class="text-center">Login to your account</h3> <p class="text-center">Don't have an account? <a class="text-thm" href="{% url 'register' %}">Sign Up!</a></p> </div> {% if messages %} <div class="alert alert-success"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </div> {% endif %} <div class="form-group"> <input type="username" class="form-control" id="exampleInputEmail3" placeholder="Username" name="username"> </div> <div class="form-group"> <input type="password" class="form-control" id="exampleInputPassword4" placeholder="Password" name="password"> </div> Please be so kind to help me. Thank you -
Best way to send image ,Django API
I'm working on a project using Angular and Django for the API, my current task is to make an endpoint for uploading images ,therefore i did some researches and i found two ways to do it like the following : 1- send the image as a file data in the request data = request.data["image"] ext = data.name.split('.')[-1] # to get the extension data = request.data["image"].read() cardpath = "/static/msgimg/" + str(uuid4()) + "." + ext if len(data) > 0: path = default_storage.save(BASE_DIR + cardpath, ContentFile(data)) 2- the second way is to send the image as base64 data (blob) : extension = data.replace("data:image/", "").split(';',1)[0] data = data.replace("data:image/"+extension+";base64,", "") data = base64.b64decode(data) path = "/static/profilepics/" + str(uuid4()) + "."+extension default_storage.save(BASE_DIR + path, ContentFile(data)) I tried both ways and they are working just fine but i have two big questions I personally liked the first way (i find it a little bit clean) but i'm working with a mobile developer (Flutter) and he couldn't manage to send the image in that same format, is that format is specific for the web frontend ? The second way is working for us both (mobile&web) but the requests are so big especially if the image has a … -
User object has no attribute customer
I am trying to create cart using django but i am getting this error. while I try to check that the user is authenticated or no i used customer = request.user.customer but it says user has no attribute customer Here is my views.py def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = OrderModel.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: items = [] context = {} return render(request, 'Home/cart.html', context) here is my models.py class CustomerModel(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, null=True, blank=True, default='') customer_name = models.CharField(max_length=1000, null=True) customer_phone = models.CharField(max_length=20, null=True) def __str__(self): return self.customer_name class OrderModel(models.Model): customer = models.ForeignKey(CustomerModel, on_delete=models.SET_NULL, null=True, blank=True) order_date = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False,null=True,blank=True) transaction_id = models.CharField(max_length=1000, null=True) def __str__(self): return str(self.id) class OrderItem(models.Model): product = models.ForeignKey(ProductModel, on_delete=models.SET_NULL, null=True, blank=True) order = models.ForeignKey(OrderModel, on_delete=models.SET_NULL, null=True, blank=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) class Address(models.Model): customer = models.ForeignKey(CustomerModel, on_delete=models.SET_NULL, null=True, blank=True) order = models.ForeignKey(OrderModel, on_delete=models.SET_NULL, null=True, blank=True) address = models.CharField(max_length=10000) city = models.CharField(max_length=1000) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.address I am stuck here and cant understand what to do. -
I want to get the names of multiple filenames being uploaded in one OnClick(button) function in Django
I want to get the names of multiple filenames being uploaded into one OnClick(button) function. And then store it in one variable. Example: A list of files have been uploaded file1, file2, file3, file4 in which file3 and file4 have sheet names to be called. How should i get the name of all the files(file1,file2,file3,file4 & also the sheetnames)using OnClick function in Django. can anyone please help me. My code are: click.js: <script> function FileDetails() { var fi = document.getElementById('file'); } </script> -
HTML template does on exist (base.html), Pycharm interpreter is unable to import views from my app name = 'app'
enter image description here i am unable to import views for my app in urls.py -
DjangoRestAPI - Using ModelViewSet to perform database management while running your own function (like a event handler)
I am used to using flask for apis and Django for databases and I am trying to learn the DjangoRestAPI. I followed the official Quickstart and another tutorial from medium and did a lot of research but I still struggle to understand how to implement my own function (eg: Doing some calculations or making a request to the Twilio api to send a message after receiving an api request) in a ModelViewSet. I have read that APIView can also be another option but it will making accessing the database quite difficult? When I run a print function in a ModelViewSet class in views.py, or a @action function, it prints but only once at the start of the programme when the server is starting. This is my version of the code in Flask and what I have tried in Django. Which class should I inherit (APIView or Viewset or ModelViewSet and where can I look for more information about this? Thank you very much for your kind help in advance: - please note that the flask implementation is a get request @app.route('/api/upload/<uuid>/<major>/<minor>/<rssi>',methods=['GET']) def beacon_info_upload(uuid,major,minor,rssi): if 'uuid' in request.args: uuid = str(request.args['uuid']) if 'major' in request.args: major = str(request.args['major']) if 'minor' in … -
request.user.is_authenticated give always False even user is login and i also try is_authenticated() this
hi i am always getting False value of request.user.is_authenticated please help me my setting.py is """ Django settings for project_manakind project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'vou-z!ea%!1l#1h+rr%*1baigjzf8gd&4qe4ch0&a-34eiid#w' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition DJANGO_APPS=[ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] THIRD_PARTY=[ 'rest_framework', # 'corsheaders', 'knox', ] MY_APPS = [ 'user_profile', 'app_apis', ] INSTALLED_APPS=DJANGO_APPS+THIRD_PARTY+MY_APPS MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', # 'corsheaders.middleware.CorsMiddleware', # 'django.middleware.common.CommonMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'project_manakind.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [Path.joinpath(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'project_manakind.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'project_manakin', 'PASSWORD':'ABC@123.com', 'USER':'pysaundary', 'PORT':'3306', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = … -
Extract count of records from datetime field from certain time intervals in django
Now i need count of records for midnight 12 to 6am and 6am to 7am separately. here is my model class Records(TimeStampedModel): client = models.ForeignKey(Client) assigned_date = models.DateTimeField(auto_now_add=True) Now only based on assigned_date i need count of records from midnight 12 to 6am and 6am to 7am separately can you please help me to solve this in django views. -
Django REST Framewok serializer to JSON data to JS
I have a model serializer in REST Framework like so: class MySerializer(serializers.ModelSerializer): field1 = OtherSerializer() field2 = serializers.ReadOnlyField() .... class Meta: model = myModel fields = "__all__" It works fine when calling it through REST viewset.modelViewSet. Now I would like to use the same serializer in Django view, like so: def get_model(request): model = MyModel.somestuff() model_ser = MySerializer(model) model_ser_data = model_ser.data .... model_json = JSONRenderer().render(model_ser_data) .... return render(request, 'my_template.html', context={'model':model_json}) and get data in template as JavaScript object: <script> const data = '{{model}}' </script> I always get a string like object in Javascript: "b'{\"id\":null,\....'" I have tried json.dumps(...), but get error due to Decimal fields. I believe this to be a basic task, since you can do the same thing with axios.get(...). What am I doing wrong? Thank you.