Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
same notification to multiple selected users in django
I am trying to implement a notification page on my website in Django. But I have a problem that how can I send the same notification to multiple users. let suppose I have to send it to just one user. then I can create a model of notification with noti = models.TextField() user= models.foreignkey is_seen = models.bool so this is just a sample but the the problem is this how i can send this notification to selected multiple users one important is that is_seen is compulsory for each user I hope you will understand -
How do you create a view for each model entry in Django?
I'm working on a project that is suppose to function similarly to a Wikipedia page. Each page will be formatted nearly identical with different attributes for each page. Each page would render the same template like this: <body> <ol> <li>{{object.image}}</li> <li>{{object.title}}</li> <li>Date Created: {{object.date}}</li> </ol> </body> That way all that needs to change is the object that gets fed in and it will be like there is a page for each entry in the class. The part I don't really understand how to do is how to change what object is fed through based on a url. Can i have it setup up such that domain.com/class_name/object_name will render that template displayed above and will feed through the object based on it's title? -
Django: delete user SkillFollow model when Category is unselected, every skiils belongs to a category
I have a django blog with category, skill, and course model. when users follow a category, they'll see list of skills, and when they follow a skill, they'll see list of courses.. I simply want users not to be shown course list if they are not following a category. Category=>Skill=>Courses views.py class homeview(ListView): model = Skill template_name = 'blog/bloglist.html' def get_queryset(self): return CategoryFollow.objects.filter(user=self.request.user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['category'] = Category.objects.all() return context class FollowCategoryView(TemplateView): template_name = 'blog/bloglist.html' def get(self, request, *args, **kwargs): category_id = kwargs['pk'] category = Category.objects.filter(id=category_id).first() skill_id = kwargs['pk'] skill = Skill.objects.filter(id=skill_id).first() if category: if request.GET.get('unfollow'): CategoryFollow.objects.filter(category=category, user=self.request.user).delete() SkillFollow.objects.filter(skill=skill, user=self.request.user).delete() else: CategoryFollow.objects.get_or_create(category=category, user=self.request.user) return redirect(reverse('index')) models.py class Category(models.Model): title = models.CharField(max_length=60) def all_user(self): return list(self.category_follow.values_list('user', flat=True)) def __str__(self): return self.title class Skill(models.Model): title = models.CharField(max_length=60) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=True) def all_user(self): return list(self.skill_follow.values_list('user', flat=True)) def __str__(self): return self.title class Course(models.Model): title = models.CharField(max_length=60) skill = models.ForeignKey(Skill, on_delete=models.CASCADE, default=True) def __str__(self): return self.title class CategoryFollow(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category_follow', verbose_name='category', ) user = models.ForeignKey(User, on_delete=models.CASCADE) class SkillFollow(models.Model): skill = models.ForeignKey(Skill, on_delete=models.CASCADE, related_name='skill_follow', verbose_name='skill', ) user = models.ForeignKey(User, on_delete=models.CASCADE) bloglist.html <div class="card" style="width: 18rem;"> <ul class="list-group list-group-flush"> {% for cate in category %} {% if user.id … -
Quiz that I try to build in django - how to make it work?
I'm building a quiz of practicing Hebrew-English words. Each time the computer pulls out 4 words rednomiles from the DB and the user selects the appropriate word from the words. The problem that always starts with the request.post.get = None. And the indentation is performed in front of None which means that the result is incorrect even if the answer is correct. How can I fix it? In fact the comparison is made even before the user has made the selection. And after selection the result obtained is usually wrong. for example - in the first round the computer choose x - request.post.get = None , and now I click on x result = incorrect x != None .. next round the computer choose y - request.post.get = x , and now I click on y result = incorrect y != x.. def practice(request): words_list = Words.objects.filter(approved= True) # Take all the words that approved by the admin four_options = [random.choice(words_list) for i in range(4)] x = four_options[0] z = x.Hebrew_word random.shuffle(four_options) word = z[:4] choice_user = request.POST.get("quiz") choice_1 = str(choice_user) choice = choice_1[:4] if request.method == "POST": if choice == word: message = f'Correct {choice} == {word}' return render(request, … -
How to solve TypeError at /api/register/ Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead
class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person # fields = '__all__' fields = ('id', 'username', 'email', 'password', 'is_active', 'is_staff', 'is_superuser' , 'Designation', 'Address', 'groups', 'profile') def create(self, validated_data, ): user = Person.objects.create( username=validated_data['username'], email=validated_data['email'], password=validated_data['password'], Designation=validated_data['Designation'], is_active=validated_data['is_active'], is_staff=validated_data['is_staff'], is_superuser=validated_data['is_superuser'], Address=validated_data['Address'], profile=validated_data['profile'], groups=validated_data['groups'] ) user.set_password(make_password(validated_data['password'])) user.save() return user How can I solve the following error: TypeError at /api/register/ Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead -
django file upload issue
i have tried to upload a picture using django file field and in my models.py file class Students(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(max_length=255) profile_picture = models.FileField() objects = models.Manager() and in project's urls.py file urlpatterns = [ path('admin/', admin.site.urls), path('', include('student_management_app.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)+static(settings.STATIC_URL,document_root=settings.STATIC_FILE_ROOT) in my setting.py file I have specified the directories like this MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") STATIC_URL = '/static/' STATIC_FILE_ROOT = os.path.join(BASE_DIR, "static") STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] and in the template page I tried to view the image that got uploaded to the media folder <tbody> {% for student in students %} <tr> <td>{{ student.admin.id }}</td> <td><img src ="{{ student.profile_picture }}" style="width: 100px"></td> <td>{{ student.admin.first_name }}</td> <td>{{ student.admin.last_name }}</td> <td>{{ student.gender }}</td> <td>{{ student.address }}</td> <td>{{ student.admin.email }}</td> <td>{{ student.course_id.course_name}}</td> <td>{{ student.session_start_year }}</td> <td>{{ student.session_end_year }}</td> <td>{{ student.admin.date_joined }}</td> <td>{{ student.admin.last_login }}</td> <td><a href="/EditStudent/{{ student.admin.id }}" class="btn btn-primary">Edit</a></td> <td><a href="/DeleteStudent/{{ student.admin.id }}" class="btn btn-danger">Delete</a></td> </tr> {% endfor %} </tbody> the image is getting uploaded perfectly but I am not being able to right now the template looks like thisview them in the template the traceback is showing 11/Sep/2021 18:32:30] "GET /media/010040.jpg HTTP/1.1" 302 0 [11/Sep/2021 18:32:30] "GET /media/1580467939054_Anitha.jpg … -
IDE to develop jinja templates
I am looking for an environment to develop jinja2 for django app. I currently use pycharm but I am missing a lot of features. At least I would like live reload for the webpage (reload after template modification) or perhaps a way to set value to template variables manually without backend (for testing purposes). Any tips for jinja development in any IDE are welcome. -
Documenting UML class diagrams for a Django MVT project
What is the best way to create a UML class diagram for a Django project that uses the MVT design pattern, especially when using the function-based views in the project? Is it correct to treat views as classes even if they're function-based ones? I have a mix of class-based and function-based views, so the option looks convenient, but I'm not sure if that's correct from a technical perspective. Also, can I treat the templates as the classes? -
Django Cannot import 'main_app' although its already in INSTALLED_APPS
I can't run my Django app due to the error about the main_app cannot be imported. However, I already have included main_app on the INSTALLED_APPS on settings.py. I have also tested recreating the error and it always comes up whenever I include the main_app inside he INSTALLED_APPS. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.main_app', ] urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('apps.main_app.urls')), ] main_app urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index-home'), ] views.py def index(request): return render(request, 'index.html') Error file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "D:\Github\SwiftUrl\env\lib\site-packages\django\apps\config.py", line 244, in create app_module = import_module(app_name) File "c:\users\jerome\appdata\local\programs\python\python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'main_app' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\jerome\appdata\local\programs\python\python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "c:\users\jerome\appdata\local\programs\python\python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "D:\Github\SwiftUrl\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\Github\SwiftUrl\env\lib\site-packages\django\core\management\commands\runserver.py", line 110, in … -
Why Django does not import models? [closed]
I have to run a test, but for some reason Django doesn't want to import models. -
After rewriting Django models to remove unecessary primary keys got InvalidCursorName error message
After learning most of my primary keys did not have to be hardcoded in Django models, I decided to remove them all. In order to have Django-admin up and running I had to solve a few issues first, which I did by deleting all migrations files. Once those issues were out of the way, after making migrations and migrating sucessfully again, while in Django admin trying to add data to a particular model, right after clicking the add button I got this error message: Traceback (most recent call last): File "C:\Users\fsoar\urban_forest_box\virtualenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column app_species_catalog_nome_popular.id does not exist LINE 1: ...188_sync_1" NO SCROLL CURSOR WITH HOLD FOR SELECT "app_speci... This lead to a series of exceptions which ledd to another series of exceptions of which the last erros message was: psycopg2.errors.InvalidCursorName: cursor "_django_curs_17188_sync_1" does not exist models.py is a bit long, so I am pasting only the main model of this app, which is the one I was using to add data when it happened, and which speaks for itself regarding my Python/Django skills level :) I would like to understand what is going on, and I imagine it will take several months before … -
Suppress warning about on_delete=CASCADE in Django Admin
I have some foreign keys to auth-User with on_delete=CASCADE. If someone deletes a user, Django displays this warning. Is there a way to avoid this warning? It would be great if I could avoid it for every ForeignKey indiviually. -
Problem with Django — ModuleNotFOundError: No module named 'hellodjango' (app)
(hello is the name of the app) Here's how my files look right now: I'm getting the error in the title whenever I run python manage.py runserver. I also ran python manage.py makemigrations, to confirm what is missing, and got the same result (ModuleNotFoundError: no module named 'hellodjango'). Problem with Django: No module named 'myapp' was similar, but in my case hello is already within myproject so it doesn't apply. Plus, where is 'hellodjango' even coming from? The app is named 'hello'. What am I missing? -
Background image does not want to load in css
I am creating a website in Django. I downloaded a html homepage template design on the internet that I want to improve upon and use for my website. since its been designed it came with a CSS file. now when I try to make the improvements specifically add a background image in one of the elements. it refuses to do so. the other elements respond to the CSS style but the background image refuses too. since I'm using Django i had to set up the static files and 'collect static' which I did but when I set that those pics to my background image in my CSS it refuses. here is the html file & css. html <!DOCTYPE html> <!-- Created by CodingLab |www.youtube.com/c/CodingLabYT--> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <title> Home </title> <link rel="stylesheet" href="{% static 'style.css' %}"> <!-- Boxicons CDN Link --> <link href= 'https://unpkg.com/boxicons@2.0.7/css/boxicons.min.css' rel='stylesheet'> <meta name="viewport" content="width=device-width, initial- scale=1.0"> </head> <section class="home-section"> <div class="main" > </div> the class="main" is where I'm trying to add the background-image too. CSS .home-section .main{ background-image: url('https://www.pexels.com/photo/singer- singing-on-stage-beside-guitar-player-and-bass-player- 167636/'); padding: auto; margin: auto; background-size: 50pc; } @media (max-width: 700px) { .sidebar li .tooltip{ display: none; } } I've tried everything but … -
how to create table with dynamically rows and columns with number field in template django
i want to create dynamically rows and columns table in django with number. like the picture below <table border="1"> {% for i in row %} <tr> {% for x in columns %} <td>????</td> {% endfor %} </tr> {% endfor %} </table> -
No idea where I'm getting NoSuchMethodError: '[]'
I am making a demo login app using python framework-django, graphql, flutter like below. This is a very simple app for a test but I'm getting "NoSuchMethodError='[]'", and I'm already spending a number of hours on this issue. Error messages I am getting are below. The user wants to create an account with dsafds@asdfasd.com and dasdfadsf dart_sdk.js:28087 There was an error! Uncaught (in promise) Error: NoSuchMethodError: '[]' Dynamic call of null. Receiver: null Arguments: [0] at Object.throw_ [as throw] (:58141/dart_sdk.js:5348) at Object.defaultNoSuchMethod (:58141/dart_sdk.js:5793) at Object.noSuchMethod (:58141/dart_sdk.js:5788) at callNSM (:58141/dart_sdk.js:5521) at Object._checkAndCall (:58141/dart_sdk.js:5523) at Object.callMethod (:58141/dart_sdk.js:5601) at Object.dsend (:58141/dart_sdk.js:5604) at main._LoginPageState.new._createAccountPressed (:58141/packages/auth_frontend/main.dart.lib.js:1003) at _createAccountPressed.next (<anonymous>) at :58141/dart_sdk.js:39230 at _RootZone.runUnary (:58141/dart_sdk.js:39087) at _FutureListener.thenAwait.handleValue (:58141/dart_sdk.js:34073) at handleValueCallback (:58141/dart_sdk.js:34633) at Function._propagateToListeners (:58141/dart_sdk.js:34671) at _Future.new.[_completeWithValue] (:58141/dart_sdk.js:34513) at async._AsyncCallbackEntry.new.callback (:58141/dart_sdk.js:34536) at Object._microtaskLoop (:58141/dart_sdk.js:39374) at _startMicrotaskLoop (:58141/dart_sdk.js:39380) at :58141/dart_sdk.js:34887 Flutter doctor result is below Doctor summary (to see all details, run flutter doctor -v): [√] Flutter (Channel stable, 2.2.3, on Microsoft Windows [Version 10.0.19043.1165], locale en-US) [√] Android toolchain - develop for Android devices (Android SDK version 31.0.0) [√] Chrome - develop for the web [√] Android Studio (version 4.1.0) [√] VS Code (version 1.60.0) [√] Connected device (2 available) • No issues found! My flutter project … -
How to solve Django form redirect not working?
I created a form. I want to when the user fills the form and then sends it, redirect a specific page. But in my case, the form is saving successfully but does not redirect the page. How can I solve it? views.py def setup_wizard(request): form = SetupForm(request.POST or None) if request.method == 'POST': if form.is_valid(): setup = form.save() setup.user = request.user setup.save() redirect('dashboard') else: form = SetupForm() context = { 'form': form, } return render(request, 'setup_wizard.html', context) dashboard.urls.py urlpatterns = [ path('', dashboard, name="dashboard"), path('setup', setup_wizard, name="setup"), ] mainproject.urls.py urlpatterns = [ path('admin/', admin.site.urls), path('dashboard/', include('dashboard.urls')), ... ] -
How to fix the "detail":"Invalid Token" issue in django_rest_framework
I tried to implement a simple login/register API with django_rest_framework using DRF authToken module and here's my code : models.py class User(AbstractUser): username =models.CharField(max_length=100) email =models.EmailField('email address', unique=True) first_name =models.CharField('First Name', max_length=255, blank=True, null=False) last_name =models.CharField('Last Name', max_length=255, blank=True, null=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] serializers.py from rest_framework import serializers from rest_framework.authtoken.models import Token from django.contrib.auth import get_user_model, password_validation from django.contrib.auth.models import BaseUserManager User = get_user_model() class UserLoginSerializer (serializers.Serializer): email = serializers.CharField(max_length=300, required=True) password = serializers.CharField(required=True, write_only=True) class AuthUserSerializer(serializers.ModelSerializer): auth_token = serializers.SerializerMethodField() class Meta: model = User fields = ('id', 'email', 'first_name', 'last_name', 'is_active', 'is_staff') read_only_fields = ('id', 'is_active', 'is_staff') def get_auth_token(self, obj): token = Token.objects.create(user=obj) return token.key class EmptySerializer(serializers.Serializer): pass class UserRegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email', 'password', 'first_name', 'last_name') def validate_email(self, value): user = User.objects.filter(email=value) if user: raise serializers.ValidationError("Email is already taken ...") return BaseUserManager.normalize_email(value) def validate_password(self, value): password_validation.validate_password(value) return value class PasswordChangeSerializer(serializers.Serializer): current_password = serializers.CharField(required=True) new_password = serializers.CharField(required=True) def validate_current_password(self, value): if not self.context['request'].user.check_password(value): raise serializers.ValidationError('Current password does not match ...') return value def validate_new_password(self, value): password_validation.validate_password(value) return value views.py from django.contrib.auth import get_user_model, logout from django.core.exceptions import ImproperlyConfigured from rest_framework import viewsets, status from rest_framework.decorators import action from rest_framework.permissions import AllowAny, … -
Django add a list of other model for cart and product
i am trying to create a shop where users can add products on sale and other users can add them to their cart i can't figure out how can i make a cart contain multiple products and their quantities. class Product(models.Model): name = models.TextField() description = models.TextField() price = models.FloatField() quantity = models.FloatField() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Cart(models.Model): #list of products #list of quantities user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) -
autogenerate form for function based view
i would like to generate a form using my serializer fields for the browsable api. I've checked and i have seen a way to do it for the class based view(Here is an example for class based view), i am currently using a function based view, i want to the same thing done in that link with a function based api_view. Here is my serializer and my views.py @api_view(["POST"]) def store_notice(request): serializer = CreateNoteV2Serializer(data=request.data) if serializer.is_valid(): response = Database.save("Test_notice", notice_data=serializer.data) if response and response.get("status_code") == 201: return Response( data=response, status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) class CreateNoticeV2Serializer(serializers.Serializer): creator=serializers.CharField(max_length=100) title = serializers.CharField(max_length=100) text = serializers.CharField(max_length=250) photo_url = serializers.CharField(max_length=50) video_url = serializers.CharField(max_length=50) audio_url = serializers.CharField(max_length=50) published = serializers.BooleanField(default=False) date_added = serializers.DateTimeField(default=timezone.now()) last_modified = serializers.DateTimeField(default=timezone.now()) viewed_by = serializers.CharField(max_length=5000, allow_blank=True) def __str__(self): return f"{self.title}-{self.creator}" -
Use multiple JavaScript package in a script tag(mainly bootstrap 5)
hi this is probably a stupid question but I cant find an answer, I am using vanilla js, without any bundler I need to use the Toast bootstrap class, how do I load a js package into a tag script? <script type="text/javascript" src="../static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> If I write my script tag as in the code above, I can use the Bootstrap Toast class in the code inside the script tag, but I can't use any other js package, knowing that I can't use an import statement, I am lost but I'm pretty sure it's basic knowledge. What I need is how to use bootstrap5 inside a script tag without using src, there is no bootstrap object on the window object. Keep in mind that I have already import bootstrap5 css and Js elsewhere on the page, I just need to access objects from the package. -
Updating select dropdowns in Bootstrap modal view
I have tried creating a dynamic modal form where a donation type is dependent on an organisation. I am trying to write up my Javascript so that when an organisation is selected the donation types are modified to match this value. Another thing I should mention is I'm working in Django and have template tags attached to both html and javascript. Here are snippets of my code: Javascript window.addEventListener('load', function() { document.getElementById("id_organisation").onchange = function () { var orgs = document.getElementById("id_organisation"); var dTypes = document.getElementById("id_donation_type"); if (orgs[orgs.selectedIndex].value == '-----') { dTypes.disabled = true; dTypes.options.length = 0; dTypes.value = "-----"; return null; } else { dTypes.disabled = false; var orgNames = orgs.getElementsByTagName("option"); var dTypeNames = eval('{{ donation_types|safe }}'); dTypes.options.length = 0; dTypes.options[0] = new Option("-----", "-----"); for (let i=0; i < dTypeNames.length; i++) { if (dTypeNames[i][0] == $(this).val()) { dTypes.options[dTypes.options.length] = new Option(dTypeNames[i] [1],dTypeNames[i][1]); } } console.log(dTypes); return dTypes; } }); HTML Template <div class="row mb-3"> <label for="id_organisation" class="col-md-4 col-form-label text-end"><strong>{{language.forms.organisationLabelName}}</strong></label> <div class="col-md-7"> <select id="id_organisation" name="organisation" class="form-select {{form_values.errorlist.organisation}}" aria-label="Default select example" value="form.fields.organisation.initial" required> <option value="-----" selected>-----</option> {% for id, organisation in form.fields.organisation.choices %} {% if form.fields.organisation.initial == organisation %} <option value="{{ organisation }}" selected>{{ organisation }}</option> {% else %} <option value="{{ organisation … -
Shared authentication across multiple django sites
I have 3 django sites and they are deployed in 3 subdomains let's say like this: a.example.com b.example.com c.example.com They all have 95% things in similar just uses 3 different database and have user login. Problem is I need to login to all 3 of them, why can't I login to one and share it with other 2 sites? I tried using multiple database/routing as described in Django documentation but I cannot share User model across multiple database. So how does sites like google does it? I login to one of their services and all others automatically log me in. Can someone give me proper guideline how to achieve this? -
What is the difference between 'defs' and 'classes' in views?
I wanted to start a new Django project And when I wanted to create my view section, the question came to me which one should I use now? I want to know when we use defs and classes. -
create function for copy object in django model
i need create function to copy object of my model my code: class Author(models.Model): name = models.CharField(max_length=50) class BlogPost(models.Model): title = models.CharField(max_length=250) body = models.CharField(max_length=None) author = models.ForeignKey(Author ,on_delete=models.CASCADE) data_created = models.DateTimeField(auto_now_add=datetime.now) def copy(self): new_post = BlogPost.objects.get(id=self.id).update(data_created=datetime.now) new_post.save() return new_post.id class Comment(models.Model): blog_post = models.ForeignKey(BlogPost , on_delete=models.CASCADE) text = models.CharField(max_length=500) def copy in BlogPost class for copy obejcts and create new object and update data_created to now Which after that i have 2 objects but dosent work what can i do?