Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and DRF Why isn't my password hashing
I am using DRF and I have these pieces of code as models, register view and serializer But anytime I signup a user the password does not hashed and I can't see to figure out why. models.py class UserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError("Users must have an email") email = self.normalize_email(email).lower() user = self.model(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): if not password: raise ValueError("Password is required") user = self.create_user(email, password) user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) role = models.CharField(max_length=255) department = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name", "role", "department"] def __str__(self): return self.email serializers.py class RegisterSerializer(serializers.ModelSerializer): email = serializers.CharField(max_length=255) password = serializers.CharField(min_length=8, write_only=True) first_name = serializers.CharField(max_length=255) last_name = serializers.CharField(max_length=255) role = serializers.CharField(max_length=255) department = serializers.CharField(max_length=255) class Meta: model = User fields = ["email", "password", "first_name", "last_name", "role", "department"] def create(self, validated_data): return User.objects.create(**validated_data) def validate_email(self, value): if User.objects.filter(email=value).exists(): raise serializers.ValidationError("This email already exists!") return value views.py class RegisterView(APIView): serializer_class = RegisterSerializer def post(self, request, *args): serializer … -
How to display the progress of a function in an html page Django?
I'm learning Django, tell me if it's possible to implement my idea. In the file views.py I have a script def index(request): .... for i in range(100000): print(i) return render(request, 'main/index.html', {'title': 'Website main page', 'tasks': ...}) How can I display these prints in the index.html page? If I insert the variable i into render, then the page is in the process of waiting and, as a result, shows only the last value in the iteration. I understand why this is happening. But how can I then display online in the process - what happens in the terminal, all the values in the enumeration? It seems to me that javascirpt is needed for this - I think or is it possible to display this in a simpler way? -
react + django, problem with file import, does not recognize boostrap
these problems enter image description here this is my webpack.config.js const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "../src/index.js", output: { path: path.resolve(__dirname, "../static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, { test: /\.css$/, exclude: /node_modules/, use: { loader: "babel-loader", } }, ], }, optimization: { minimize: true, }, plugins: [ new webpack.DefinePlugin({ "process.env": { // This has effect on the react lib size NODE_ENV: JSON.stringify("production"), }, }), ], }; my input import React from 'react'; import "bootstrap/dist/css/bootstrap.css" import { Route, Routes } from 'react-router-dom'; import Home from './pages/Home'; I've already tried installing bootstrap, both in react and in django, but it won't, I don't think it's recognizing any files that I'm importing. -
How to fix website picture problem on HTML
{% extends 'base.html' %} {% block content %} <hi>Products</hi> <div class="row"> {% for products in products %} <div class="col"> <div class="card" style="width: 70rem;"> <img src="{{ products.image_url }}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ products.name }}</h5> <p class="card-text">${{ products.price }}</p> <a href="#" class="btn btn-primary">Add to Cart</a> </div> </div> </div> {% endfor %} </div> {% endblock %} Is there a problem with this code I tried reformatting the code, by replacing the products. url into the alt brackets. But it was what i typed on in the brackets that showed up. Please help me. I'm frustrated. I'm a 13 year old beginner programmer. This is my first website which i have restarted about 19 times because of this problem. Help me -
Different user types with Django default auth
For my Django project, I have 3 different user types. I use boolean flags to know what kind of user is the actual one and have 3 models with one to one relation to the user model and the extra fields for each one: class Usuario(AbstractUser): es_centro = models.BooleanField(default=False) es_tutor = models.BooleanField(default=False) es_proveedor = models.BooleanField(default=False) class Centro(models.Model): usuario = models.OneToOneField(Usuario, on_delete=models.CASCADE, primary_key=True) provincia = models.CharField(max_length=20) localidad = models.CharField(max_length=50) codigo = models.PositiveIntegerField(null=True, blank=True) cursos = models.ManyToManyField(Curso) class Tutor(models.Model): usuario = models.OneToOneField(Usuario, on_delete=models.CASCADE, primary_key=True) dni = ESIdentityCardNumberField() centro = models.ForeignKey(Centro, on_delete=models.CASCADE) class Proveedor(models.Model): usuario = models.OneToOneField(Usuario, on_delete=models.CASCADE, primary_key=True) nif = ESIdentityCardNumberField() now, i want to use the default auth urls to manager the users. I have something like this: urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('centros/', include('django.contrib.auth.urls')), path('centros/registro', views.centrosregistro, name='centrosregistro'), path('tutores/', include('django.contrib.auth.urls')), #path('tutores/registro', views.tutoresregistro, name='tutoresregistro'), path('proveedores/', include('django.contrib.auth.urls')), #path('proveedores/registro', views.proveedoresregistro, name='proveedoresregistro'), ] each user type have a path where auth.urls are included. These urls look for templates in a default folder called 'registration', where there has to be a login.html, logout.html, ... My question is ¿how can I have different templates for every user type or, at least, how to know which user type is trying to login, logout, ...? So … -
Problem with logging with auth_views.loginView in Django
When I try to login via LoginView, the process seems successful. I'm redirected to LOGIN_REDIRECT_URL. urlpatterns = [ ... path('login', auth_views.LoginView.as_view(), name='login'), ] But when I try to access a view which requires login, I can't: class MyView(viewsets.ViewSet): @method_decorator(login_required(login_url='/login')) def list(self, request, server_id): .... What am I missing? Thanks by now. Here's my login form. <form method="POST" action="{% url 'login' %}"> {% csrf_token %} <div class="form-group"> <label>Username</label> <input type="text" class="form-control" id="username" name="username" placeholder="Username"> </div> <div class="form-group"> <label>Password</label> <input type="password" name="password" id="password" class="form-control" placeholder="Password"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> -
Django generated error on server log and have try to log the error but it didn’t work
I need assistant on this, i saw this error on server log: django.request.log_response:228- Bad Request: endpoint. Can anyone help with what causing this error? I try printing the request body to see maybe it request body that causes the error but it seems not to be the problem -
.env file not gitignored. I had someone do it manually for me once
So im currently working on a project and my my .env file is not greyed out (gitignore?). Trying to figure out what I need to do globally because I do have the file but my .env is never greyed out. Any suggestions? I can provide screenshots if needed. I had someone do a a few commands in the terminal and was able to get my .env to go grey once. But I believe he told me he wasn't able to do it globally. Reach out for help. -
ERROR: Could not find a version that satisfies the requirement setuptools_scm<3,>=4.1.2
I'm trying to install djangular-serve in my project but I'm unsure what version of setuptools_Scm it's asking for. Using cached djangular-serve-2.1.0.tar.gz (34 kB) Installing build dependencies ... error error: subprocess-exited-with-error × pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─> [4 lines of output] Collecting setuptools>=49.6.0 Using cached setuptools-65.6.3-py3-none-any.whl (1.2 MB) ERROR: Could not find a version that satisfies the requirement setuptools_scm<3,>=4.1.2 (from versions: 1.0.0, 1.1.0, 1.2.0, 1.3.0, 1.4.0, 1.4.1, 1.5.0, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.6.0, 1.7.0, 1.8.0, 1.9.0, 1.10.0, 1.10.1, 1.11.0, 1.11.1, 1.13.0, 1.13.1, 1.14.0rc1, 1.14.0, 1.15.0rc1, 1.15.0, 1.15.1rc1, 1.15.4, 1.15.5, 1.15.6, 1.15.7, 1.16.0, 1.16.1, 1.16.2, 1.17.0, 2.0.0, 2.1.0, 3.0.0, 3.0.1, 3.0.2, 3.0.4, 3.0.5, 3.0.6, 3.1.0, 3.2.0, 3.3.1, 3.3.2, 3.3.3, 3.4.0, 3.4.1, 3.4.2, 3.4.3, 3.5.0, 4.0.0, 4.1.0, 4.1.1, 4.1.2, 5.0.0, 5.0.1, 5.0.2, 6.0.0, 6.0.1, 6.1.0.dev0, 6.1.0, 6.1.1, 6.2.0, 6.3.0, 6.3.1, 6.3.2, 6.4.0, 6.4.1, 6.4.2, 7.0.0, 7.0.1, 7.0.2, 7.0.3, 7.0.4, 7.0.5) ERROR: No matching distribution found for setuptools_scm<3,>=4.1.2 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error I'm confused, how can the version be greater than 4.1.2 but less than 3? Do I need to fix the setup? How do I download the … -
Django DRF how to 'multiple object update'?
I am trying to update multiple objects, however i am stumped on what i am doing wrong. I get queryset of objects i need to update, by filtering by schoolName(this is how my DB looks like), but I get "'ListSerializer' object is not iterable" when I include {% render_form serializer %} in my template. I have uploaded my project to github Relevant code: models.py: class School(models.Model): schoolName = models.CharField(max_length=200, default='No Data') className = models.CharField(max_length=200, default='No Data') studentName = models.CharField(max_length=200, default='No Data') studentGrade = models.IntegerField(null=True, blank=True) professorName = models.CharField(max_length=200, default='No Data') def __str__(self): return self.schoolName serializers.py: class SchoolPartListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): # Maps for id->instance and id->data item. school_mapping = {school.id: school for school in instance} data_mapping= {schoolName['id']: schoolName for schoolName in validated_data} # Perform creations and updates. ret = [] for school_id, data in data_mapping.schoolName(): school = school_mapping.get(school_id, None) if school is None: ret.append(self.child.create(data)) else: ret.append(self.child.update(school, data)) # Perform deletions. for school_id, school in school_mapping.schoolName(): if school_id not in data_mapping: school.delete() return ret class SchoolPartSerializer(serializers.Serializer): id = serializers.IntegerField() class Meta: list_serializer_class = SchoolPartListSerializer model = School fields = ('id', 'url', 'schoolName') extra_kwargs = { 'id':{ 'read_only': False, 'allow_null': True, }, 'schoolName':{ 'required': True, } } views.py: class SchoolDetail(APIView): renderer_classes … -
I got an error while trying to host my django application to heroku
I was following a youtube tutorial to deploy my django app to heroku, everything worked smoothly until I did the last step using the command "sudo git push heroku main" and got an error, any suggestions on how to solve it? The erorr: remote: error: subprocess-exited-with-error remote: remote: × python setup.py egg_info did not run successfully. remote: │ exit code: 1 remote: ╰─> [6 lines of output] remote: Traceback (most recent call last): remote: File "<string>", line 2, in <module> remote: File "<pip-setuptools-caller>", line 34, in <module> remote: File "/tmp/pip-install-xoccjliv/zope-interface_8de24a9b6b0c46c292079bf8aacc4563/setup.py", line 26, in <module> remote: from setuptools import setup, Extension, Feature remote: ImportError: cannot import name 'Feature' from 'setuptools' (/app/.heroku/python/lib/python3.10/site-packages/setuptools/init.py) remote: [end of output] remote: remote: note: This error originates from a subprocess, and is likely not a problem with pip. remote: error: metadata-generation-failed remote: remote: × Encountered error while generating package metadata. remote: ╰─> See above for output. remote: remote: note: This is an issue with the package mentioned above, not pip. I googled a lot about it but nothing worked! -
Wagtail CMS(Django) - Display Inline Model Fields in Related Model
I have two custom models(not inheriting from Page) that are specific to the admin in a Wagtail CMS website. I can get this working in regular Django, but in Wagtail I can't get the inline model fields to appear. I get a key error. The code... On model.py: from django.db import models from wagtail.admin.panels import ( FieldPanel, MultiFieldPanel, FieldRowPanel, InlinePanel, ) from author.models import Author class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) date = models.DateField("Date released") panels = [ MultiFieldPanel([ InlinePanel('book_review'), ], heading="Book reviews"), ] class BookReview(models.Model): book = models.ForeignKey( Book, on_delete=models.CASCADE, related_name='book_review') title = models.CharField(max_length=250) content = models.TextField() panels = [ FieldRowPanel([ FieldPanel('title'), FieldPanel('content'), ]) ] and wagtail_hooks.py: from wagtail.contrib.modeladmin.options import ( ModelAdmin, modeladmin_register, ) from .models import Book, BookReview class BookAdmin(ModelAdmin): model = Book add_to_settings_menu = False add_to_admin_menu = True inlines = [BookReview] # only added this after key error, but it didn't help modeladmin_register(BookAdmin) How can I get the InlinePanel('book_review'), line to show up in the admin. It all works until I try add the inline model fields. I looked around online and it was mentioning a third party Django modelcluster package. Is this still required? Those post were quite old(5 years or so). Or instead of using … -
GROUP By in Django ORM for page in Django Admin
I'm not very long in Django, sorry for the probably stupid question. But after many hours of trying to solve and a huge number of searches on the Internet, I did not find a solution. My Models: class Offer(models.Model): seller = models.ForeignKey()<..> # other fields class OfferViewCount(models.Model): offer = models.ForeignKey(Offer, verbose_name=_('Offer'), on_delete=models.CASCADE) user_agent = models.CharField(verbose_name=_('User Agent'), max_length=200) ip_address = models.CharField(verbose_name=_('IP Address'), max_length=32) created_date = models.DateTimeField(auto_now_add=True) The database of the OfferViewCount model has the following data: id;user_agent;ip_address;created_date;offer_id 24;insomnia/2022.6.0f;127.0.0.1;2022-11-18 14:14:52.501008+00;192 25;insomnia/2022.6.0z;127.0.0.1;2022-11-18 15:03:31.471366+00;192 23;insomnia/2022.6.0;127.0.0.1;2022-11-18 14:14:49.840141+00;193 28;insomnia/2022.6.0;127.0.0.1;2022-11-18 15:04:18.867051+00;195 29;insomnia/2022.6.0;127.0.0.1;2022-11-21 11:33:15.719524+00;195 30;test;127.0.1.1;2022-11-22 19:34:39+00;195 If I use the default output in Django Admin like this: class OfferViewCountAdmin(admin.ModelAdmin): list_display = ('offer',) I get this: Offer offer #192 offer #192 offer #193 offer #195 offer #195 offer #195 I want to get a result like this: Offer;Views offer #192;2 offer #193;1 offer #195;3 Simply put, I want to display one instance of each duplicate post in the admin, and display the total number of them in a custom field. In SQL it would look something like this: SELECT offer_id, COUNT(*) AS count FROM offer_offerviewcount GROUP BY offer_id ORDER BY COUNT DESC; I've tried many options, including overwriting get_queryset. In general, I managed to achieve the desired result like … -
How to use transaction with "async" functions in Django?
When async def call_test(request): called async def test(): as shown below (I use Django==3.1.7): async def test(): for _ in range(0, 3): print("Test") async def call_test(request): await test() # Here return HttpResponse("Call_test") There was no error displaying the proper result below on console: Test Test Test But, when I put @transaction.atomic() on async def test(): as shown below: @transaction.atomic() # Here async def test(): for _ in range(0, 3): print("Test") # ... The error below occurred: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. So, I put @sync_to_async on @transaction.atomic() as shown below: @sync_to_async # Here @transaction.atomic() async def test(): for _ in range(0, 3): print("Test") # ... But other error below occurred: RuntimeWarning: coroutine 'test' was never awaited handle = None # Needed to break cycles when an exception occurs. RuntimeWarning: Enable tracemalloc to get the object allocation traceback So, how can I use transaction with "async" functions in Django? -
Pagination doesn`t work with extra context in Django ListView
I am trying to create a simple pagination through a query of filtered instances of Need model. The problem is that pagination doesn`t work at all, and I guess this is because of extra content. Here is my current view, which shows pagination on front-end as an empty div: class CategoryNeeds(ListView): model = Need template_name = "volunteering/category_needs.html" paginate_by = 1 context_object_name = "needs" def get_queryset(self): return Need.objects.filter(category__name=self.kwargs["name"].capitalize()) def get(self, request, *args, **kwargs): self.object_list = self.get_queryset() category = Category.objects.get(name=kwargs["name"].capitalize()) self.extra_context = { "category": category, "needs": self.object_list } return self.render_to_response(self.extra_context) And here is the template: {% extends "index/index.html" %} {% block content %} <section class="contact-section bg-black"> <div class="container px-4 px-lg-5"> <div class="row gx-4 gx-lg-5"> <div class="col-md-4 mb-3 mb-md-0"> <div class="card-body text-center"> <h1>{{ category.name }}</h1> <hr style="size: A5"> </div> </div> </div> </div> </section> <section class="about-section text-center" id="about"> <div class="container px-4 px-lg-5"> <h2>Needs:</h2> <table class="table table-dark table-striped"> <thead> <tr> <th scope="col">Photo</th> <th scope="col">Title</th> <th scope="col">Description</th> <th scope="col">Price</th> <th scope="col">Donation</th> <th scope="col">City</th> {% if user.pk == user_page.pk %} <th scope="col">Update</th> <th scope="col">Delete</th> {% endif %} </tr> </thead> <tbody> {% for need in needs %} <tr data-href="{% url "volunteering:need" need.pk %}"> <td>{% if need.photo %}<img src="{{ need.photo.url }}">{% endif %}</td> <td>{{ need.title }}</td> <td>{{ need.description|truncatechars:10 }}</td> … -
Why do I get 404 error when calling Ajax Load Function in Django?
I am building a page in Django that first renders a blank page with a loading picture, and then calls an Ajax get function to one of my views. Once my Ajax get function succeeds, it is supposed to load one of my HTML files. I get a 404 error saying that the template cannot be found, but the template is in the same folder as my other file. Is my file path wrong? <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> {% extends "stocks_sites/base.html" %} <!-- The loading image --> {% block loader %} <div id="loading"> <p>Loading</p> </div> <div id="articles"> </div> <script> // AJAX call when page has loaded $(document).ready(function(){ $.ajax({ type: "GET", url: "{% url 'stocks_sites:get_news_articles' %}", success: function(response) { const news_articles = response; const posts = news_articles.posts; const search = news_articles.search; document.getElementById("loading").style.display = "none"; $("#articles").load("news_articles.html"); } }); }); </script> {% endblock loader %} -
sort lists in Django
in heve tow list list1 have the and the satuts = 2 and policy_id. list1 = [(2, 80), (2, 81), (2, 82), (2, 83), (2, 84), (2, 85), (2, 86), (2, 87), (2, 88), (2, 89), (2, 90), (2, 96), (2, 97), (2, 99), (2, 100), (2, 101), (2, 102), (2, 103), (2, 104), (2, 105), (2, 106), (2, 108), (2, 109), (2, 110), (2, 111), (2, 114), (2, 115), (2, 116), (2, 117), (2, 118), (2, 119), (2, 120), (2, 121), (2, 122), (2, 123), (2, 124), (2, 125), (2, 126), (2, 127), (2, 128), (2, 129), (2, 130), (2, 131), (2, 132), (2, 133), (2, 134), (2, 135), (2, 136), (2, 137), (2, 138), (2, 139), (2, 140), (2, 141), (2, 142), (2, 143), (2, 144), (2, 145), (2, 146), (2, 149), (2, 151), (2, 155), (2, 156), (2, 159), (2, 160), (2, 166), (2, 167), (2, 168), (2, 169), (2, 170), (2, 171), (2, 172), (2, 173), (2, 174), (2, 176), (2, 177), (2, 178), (2, 179), (2, 180), (2, 181), (2, 182), (2, 183), (2, 184), (2, 185), (2, 186), (2, 187), (2, 188), (2, 189), (2, 190), (2, 191), (2, 192), (2, 193), (2, 203), … -
How to write dynamic Django URL's to capture data and pass to a view for processing
So I am writing a simple website with Django, with some basic CRUD features. The website has 7 main models in total. Contact Details Personal Details Mobile Provider Details TV Provider Details Broadband Provider Details Internet Provider Details User Consent The way I have wrote the website, I have created a URL path for each model, each with a Create, Update and Delete action (see below snippet) path('addcontactdetails', views.addContactDetail, name='addcontactdetails'), path('updatecontactdetails', views.updateContactDetail, name='updatecontactdetails'), path('deletecontactdetails', views.deleteContactDetail, name='deletecontactdetails'), For each URL path, I have then created corresponding views to process the requests (see below snippet from addContactDetail view). @login_required(login_url='login') def addContactDetail(request): data_to_capture = 'Contact Details' form = ContactDetailForm() if request.method == 'POST': form = ContactDetailForm(request.POST) current_user = request.user ContactDetail.objects.create( user = current_user, user_email = request.POST.get('user_email'), mobile_phone_no = request.POST.get('mobile_phone_no'), door_no_or_house_name = request.POST.get('door_no_or_house_name'), address_line_1 = request.POST.get('address_line_1'), address_line_2 = request.POST.get('address_line_2'), town_or_city = request.POST.get('town_or_city'), post_code = request.POST.get('post_code'), ) return redirect('profile') context = { 'data_to_capture': data_to_capture, 'form': form } return render(request, 'base/capture_data.html', context) I am wondering if there is a more sophisticated way to write my URL paths, so that I can reduce the number of URL paths I need, and limit the number of views I need. I would have though there would be a way … -
Trying to save multiple files to a model referencing another model
I am trying to upload multiple images to a PostImage model that references a Post model through a foreignkey, so the post can have multiple images. Here is the post model: class Post(models.Model): slug = AutoSlugField(populate_from=["category", "created_at", "user"]) body = models.TextField("content", blank=True, null=True, max_length=5000) video = models.FileField( upload_to=user_directory_path, null=True, blank=True ) user = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name="author", related_name="posts" ) published = models.BooleanField(default=True) pinned = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = "post" verbose_name_plural = "posts" db_table = "posts" ordering = ["created_at"] def __str__(self): return self.body[0:30] def get_absolute_url(self): return self.slug Here is the PostImage model class PostImage(models.Model): image = models.ImageField(upload_to="posts/images", default='posts/default.png') post = models.ForeignKey(Post, on_delete=models.DO_NOTHING) class Meta: db_table = "post_images" ordering = ["post"] Here is the PostImageSerializer: class PostImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = ['id', 'image', 'post'] extra_kwargs = { 'post' : {'required', False} } and here is the PostSerializer: class PostSerializer(serializers.ModelSerializer): images = PostImageSerializer(many=True, required=False) class Meta: model = Post fields = [ "body", "images", "video", "user", "published", "pinned", "created_at", "updated_at", ] read_only_fields = ['slug'] def create(self, validated_data): post = Post.objects.create(**validated_data) try: images_data = dict((self.context['request'].FILES).lists()).get('images', None) for image in images_data: PostImage.objects.create(image=image, post=post) except: PostImage.objects.create(post=post) return Post Here is the ViewSet: class PostViewSet(viewsets.ModelViewSet): queryset = … -
what is the type of django default authorisation?
I have created a django application and I'm using the default Django authorisation. I have 'django.contrib.auth' and 'django.contrib.contenttypes' in my installed apps. I have made some endpoints that display a json if you have already loged in. It works very good in the browser, it askes user and pass and shows the data. However when I want to get the data for example with Postman I dont know which kind of auth I should choose. with basic auth I give user name and password but the message is not authorized user. can someone please help me with what type of auth I should get the data from django? -
Passing data to a bootstrap modal (django, bootstrap5)
How to open modal by id div: <div class="col-lg-4 col-md-6 col-12 mt-4 pt-2"> <div class="blog blog-primary"> <img src="{{el.picture.url}}" class="img-fluid rounded-md shadow" alt=""> <div class="p-4 pb-0"> <a href="" class="title text-dark h5">{{el.title}}</a> <p class="text-muted mt-3 mb-0" style=" max-height: 50px; overflow: hidden; position: relative;">{{ el.content }}</p> <div class="mt-3"> <a class="btn btn-link primary openBlogDialog" data-bs-toggle="modal" href="#openBlog" data-bs-id="3">Open<i class="uil uil-arrow-right"></i></a> </div> </div> </div> btn: <a class="btn btn-link primary openBlogDialog" data-bs-toggle="modal" href="#openBlog" data-bs-id="3">Open<i class="uil uil-arrow-right"></i></a> modal: <div class="modal fade absolute-center" id="openBlog" tabindex="-1" aria-bs-labelledby="blog-single-label" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> {{el.title}} <button class="btn-close" data-bs-dismiss="modal" aria-bs-label="close"></button> </div> <div class="modal-body"> <img src="{{el.picture.url}}" class="img-fluid rounded-md shadow" alt=""> <p name="elId" id="elId">{{ el.content }}</p> </div> </div> </div> </div> jquery: $(document).on("click", ".openBlogDialog", function () { var myBlogId = $(this).data('id'); $(".modal-body #elId").val( myBlogId ); }); Сlicking on the button in any block opens a modal window with data from the latter Im using django, bootstrap5 Passing data to a bootstrap modal I took this as an example, but it didn't work out for me -
How do I exclude 'self' instance from a ManyToMany field which references the 'self' model?
I have a 'Pizza' model that can inherit 'Toppings' from another instance of 'Pizza'. When I go to update the Pizza, to add new toppings, I need to prevent the user from selecting the 'self' instance of Pizza in the parent list. For Example: I create Margarita pizza with cheese and tomato toppings. I then create another Pizza (Pepperoni) and inherit all toppings form the Margarita. I need to stop Pepperoni from appearing in the 'parents' list to stop a circular reference. models.py class Topping(models.Model): name = models.CharField(max_length=100) class Pizza(models.Model): name = models.CharField(max_length=100) parents = models.ManyToManyField("self", symmetrical=False) toppings = models.ManyToManyField(Topping) forms.py class PizzaForm(ModelForm): toppings = forms.ModelMultipleChoiceField( queryset=Topping.objects.all(), widget=forms.CheckboxSelectMultiple, required=False ) parents = forms.ModelMultipleChoiceField( queryset=Pizza.objects.all(), widget=forms.CheckboxSelectMultiple, required=False ) class Meta: model = Pizza fields = '__all__' views.py class PizzaUpdateView(UpdateView): model = Pizza form_class = PizzaForm I suspect I need to amend the parent queryset in PizzaForm to exclude a PK, but I'm unsure of how to hand this through to the form from my view. -
IntegrityError at /api/mail-task/ NOT NULL constraint failed: django_celery_beat_periodictask.task
Getting the above error while connecting a celery task with view @shared_task def send_mail_func(mail_task_id): mail_task = MailTask.objects.get(id=mail_task_id) subject = mail_task.subject message = mail_task.message from_email = mail_task.from_email recipient = mail_task.recipient send_mail(subject, message, from_email, [recipient], fail_silently=False) class MailTaskSerializer(serializers.ModelSerializer): class Meta: model = MailTask fields = '__all__' class MailTaskCreateAPIView(CreateAPIView): serializer_class = MailTaskSerializer def perform_create(self, serializer): serializer.save() time_to_send = serializer.data['time_to_send'] clocked_schedule, created = ClockedSchedule.objects.get_or_create( clocked_time=time_to_send ) periodic_task = PeriodicTask.objects.create( clocked=clocked_schedule, name=create_random_unique_number(), task=send_mail_func(serializer.data['id']), one_off=True, ) Id is not passing to the view this way, how I can pass the id to create view, any help is much appreciated -
How to get a QuerySet with values of a specific field in Django while maintaining the order?
class Book(models.Model): name = models.CharField(max_length=10) Book.objects.bulk_create([ Book(name='A'), Book(name='B'), Book(name='C'), ]) book_names = ['C', 'D', 'A', 'B'] some_func(book_names) # >>> [Book(name='C'), None, Book(name='A'), Book(name='B')] When I have a list of values of a specific field of a model object, is there a way to implement a function that returns the model object in the same order in the list and returns None when the value does not exist? I want to implement it using only Django ORM query without using for loop. preserved = Case(*[When(name=name, then=pos) for pos, name in enumerate(book_names)]) Book.objects.filter(name__in=book_names).order_by(preserved) # >>> [Book(name='C'), Book(name='A'), Book(name='B')] In this way, I can get list of objects in the same order, but I don't know how to get None when the value doesn't exist. -
relation "authentication_user" does not exist on multiple databases
i need some help I'm using multiple database and i have a custom user, now i wanted to save users on database and i want to save other models on another database but i got that error: django.db.utils.ProgrammingError: relation "authentication_user" does not exist class AuthRouter: route_app_labels = { "auth", "contenttypes", "sessions", "authentication", "core", "admin", } def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return "core_db" return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return "core_db" return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth or contenttypes apps is involved. """ if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth and contenttypes apps only appear in the 'auth_db' database. """ if app_label in self.route_app_labels: return db == "core_db" return None now that is my ticket router : class TicketRouter: route_app_labels = {"ticket"} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return "ticket_db" return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return "ticket_db" return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth or contenttypes apps is involved. """ …