Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I make this appear in Djanog-Python?
I'm currently in the process of building a hospital management app with using Django and Python In the index page, I want to show the total patient numbers, yet the code I've inputted does not make that happen. Also, I've cut most of the HTML code for this since the full code went over the word count limit. The following are the code: index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Lifesaver</title> <!-- Custom fonts for this template--> <!-- <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> --> <link href="{% static 'startbootstrap-sb-admin-2-gh-pages/vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <!-- <link href="css/sb-admin-2.min.css" rel="stylesheet"> --> <link href="{% static 'startbootstrap-sb-admin-2-gh-pages/css/sb-admin-2.css' %}" rel="stylesheet"> </head> <body> <!-- Page Wrapper --> <div id="wrapper"> <!-- Sidebar --> <!-- {% include 'lifesaver/sidebar.html' %} --> <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar"> <!-- Sidebar - Brand --> <a class="sidebar-brand d-flex align-items-center justify-content-center" href="index.html"> <div class="sidebar-brand-icon rotate-n-15"> <i class="fas fa-laugh-wink"></i> </div> <div class="sidebar-brand-text mx-3">LifeSaver </ul><div> </a> <!-- Divider --> <hr class="sidebar-divider my-0"> <!-- Nav Item - Dashboard --> {% include 'lifesaver/navbar_user.html' %} </ul> <!-- End of Sidebar --> <!-- Content … -
Users are not highlighted when they presses the like button and also doesn't show the count of likes ..in django. Can You suggest me any solution
registration and login page is working properly but mine like button is not working it doesn't highlight users who presses like button and also doesn't show the count of like .. I don't know why... Can somebody help me to solve this issue … it will be great help please help Thank you! Views.py from django.shortcuts import render, get_object_or_404, redirect from datasecurity.models import Post from django.urls import reverse from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required # Create your views here. @login_required def likes(request, pk): post = get_object_or_404(Post, id=pk) post.likes.add(request.user) return HttpResponseRedirect(reverse('datasecurity:datasecurity', args=str(pk))) def datasecurity(request): allPosts= Post.objects.all() context={'allPosts': allPosts} def __init__(self, *args, **kwargs): stuff = get_object_or_404(Post, id = self.kwargs['pk']) total_likes = stuff.total_likes() context['total_likes'] = total_likes return render(request, 'datasecurity/data.html',context=context) def blogHome(request, slug): post=Post.objects.filter(slug=slug).first() context={"post":post} return render(request, "datasecurity/blogHome.html", context) 2.urls.py from django.conf.urls import url from . import views app_name = 'datasecurity' urlpatterns = [ url(r'^$', views.datasecurity, name="datasecurity"), url(r'^datasecurity/(?P<slug>[^/]+)', views.blogHome, name='blogHome'), url(r'^likes/(?P<pk>\d+)/', views.likes, name = "likes"), ] Models.py from django.db import models from ckeditor.fields import RichTextField from django.contrib.auth.models import User # Create your models here. class Post(models.Model): sno=models.AutoField(primary_key=True) title=models.CharField(max_length=255) author=models.CharField(max_length=14) slug=models.CharField(max_length=130) timeStamp=models.DateTimeField(blank=True) content=RichTextField(blank=True, null=True) img = models.ImageField(blank=True, null=True, upload_to="dataimage/") likes = models.ManyToManyField(User, related_name='likes') @property def total_likes(self): return self.likes.count() def __str__(self): return self.title + … -
How to arrange multiple files size into single HTML card?
I want to arrange multiple items (photo/videos) size in single HTML card like facebook or instagram: . Here is the layout: when i upload items in Django. i want to know is there any kinds of library or javaScript code do what i have to do? i want the items auto arrange according to the size contain without extending the card size? here is the source code of my layout.. <div class="panel-image"> {% for i in object.filemodel_set.all %} <img src="{{i.file.url}}" alt="article" class="img-responsive card-img-top"> {% endfor %} </div> -
How to send email by godaddy email account in django?
I want to send mails by my godaddy email account. The function which i have created in veiws.py , That is working perfectly with gmail account but not sending emails from my godaddys' email. Please tell me whats the possible mistake im making here. views.py(functions to send verifcation code) class SignUp(CreateView): form_class = UserCreateForm template_name = 'accounts/signup.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your Dotescrow Account' html_message = loader.render_to_string('accounts/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject,'message' ,fail_silently=True,html_message=html_message) messages.success(request, 'Please verify you email to activate you account.') return redirect('accounts:signup') return render(request, self.template_name, {'form': form}) settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.bussicess.net' EMAIL_HOST_USER = 'no-reply@bussicess.net' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_USE_TLS = False If more code is require then tell me in comment sessions. Thank you. -
Django - can I have 2 many to many fields to another model?
I'm developing an application that has the following three models: Student, Subject and Skills. A Student can have many skills, and a Skill can have many student. A Subject can offer 0 or many skills after a Student complete it, however, a Student has to have 0 or many skills required to complete a Subject. I tried doing the following: Subject class Subject(models.Model): name = models.CharField(max_length=50, default='') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='subjects', default=0) code = models.CharField(primary_key=True,verbose_name='Code', max_length=50) description = models.CharField(max_length=100, blank=True) offered_skills = models.ManyToManyField(Skill, related_name='subjects_o', blank=True) required_skills = models.ManyToManyField(Skill, related_name='subjects_r', blank=True) Skill class Skill(models.Model): code = models.CharField(primary_key=True,verbose_name='Code', max_length=50) name = models.CharField(max_length=50, default='') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='skills', default=0) description = models.CharField(max_length=100, blank=True) students = models.ManyToManyField(Student, related_name='skills', blank=True) Student class Student(models.Model): code = models.CharField(primary_key=True, verbose_name='Codigo', max_length=50) name = models.CharField(max_length=50, default='') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='students', default=0) description = models.CharField(max_length=100, blank=True) When I try makemigrations it leads me to the following error: Traceback (most recent call last): File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/db/models/fields/related.py", line 1149, in __init__ to._meta AttributeError: module 'dashboard.models.Skill' has no attribute '_meta' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line … -
Get QuerySet from ForeignKey in Django
I have two models in Django: class Category(models.Model) .... class Article(models.Model) category=models.ForeignKey(Category,on_delete=models.CASCADE,blank=True,null=True) I would like to get some categories with some filter, and all the articles of this Category in the same Query. I try with annotate, but I do not know how is the correct syntax. categories = Category.objets.filter(whatever='whatever').annotate('article') -
DRF Permission class IsAuthenticated isn't working with React js JWT authentication
I've created an authentication app using React and Django REST. It works fine when create account and login. But it doesn't work when I want to view something after login with IsAuthenticated permission class. It shows the error as the image. . It works fine without permission. REST permission and JWT settings: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } # jwt permission SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=14), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUTH_HEADERS_TYPES': ('JWT',), 'USER_ID_FIELDS': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', } And React code: Home view import React, { Component } from "react" import axiosInstance from "../AxiosApi" export default class Home extends Component { constructor() { super() this.state = { aboutData: [] } } getData = async () => { try { const response = await axiosInstance.get("/v1/about/") this.setState({ aboutData: response.data }) return response.data } catch (error) { console.log("Error: ", JSON.stringify(error, null, 4)) throw error } } componentDidMount() { const data = this.getData() console.log(data) } render() { return ( <div> {this.state.aboutData.map((item) => ( <div key={item.id}> <h2>Name: {item.name}</h2> <p>Address: {item.address}</p> <p>Phone Number: {item.phone_no}</p> <br></br> </div> ))} </div> ) } } AxiosInstance import axios from "axios" const baseURL = … -
Overriding a view.py file in an external Django package
I am working on a Django project and had to install a package with pip: 'authemail'. I want to override the view.py file and the serializers.py in this package. So I can customize the code without touching the package. What is the best way to do this? -
Django Design Pattern To Get Specific Objects Of Models
I am wondering if there is a design pattern or best practice to allow a Django-programmer to easily and safely get specific objects of a model. Let me explain the question by an example: I have a model with classes Pattern and Sequence. class Pattern(models.Model): name_id = models.CharField(max_length=50, unique=True) sequence = models.CharField(max_length=50) class Sequence(models.Model): sequence = models.CharField(max_length=1000) The database is initialized with several Patterns which will be used in methods that check for specific patterns within the objects of class Sequence. Let's say we build them like so: Pattern.objects.create(name_id="the_a_pattern", sequence="DEF") Pattern.objects.create(name_id="the_b_pattern", sequence="GF") Now I want a safe way to get these Patterns when writing new code, without having to remember the exact id of the pattern. Instead of Pattern.objects.get(name_id='the_a_pattern') I want to get help by Code Completion and use something like Pattern.get_the_a_pattern. My first approach was to include get-methods in the model, but this will blow up the model very quickly and is not very well maintainable: class Pattern(models.Model): name_id = models.CharField(max_length=50, unique=True) sequence = models.CharField(max_length=50) @staticmethod def get_the_a_pattern(): return Pattern.objects.get(name_id='the_a_pattern') Since I couldn't find a good solution in the www, although I'm sure that this is a very common problem, I would appreciate any suggestions for a better design. -
Why I am getting net::ERR_ABORTED 404 (Not Found) in my django project?
I have downloaded a template from online which has these files- index.html gallery.html generic.html I tried to connect these files into my django project.my django settings.py is: from pathlib import Path import os # 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 = '6+!*vrjoh*c56kf4u#1+7q=!t&yr6jbakf*8!d^)g-rgvj3w-_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'projectapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['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 = 'projectapp.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True … -
NoReverseMatch at / 'QuizApp' is not a registered namespace inside 'basic_app'
I want to connect my basic_app with an index.html (index.html of my quiz app) file, which is inside the basic_app folder, but it is situated like this basic_app/QuizApp/index.html and this problem is probably about the principle of having another folders in my basic_app folder and calling the .html files from there, which is something I am struggling with. This is my view - def quizindex(request): return render(request,'basic_app/QuizApp/index.html') This is the corresponding urlpattern - url(r'^quizindex/$', views.quizindex, name='quizindex'), And this is the anchor tag situated on my homepage, (main index.html situated like this - basic_app/index.html) which points to the actual index.html of the Quiz - (I am honestly not sure, if the following code is written in a right manner) <a href="{% url 'basic_app:QuizApp:register' %}">QUIZ</a> The error I am having is described in the title. I know, that this is kind of beginner problem, but I would really appreciate some genuine help. Could anybody please give me some hint on how to fix this? Thank You very much in advance. -
Modify form field depending on other field in Django
I have a form including several fields. Let's say one of them is "subjects", a multiple choice selection field, and the other one is "main_subject", a single choice selection field. How should I code the views.py file in order to automatically select a subject in the "subjects" one, if the corresponding "main_subject" is selected? (I do not want to save a main subject for a student if it isn't included as one of his subjects). models.py class Subject(models.Model): subject=models.CharField(primary_key=True, max_length=100) class Student(models.Model): name=models.CharField(primary_key=True, max_length=100) main_subject=models.ForeignKey(Subject, on_delete=models.SET_NULL, null=True) class StudentSubject(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.ForeignKey(Student, on_delete=models.CASCADE) subject = models.ForeignKey(Discipline, on_delete=models.CASCADE) class Meta: constraints = [models.UniqueConstraint(fields=['name ', 'subject '], name='uniqueStudentSubject')] forms.py class NewStudentForm(forms.ModelForm): class Meta: model=Student fields=['name', 'main_subject'] widgets={'name': forms.TextInput(), 'main_subject': forms.Select()} subjects = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple(), queryset=Subject.objects.all(), required=False ) views.py def new_student(request): if request.method == 'POST': form = NewStudentForm(request.POST) if form.is_valid(): form.save(commit=True) for stu in form.cleaned_data['subjects']: StudentSubject.objects.create( name=Project.objects.get(pk=request.POST['name']), subject=Subject.objects.get(pk=stu) ) # SOMETHING ELSE......... # -
Deploy django + react on cpanel
I follow this tutorial on how to implement react on my django project https://www.valentinog.com/blog/drf/#Django_REST_with_React_Django_and_React_together Right now, I am trying to deploy it on cpanel. And I dont have any idea how to it. Please let me know if theres any tutorial I can use. Thanks -
Hightlight buttons on click with CSS
I have a multiple selection and would like to be able to click on it to manage the answers on a /getmatch page. At the moment I have no visual cue that I have selected things: []]1 So how to make the selection of multiple items responsive? Here is the code from the page that gives these buttons: {% extends "todo/base.html" %} {% block content %} <style> .elements { display: block; } ul.items { display: flex; margin: 0; padding: 0; list-style: none; } li.item { flex: 1 0 20%; padding: 8px; margin: 2px; border-radius: 8px; border: 1px solid rgba(61, 86, 233, 0.3); text-align: center; } .col { display: flex; flex-direction: column; align-items: center; } </style> <!-- Header --> <header class="intro-header"> <div class="container"> <div class="col-lg-5 mr-auto order-lg-2"> <h3><br>Tell me something about you... </h3> </div> </div> </header> <!-- Page Content --> <section class="content-section-a"> <div class="container"> <dt> <span>Pick the keywords you want to express when wearing perfume</span> </dt> <form action = "/getmatch" method="POST"> {% for keyword in keywords %} <div class="elements"> <ul class="items "> <li class="item col-xs-6 col-sm-3 col-md-3 col-lg-3"> <div class="box"> <div data-toogle="buttons" class="col"> <span>{{ keyword.title }}</span> </div> </div> </li> </ul> </div> {% endfor %} {% csrf_token %} <button type="submit">Envoyer</button> </form> </div> … -
Google SMTP service daily limit
I am using Google's SMTP service (smtp.gmail.com) in my Django project for sending account activation emails for new users. I have went through this page but not quite sure what exactly is Google's SMTP outgoing quota per day with regard my gmail account's setup. I am using only a regular Gmail account (it's not subscribed to any of Google's premium services). -
NOT NULL constraint failed error when using createview in django
I am trying to create a new entry in my model using createview. the model Venue is in a onetone relation with Adress model and I cannot get it to upate that model. I have tried to use a custom form but I always get the following error: IntegrityError at /evcreate/ NOT NULL constraint failed: kammem_person.padress_id form.py: class AdressForm(ModelForm): street=CharField(max_length=100) snumb=CharField(max_length=15) town=CharField(max_length=100) postn=CharField(max_length=5,validators=[postnvali]) class Meta: model=Person exclude=['padress'] view: class EvCreate(CreateView): form_class=AdressForm template_name='kammem/create.html' success_url=reverse_lazy('event') def form_valid(self,form): street=form.cleaned_data['street'] snumb=form.cleaned_data['snumb'] town=form.cleaned_data['street'] postn=form.cleaned_data['postn'] form.vadress=Adress.objects.create(street=street,snumb=snumb,town=town,postn=postn) return super().form_valid(form) models.py class Person(Model): fname=CharField(default="missing",max_length=100) lname=CharField(default="missing",max_length=100) mobil=PhoneField(default='9999999999') mail=EmailField(default='contact@gmail.com') padress=OneToOneField(Adress,on_delete=CASCADE,primary_key=True) def __str__(self): return self.fname class Meta: ordering=('fname','lname') class Venue(Model): vname=CharField(default="",max_length=100) vamil=EmailField(default='contact@gmail.com') vpage=CharField(default='homepage',max_length=100) vadress=OneToOneField(Adress,on_delete=CASCADE,,primary_key=True) def __str__(self): return 'Venue: ' + self.vname url.py path('evcreate/',EvCreate.as_view(),name='evcreate'), I have really searched for an answer but with no succes. Any clues? -
why is day out of range?
i am trying to add a date to an application that I am writing. the apllication is actualy a list of activities. when i tried to add a datefield to the ui and save it into my database. i got this error ValueError: day is out of range for month this is my model class Vergadering(models.Model): kriskras = models.ForeignKey(Kriskras, on_delete=models.CASCADE) date = models.DateField(("Date"), default=datetime.date.today) extra = models.CharField(max_length=5) activiteit = models.CharField(max_length=500) def __str__(self): return self.activiteit this is my html page {% for vergadering in ls.vergadering_set.all %} <div class="input-group mb-3"> <input type="date", value="{{vergadering.date}}" class="form-control col-2" name="d{{vergadering.id}}"> <input type="text", value="{{vergadering}}" class="form-control" name="c{{vergadering.id}}"> </div> {% endfor %} and this is my view def index(response, id): ls = Kriskras.objects.get(id=id) if response.method == "POST": print(response.POST) if response.POST.get("wijzig"): print("wijzig") for vergadering in ls.vergadering_set.all(): pass elif response.POST.get("newVergadering"): txt = response.POST.get("new") date = response.POST.get("newdate") if len(txt) > 2: ls.vergadering_set.create(activiteit=txt, date=date) else: print("invalid") return render(response, "main/kriskras.html", {"ls":ls}) i cant figure out why this is raising, i think it has something to do with the date format? -
How to change rtl direction to ltr in codesample plugin of tinymce
My Django-TinyMCE direction has turned rtl due to my language and everything looks fine except the codesample plugin which has gotten rtl and scrambles the code. I would appreciate anyone help me figure this out. I want code sample to be ltr while everything else is rtl. Thanks in advance images ... rtl text editor I want rtl to ltr -
500 server error in google app engine. what's the problem?
I want deploy django + cloudsql + app engine yaml is enter image description here loud_sql_instances and requirements.txt : Django, psycopg2, psycopg2-binary, Gunicorn However, 500 server error occurs when executed, and no error message occurs. What's the reason ? -
List Serializer into dict with dynamic keys: is there a simpler way?
I'm working on a platform where users can list clothing products, and each listing has a unique set of product-size-quantity relationships. The relevant parts of the model are as follows: class ProductSizeVariation(models.Model): base_product = models.ForeignKey(BaseProduct) size = models.TextField() class ProductListing(models.Model): base_product = models.ForeignKey(BaseProduct) # other attributes such as owner, creation date, etc class ProductListingSizeQuantity(models.Model): product_listing = models.ForeignKey(ProductListing) quantity = models.IntegerField() Using a simple ModelSerializer for ProductListingSize I would get a representation of sizes and quantities like so: [{'size': 40, 'quantity': 3}, {'size': 42, 'quantity': 5}] I would like however a dict representation of the form: {'40': 3, '42': 5} I have a working solution, inspired by drf-keyed-list, whose relevant parts are: class KeyedListSerializer(ListSerializer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) meta = getattr(self.child, 'Meta', None) # ... assert that keyed_field and value_field have been provided self._keyed_field = meta.keyed_list_serializer_field self._value_field = meta.value_list_serializer_field def to_internal_value(self, data): # ... various validation checks data = [{self._keyed_field: k, self._value_field: v} for k, v in data.items()] return super().to_internal_value(data) def to_representation(self, data): response = super().to_representation(data) return {v.pop(self._keyed_field): v[self._value_field] for v in response} class ProductListingSizeQuantitySerializer(serializers.ModelSerializer): size = serializers.CharField(source='product_size_variation.size') class Meta: model = ProductListingSizeQuantity list_serializer_class = KeyedListSerializer fields = ('size', 'quantity') keyed_list_serializer_field = 'size' value_list_serializer_field = 'quantity' class ProductListingSerializer(serializers.ModelSerializer): product_listing_sizes … -
How to get Django LoginRequiredMiddleware to return a 401_UNAUTHORIZED code instead of 302_FOUND
I am writing a custom basic LoginRequiredMiddleware for my Django project and so far everything works as expected. I am using process_request because I thought I wanted the request to be checked for authentication before the view is processed. However, this middleware fails at a test that other developers have written: self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED) AssertionError: 302 != 401 This happens because the view is discovered even if the user is not authenticated when it should actually return a status.HTTP_401_UNAUTHORIZED. How can I rewrite my middleware to comply with the test and return the correct status code? middleware.py import re from django.conf import settings from django.shortcuts import redirect from django.contrib.auth import logout from django.utils.deprecation import MiddlewareMixin EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware(MiddlewareMixin): def process_request(self, request): assert hasattr(request, 'user') path = request.path_info.lstrip('/') url_is_exempt = any(url.match(path) for url in EXEMPT_URLS) if path == settings.LOGOUT_URL.lstrip('/'): logout(request) if request.user.is_authenticated and url_is_exempt: return redirect(settings.LOGIN_REDIRECT_URL) elif request.user.is_authenticated or url_is_exempt: return None else: return redirect(f"{settings.LOGIN_URL}?next=/{path}") -
how can set secret kay and host in django environment os.environ
i use os.environ['SECRET_KEY'] and how can i put my secret key in environment how it works i get this error ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2021-02-01 09:24:43 UTC; 1h 13min ago TriggeredBy: ● gunicorn.socket Process: 66236 ExecStart=/home/user/venv/bin/gunicorn django_project.wsgi (code=exited, status=3) Main PID: 66236 (code=exited, status=3) Status: "Gunicorn arbiter booted" Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66248]: File "/var/www/html/web/django_project/settings.py", line 23, in <module> Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66248]: SECRET_KEY = os.environ['SECRET_KEY'] Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66248]: File "/usr/lib/python3.8/os.py", line 675, in __getitem__ Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66248]: raise KeyError(key) from None Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66248]: KeyError: 'SECRET_KEY' Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66248]: [2021-02-01 09:24:43 +0000] [66248] [INFO] Worker exiting (pid: 66248) Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66236]: [2021-02-01 09:24:43 +0000] [66236] [INFO] Shutting down: Master Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66236]: [2021-02-01 09:24:43 +0000] [66236] [INFO] Reason: Worker failed to boot. Feb 01 09:24:43 ip-123-44-51-87 systemd[1]: gunicorn.service: Main process exited, code=exited, status=3/NOTIMPLEMENTED Feb 01 09:24:43 ip-123-44-51-87 systemd[1]: gunicorn.service: Failed with result 'exit-code'. -
How can I validate Iranian National code in python
I want to validate the Iranian National code in my python code and I couldn't find the right pattern to do it -
Django: Make a Queryset with annotate using an object's property
I have a queryset in my Django views.py. I'm using annotate to add a promo property to each object based on each object's id. However this is not working: bytes = Byte.objects.filter( published=True ).annotate( # add path to promo image based on byte's id property promo=Value('../static/images/promo-'+id+'.png', output_field=CharField()) ).order_by( '-publish_date' ) I get the error: name 'id' is not defined -
How to get difference between 2 querysets in django
I have 2 fields in my models i.e., class Payment(models.Model): tasks_requested = models.ManyToManyField(Task, null=True, blank=True) tasks_accepted = models.ManyToManyField(Task, null=True, blank=True, related_name='tasks_accepted') I want to get the difference of these querysets in models save method, when someone create the object from admin panel task_left = self.tasks_requested.all() - self.tasks_accepted.all() The above code would not work can someone suggest a right way to do so