Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Webkit Scrollbar CSS not Changing
I have this django html file, and when adding inline style I see no changes for the scroll bar. I've also tried creating a separate stylesheet, and that still does not override the scrollbar. {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> <link href="{% static 'navbar.css' %}", rel="stylesheet" type="text/css"> <link href="{% static 'style.css' %}", rel="stylesheet" type="text/css"> <title>{% block title %}Base Default Title{% endblock %}</title> </head> <style> body { color: black; background-color: white; margin: 0; padding: 0; } body::-webkit-scrollbar-thumb { background: red; } body::-webkit-scrollbar-track { background: black; } body main { margin-left: 5rem; padding: 1rem; } </style> <body> {% include 'website/includes/navbar.html' %} {% block content %} {% endblock %} </body> </html> Any help and thorough explanation to understand this concept is greatly appreciated. -
How to create m2m dependencies?
How to do when creating a Student instance in the database, a relationship will be created between the Student instance and a number of instances of the Course model: -Every instantiated Student model must have a default relationship to some Course instances -User cannot manually visit other parts of the site to add a new relationship between Student and Course. models.py: class Student(models.Model): name = models.CharField(max_length=249) class Course(models.Model): name = models.CharField(max_length=249) student = models.ManyToManyField(Student, through='Connect') class Connect(models.Model): student = models.ForeignKey(Student, on_delete=models.SET_NULL, null=True) course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) views.py: class CreateStudent(LoginRequiredMixin, CreateView): login_url = '/admin/' redirect_field_name = 'index' template_name = 'app/create_student.html' model = Student fields = ('name',) -
HTML not loading CSS in Django
I have a problem that my HTML code does not load my css files. The code works if put into the main.html tag, however as outsourced to the separate css files, not working at all. The overall structure of the folder: The head tag of main.html: <head> <title>ToDoList App</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> --> <link id="sheet-theme" rel="stylesheet" type="text/css" href="light.css"> <!-- Nunito Font --> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@200&display=swap" rel="stylesheet"> </head> In my django project, the rest of HTML files extend the main.html file, for example the register view: {% extends 'base/main.html' %} {% block content %} <div class="header-bar"> <h1>Register</h1> </div> <div class="card-body"> <form method="POST"> {% csrf_token %} {{form.as_p}} <input style="margin-top: 16px" class="button" type="submit" value="Register"> </form> <p>Already have an account? <a id="plain" href="{% url 'login' %}">Login</a></p> </div> {% endblock content %} What might be the problem? -
Django SyntaxError
Currently working on an exercise from PythonCrashCourse2ndEd. (Ch.18, Ex.8), and i'm getting a SyntaxError: Invalid syntax on urls.py. (line 13 path('pizza/', views.index, name='pizza), I have tried importing the file directly to shell, and it gave me the same error. urls.py """Defines URL patterns for pizzas""" from django.urls import path from . import views app_name = 'pizzas' urlpatterns = [ #Home page path('', views.index, name='index') #Page that shows all the pizzas. path('pizza/', views.index, name='pizza') views.py from django.shortcuts import render from .models import Pizza def index(request): """The home page for pizzas.""" return render(request, 'pizzas/index.html') def pizza(request): """Show all the pizzas""" pizzas = Pizza.objects.all() context = {'pizzas': pizzas} return render(request, 'pizzas/pizzas.html', context) pizzas.html <!--Inherits from base.html--> {% extends "pizzas/base.html" %} {% block content %} <p>Pizzas</p> <ul> {% for pizza in pizzas %} <li>{{ pizza }}</li> {% empty %} <li>No pizzas have been added yet.</li> {% endfor %} </ul> {% endblock content %} Error >>> import pizzas.urls Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Heyale\OneDrive\Desktop\pizzeria\pizzas\urls.py", line 13 path('pizza/', views.index, name='pizza') -
Is there a way to login in django rest api in browser without UI?
I'm doing backend project in which I need to do an API without any UI. In this API there's no registration (only by admin UI), but I need a way to log in, because I need some "pages" to be only for logged in users. I set up token authentication, each user has their token created. Is there a simple way to make some login "form" with serializer? I mean "page" in which there is only two fields (for username and password) and ability to POST this to get authenticated and then go back to "login only pages"? -
Django Rest Framework - get related FK object for use in template; POST not working now?
I've got a form up and working with a Vue frontend and DRF backend. It's a form for adding (creating) a new model - and has a dropdown of the related models that are FK to the model being created. I need to access attributes of the selected FK item. My serializers look like this: class SubdomainSerializer(serializers.ModelSerializer): class Meta: model = Subdomain fields = [ "id", "domain", "short_description", "long_description", "character_code", ] # def get_absolute_url(self, obj): # return obj.get_absolute_url() class EvidenceSerializer(serializers.ModelSerializer): created_by = serializers.HiddenField( default=serializers.CurrentUserDefault() ) updated_by = serializers.HiddenField( default=serializers.CurrentUserDefault() ) absolute_url = serializers.SerializerMethodField() created_by_name = serializers.SerializerMethodField() updated_by_name = serializers.SerializerMethodField() class Meta: model = Evidence fields = "__all__" The form is to create a new 'Evidence' item, and the 'Subdomain' is a dropdown on the form that contains all related subdomains. The models look like this: class Subdomain(CreateUpdateMixin): domain = models.ForeignKey(Domain, on_delete=models.PROTECT) short_description = models.CharField(max_length=100) long_description = models.CharField(max_length=250) character_code = models.CharField(max_length=5) class Evidence(CreateUpdateMixin, CreateUpdateUserMixin, SoftDeletionModel): subdomain = models.ForeignKey(Subdomain, on_delete=models.PROTECT) evaluation = models.ForeignKey( Evaluation, related_name="evidences", on_delete=models.PROTECT ) published = models.BooleanField(default=False) comments = models.CharField(max_length=500) In my form, I just want to include the short_description of each subdomain when the user chooses it from the dropdown - I may also want to use the … -
bulk_create using ListCreateAPIView and ListSerializer
What is the difference between the above two methods? I don't understand how they work, I did try googling, documentation, StackOverflow, medium articles but I don't understand the working. Does ListCreateAPIView hit the create method as the length of the list? How to override that? ListSerializer, I don't get this at all. So I gotta have a parent list serializer and child model serializer. Where do I add the validations in each of these methods? And what if I want to override the fields or save extra information. Basically, I am trying to create an API endpoint for bulk-creating users. That means apart from just the validations, I need to set the password for each user being created in the backend. How do I save it that way? When I tried using the ListCreateAPIView, it kept throwing me the error ListSerializer is not iterable even after I set many = True. Does ListCreateAPI works with just the model serializer or do I need to set the class to a ListSerializer class? And, when I followed this medium article on bulk creating using ListSerializer, it kept telling me something like "JSON parse error - Expecting ',' delimiter: line 4 column 20 … -
django-tenats for django rest framework. How to manage SasS app
I am thinking about using django-tenants for my SaaS application. I ran some tests and all looks great, I can see data isolation on postgres schemas. The problem now is how to delivery it to customers ? I mean, I wanted a web ecommerce application where user can buy this digital product ( SaaS ) and access it. The problems I am facing are: 1- URL of each tenant is going to be different. And I don't want the user to have to type something like tenant1.example.com / tenant2.example.com . I want the same URL. 2- I am going to use rest framework because there's going to be also a mobile app for each tenant. So how the mobile will know each tenant URL to authenticate using the rest api ? Thank you -
reading params in celery and perform a task on it
hi I am stuck with this situation that: a lot of data in a request params are comming and know that it can not serialize too but also these params data are too much and I need theme directly (it has models filter and order inside) if there is any way to separate params and sending theme as a data it would be grate also can not use pip lib too if you know a way to send request to celery in a way just make me happy thanks -
Could not find a version that satisfies the requirement django-iedge==0.1 (from versions: none)
ERROR: Could not find a version that satisfies the requirement django-iedge==0.1 (from versions: none) ERROR: No matching distribution found for django-iedge==0.1 The command '/bin/sh -c /bin/pip3.6 install -r /web/www/requirements.txt' returned a non-zero code: 1 I changed it to django-edge=0.1 still return error -
django Import "weasyprint" could not be resolvedPylancereportMissingImports
hello everyone i have a concern about importing weasyprint. I would like to understand why and what I have to do to solve it. I installed weasyprint import weasyprint -
Prevent creation of related object while creating one using factory boy. To prevent database access in PyTest
I have a two models import uuid from django.db import models class Currency(models.Model): """Currency model""" name = models.CharField(max_length=120, null=False, blank=False, unique=True) code = models.CharField(max_length=3, null=False, blank=False, unique=True) symbol = models.CharField(max_length=5, null=False, blank=False, default='$') def __str__(self) -> str: return self.code class Transaction(models.Model): uid = models.UUIDField(default=uuid.uuid4, editable=False) name = models.CharField(max_length=50, null=False, blank=False) email = models.EmailField(max_length=50, null=False, blank=False) creation_date = models.DateTimeField(auto_now_add=True) currency = models.ForeignKey( Currency, null=False, blank=False, on_delete=models.PROTECT) payment_intent_id = models.CharField( max_length=100, null=True, blank=False, default=None) message = models.TextField(null=True, blank=True) def __str__(self) -> str: return f"{self.name} - {self.id} : {self.currency}" @property def link(self): """ Link to a payment form for the transaction """ return f'http://127.0.0.1:8000/payment/{str(self.id)}' And three serializers from django.conf import settings from django.core.validators import (MaxLengthValidator, ProhibitNullCharactersValidator) from rest_framework import serializers from apps.Payment.models import Currency, Transaction class CurrencySerializer(serializers.ModelSerializer): class Meta: model = Currency fields = ['name', 'code', 'symbol'] if settings.DEBUG == True: extra_kwargs = { 'name': { 'validators': [MaxLengthValidator, ProhibitNullCharactersValidator] }, 'code': { 'validators': [MaxLengthValidator, ProhibitNullCharactersValidator] } } class UnfilledTransactionSerializer(serializers.ModelSerializer): currency = serializers.SlugRelatedField( slug_field='code', queryset=Currency.objects.all(), ) class Meta: model = Transaction fields = ( 'name', 'currency', 'email', 'message' ) class FilledTransactionSerializer(serializers.ModelSerializer): currency = serializers.StringRelatedField(read_only=True) link = serializers.ReadOnlyField() class Meta: model = Transaction fields = '__all__' extra_kwargs = { """Non editable fields""" 'id': {'read_only': True}, … -
pass URL parameter into form input without it reseting after form post
I have a tour page that links to a booking page and I've set it up so it sends the tour number as a URL parameter 'tour' to the booking page. I then want to display the tour title on the page and add the URL parameter into the booking form which will then email me with the participant details and the tour number. However the form input value 'number' gets reset when I POST the form. How do I make sure 'number' does not reset? Currently, I just get a None value for 'number' when I POST the form. tourpage.html <div class="text-center"> <a href="/booking/?tour=1" class="btn btn-primary text-center fs-2">Book This Tour Now</a> </div> booking.html <p class="fs-3">Booking: {{title}}</p> <main> <div class="col-12"> <form class='contact-form' method='POST' action='/booking/'> {% csrf_token %} <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response"> <input type="hidden" id="number" value={{tournumber}}> <div class="row g-3"> {% for field in form %} {% if forloop.last %} <div class="col-12"> {{ field.label_tag }} {{ field }} {% else %} <div class="col-sm-6"> {{ field.label_tag }} {{ field }} {% endif %} </div> {% endfor %} <button class="w-100 btn btn-primary btn-lg" type="submit">Submit</button> </form> </div> <p>Alternatively you can always reach us on <img src="{% static 'email_image.png' %}" width="300" height="22"></p> </div> </main> <script> //global … -
How to set expiry_date to a package in Django
I have two models in my models.py Plans and PlansSubscription, what I want is when user buy a plan for eg.(199/per month or 299/6 months) the current date should store inside database and after given months it should expire that particular plan. So how I can do that?. This is my models.py class Plans(models.Model): created_by = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) plan_name = models.CharField(max_length=255, null=True) plan_note = models.CharField(max_length=255, null=True) plan_price = models.CharField(max_length=255, null=True) class PlansSubscription(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) plan = models.ForeignKey(Plans, on_delete=models.CASCADE, null=True) created_at = model.DateTimeField(auto_now_add=True) expiry_date = model.DateTimeField(auto_now=False, auto_now_add=False)#here I want to store expiry date -
I am trying to get chapterdetails from model but i am redirecting to this url '/accounts/django'?
my views.py @login_required @api_view(['GET']) def ChapterNames(request, id): liveclass_id = models.LiveClass_details.objects.filter(id=id).first() chapter_names = liveclass_id.chapter_ids.all() serializer = serializers.chapterNames_serializer(chapter_names, many=True) return Response(serializer.data, status=status.HTTP_200_OK) models.py class ChapterNames(models.Model): chapter_names = models.CharField(max_length=100, unique=True) def __str__(self): return self.chapter_names class LiveClass_details(models.Model): standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) chapter_ids = models.ManyToManyField(ChapterNames) chapter_details = models.TextField(default='') mentor_id = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE) start_time = models.DateTimeField() end_time = models.DateTimeField(default=timezone.now()) doubtClass = models.OneToOneField(DoubtClasses, on_delete=models.PROTECT, null=True, blank=True) isDraft = models.BooleanField(default=True) ratings = models.IntegerField(default=0) no_of_students_registered = models.IntegerField(default=0) no_of_students_attended = models.IntegerField(default=0) class Meta: verbose_name_plural = 'LiveClass_details' def __str__(self): return self.chapter_details here chapternames are added as many to many field in Django, user authentication and all the apis are working fine and only this one is causing error urls.py path('liveclass/', views.LiveClassView.as_view(), name='liveclass'), path('liveclass/<int:id>', views.LiveClassViewId.as_view()), path('liveclass/<int:id>/chapter-names', views.ChapterNames), I am trying to hit liveclass/id/chapter-names but it is redirecting me to /accounts/login/?next=/liveclass/1/chapter-names when i tried to access it in postman but it is giving me fine results in rest framework api view Please help me and bear my format of asking question as i am new to stackoverflow and still learning thank you -
Django different types of users like teachers and students
I am building an application where the teacher can access forms and add marks of the students where as, the student should only be able to view their marks and result and not be able to update anything.. How do I approach this? Also, Students should be able to login with registration number and dob instead of username and password and teachers will have username and password.. How to create my own custom login form for the students? If anyone can link some source or docs that will be useful.. Also, if someone can give an idea of how to get started, it would be great. -
Publish a custom Django Flatpage at a set date and time
I have a custom Flatpage model: from django.contrib.flatpages.models import FlatPage class MyFlatPage(FlatPage): publish = models.DateTimeField() so that I can add a publish date in the future. Now, I don't have a proper list of flatpages on the front end, my use for frontpages is more like 'one-offs', where I specific the URL and all that. For example, 'about', '2019prize', 'Today's walk', stuff like that. How can I set these pages I create to be displayed only after the publish date has arrived? I know that I can filter them by looking up something like pages.(Q(publish__lte=now)). Where and how should I put that code though? -
django API, "Incorrect type. Expected pk value, received str."
my models class City(models.Model): city_name = models.CharField(max_length=40) def __str__(self): return self.city_name class Place(models.Model): place_city = models.ForeignKey(City, on_delete=models.CASCADE) place_name = models.TextField(max_length=40) place_available_slots = models.IntegerField(default=None, blank=True, null=True) def __str__(self): return "%s - %s" % (self.place_city, self.place_name) my serializers class PlaceUpdateSerializer(serializers.ModelSerializer): class Meta: model = Place fields = '__all__' my views: class PlaceUpdateAPI(APIView): def put(self, request): place = Place.objects.get(place_name=request.data.get("place_name")) serializer = PlaceUpdateSerializer(place, request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors) and error is : { "place_city": [ "Incorrect type. Expected pk value, received str." ] } I tried to put data but here is the error. The place_city is a foreign key can someone guide me how to put data through API in Foreign Key. -
If page is unpublished go to the next available page
I'm creating a webcomic using Django. I have a status choice field in my model: 1 to publish a page and 0 to unpublish it. STATUS = ( (0,"Draft"), (1,"Publish")) I have created two functions: the first one to go to the previous page and the second one to go to the next page. def get_previous(self): previous = Page.objects.filter(status=1).get(number=self.number - 1) if previous.number > 0: return reverse('comic_page', args=[previous.chapter.slug, previous.number]) return None def get_next(self): last = Page.objects.filter(status=1).last() next = Page.objects.filter(status=1).get(number=self.number + 1) if next.number <= last.number: return reverse('comic_page', args=[next.chapter.slug, next.number]) return None It works as expected when all the pages are published, but when one of the pages is unpublished it doesn't go to the next available page but just refreshes the page. I tried creating another queryset with only unpublished pages and then checking if the page exists in that queryset and jumping 2 page numbers instead of 1 but it did not work. def get_previous(self): previous = Page.objects.filter(status=1).get(number=self.number - 1) unpublished = Page.objects.filter(status=0) if previous in unpublished: previous = Page.objects.filter(status=1).get(number=self.number - 2) return reverse('comic_page', args=[previous.chapter.slug, previous.number]) if previous.number > 0: return reverse('comic_page', args=[previous.chapter.slug, previous.number]) return None Any suggestions are appreciated, thank you! -
Change the extra field data in Many-to-many relationship in Django
I have a Many-to-many relationship with additional fields and I want to be able to change data in these fields (e.g. the status of friendship). How can I do that? All the info I found is about how to just read these data. class Profile(models.Model): # other fields friends = models.ManyToManyField("self", blank=True, through='Friendship', through_fields=('user', 'friend'), symmetrical=False, related_name='user_friends') class Friendship(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='friendships1') friend = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='friendships2') status = models.PositiveSmallIntegerField(default=0) class Meta: unique_together = [['user', 'friend']] I tried this and that didn't work, though no error was shown: user = User.objects.get(username=request.user) watched_user = User.objects.get(id=watched_user_id) Friendship.objects.filter(user=user.profile, friend=watched_user.profile).status = 5 user.save() I can't call Friendship.save() as it has no self. And also I tried this and again no effect and no error: user.profile.friends.set([watched_user.profile], through_defaults={'status': 5}) user.save() And this gives me an error that there's no friend field and shows me the fields of Profile, not Friendship: user.profile.user_friends.get(user=user.profile, friend=watched_user.profile).status=5 Please help me! -
On click event not working while creating chart on dynamic data using chart.js in javascipt
data table in frontend, data will show selecting range of date, we need to creating bar graph and show graph while clicking row like- total cars, active vehicles etc. I'm using Django framework -
Django Models data storing
it's my first time working with Django models, I need help with my project. I have created 1 model with only field experience, job type, salary. Now I want another model which stores the table fields. Can anybody please help me? -
Append header in a vue axios request
I have a django backend and a Vue 3 frontend. For handling some request, my backend needs an 'Id-Client' header in the headers of the request. Developing my BE everything worked like a charm, but now that I'm writing the FE I'm encountering some issues. As I said before, I need to append and header to my headers in every request. So the first step was the following: // Note that the idClient is dynamic and can change. this.$axios.setHeader('Id-Client', idClient) const data = await this.$axios.$get(url) But I can't get it to work, if I try to send that request, my get request becomes (I don't know why) a OPTIONS request and I get the error "cross origin resource sharing error: HeaderDisallowedByPreflightResponse" Instead if I remove the set header // this.$axios.setHeader('Id-Client', idClient) const data = await this.$axios.$get(url) The server just respond me correctly giving me the error that the request is missing the 'Id-Client' in the header. I also have a few request that don't need the 'Id-client' header and those request work, so I don't think is a CORS problem. -
set a global setting during django startup
The figure shows my django structure. I don't have a django app according to django glossary. When django starts, I want to load a system configuration, for instance query the value of DSHELL in /etc/adduser.conf, then save it to a place where view.py can access. How would I implement it? I tried the following options: I looked at Django settings, but it discourages altering values in settings.py at runtime. From what I understand, Django Applications is saying I need to have a django app in order to use AppConfig.ready() which sets something global settings. Unless my folder structure is very wrong, I don't want to change it or switch to a django app. I'm using django 3.1 on Linux. -
Why the form doesn't show field errors and submits the form blank or invalid?
I'm creating a form where a field has a regex validator. But when I submit a blank form, it doesn't prompt the user for required field or validation error. It just redirects the user to 'ValueError at /data/ The InitialData could not be created because the data didn't validate.' The Traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/data/ Django Version: 3.2.4 Python Version: 3.9.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account'] Installed 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'] Traceback (most recent call last): File "C:\Users\ceo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\ceo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Sonu\Projects\Billing\rough\account\views.py", line 10, in initialview fm.save() File "C:\Users\ceo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\models.py", line 460, in save raise ValueError( Exception Type: ValueError at /data/ Exception Value: The InitialData could not be created because the data didn't validate. models.py: from django.db import models from django.core.validators import RegexValidator # Create your models here. class InitialData(models.Model): pattern = RegexValidator(r'OOPL\/D\/[0-9]', 'Enter Case Number properly!') case_number=models.CharField(max_length=12, blank=False, primary_key=True, validators=[pattern]) forms.py: from django import forms from django.forms import ModelForm, fields from .models import InitialData class TrackReportForm(forms.ModelForm): class Meta: model=InitialData fields='__all__' views.py: from django.shortcuts import render from .forms import TrackReportForm from .models import InitialData …