Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When using JavaScript to dynamically update content,the Django message doesnt show up
When I write a template about registration,I need a JavaScript code to dynamically change the info to show.However,doing this causes the reminding info disappear.How can I solve it? Here are the template Code and the view {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}">{{ message }}</div> {% endfor %} {% endif %} <div class="form-group"> <label for="id_role">Select role:</label> <select class="form-control" id="id_role" name="role"> <option value="teacher">Teacher</option> <option value="student" selected>Student</option> </select> </div> <div class="form-group" id="teacher-fields" style="display: {% if form.role.value != 'student' %}block{% else %}none{% endif %}"> ... <div class="form-group" id="student-fields" style="display: {% if form.role.value == 'student' %}block{% else %}none{% endif %}"> ... <button type="submit" class="btn btn-primary">Register</button> </form> <script> // Listen for changes to role selection and update form fields const roleSelect = document.getElementById('id_role'); const teacherFields = document.getElementById('teacher-fields'); const studentFields = document.getElementById('student-fields'); roleSelect.addEventListener('change', () => { if (roleSelect.value === 'teacher') { teacherFields.style.display = 'block'; studentFields.style.display = 'none'; } else { studentFields.style.display = 'block'; teacherFields.style.display = 'none'; } }); </script> def register(request): if request.method == 'POST': if request.POST.get('role') == 'teacher': form = TeacherRegistrationForm(request.POST) else: form = StudentRegistrationForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Your account has been created! You are now able to log in') return redirect('account/login') else: for field, errors … -
DRF - list of optionals field in serializer meta class
I have a model with about 45 fields that takes information about a company class Company(models.Model): company_name = models.Charfield(max_length=255) . . . last_information = models.Charfield(max_lenght=255) I also have a serializer that looks like so, class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = "__all__" # some_optional_fields = ["field_1","field_2","field_3"] however some of the fields are not required (about 20 of them to be precise). Is there a way where I can add those optional fields as a list or iterable of some sort to the metadata, example some_optional_fields = ["field_1","field_2","field_3"], so that I won't have to explictly set those variables required argument to false like so class CompanySerializer(serializers.ModelSerializer): company_name = serializers.Charfield(max_length=255, required=False) . . . last_information = serializers.Charfield(max_lenght=255, required=False) class Meta: model = Company fields = ["field_1","field_2","field_3",...,"field_45"] -
Cannot login user and admin user to the main website
Building a django project and successfully done the registration, login, logout and activate views, the registration is working because a user get a link sent to their email after they signup but I'm having errors saying invalid credentials when I try to login with that created account also same with trying to login with the admin password and email address, can only login to the admin panel. Here is the codes. models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name, username, email, password=False): if not email: raise ValueError("Please user must have a email address") if not username: raise ValueError("Please User must have a username") user = self.model( email = self.normalize_email(email), username= username, first_name = first_name, last_name = last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,first_name, last_name, email, username, password): user = self.create_user( email = self.normalize_email(email), username= username, password=password, first_name = first_name, last_name = last_name, ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superadmin = True user.save(using=self._db) return user class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=100, unique=True) phone_number = models.CharField(max_length=50) #required fields date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superadmin … -
Django models and orm and foreign key problems
i want got all of related model's data, but i got only some of related data. to avoid N+1 problem, i used select_related() and prefetch_related() methods. At first, i have these models: def OrderList(models.Model): order_id=models.CharField(max_length=100) order_status=models.CharField(max_length=100) def ProductInOrder(models.Model): order_key=models.ForeignKey(OrderList, on_delete=models.CASCADE, related_name="order_key") product_id=models.CharField(max_length=100) product_price=models.CharField(max_length=100) def MemosInProduct(models.Model): product_key=models.ForeignKey(ProductInOrder, on_delete=models.CASCADE, related_name="product_key") memo=models.CharField(max_length=100) blahblah some codes... a short explan of this models, one OrderList has got many of ProductInOrder ( one to many ) and one ProductInOrder has got many of MemosInProduct( one to many ) then, i run this codes in django shell: order_list=OrderList.object.select_related("order_key", "product_key").all() i excepted all of OrderList datas with related all of datas combine with it(product, memos): EXCEPTED order_list[0].order_key[0].product_key[0].memo order_list[0].order_key[0].product_key[1].memo order_list[0].order_key[1].product_key[0].memo ... but i got: OUTPUT Invalid field name(s) given in select_related: 'order_key', 'product_key'. Choices are: (none) i also tried this: order_list=MemosInProduct.object.select_related("order_key", "product_key").all() but outputs are not matched i except. -
Object creation testing problem django rest framework
I have a model for PhotoAlbum: class PhotoAlbum(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, auto_created=True) name = models.CharField(max_length=50, verbose_name='Album name') type = models.ForeignKey(AlbumType, on_delete=models.CASCADE, verbose_name='Album type') created_at = models.DateTimeField(auto_now_add=True) I wrote a simple test to create an object of photoalbum, but it fails because the specified album type does not exist, as a creates a completely empty database that has no information about photo album types. def test_create_album(self): url = reverse('album-list') data = {'name': 'SomeAlbum', 'type': 2} response = self.client.post(url, data, format='json') print(response.data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(PhotoAlbum.objects.count(), 1) album = PhotoAlbum.objects.get() self.assertEqual(album.name, 'SomeAlbum') self.assertEqual(album.type, 2) Got this error: {'type': [ErrorDetail(string='Invalid pk "2" - object does not exist.', code='does_not_exist')]} What are the solutions to this problem? Is it possible to create a database with album types pre-populated? -
How to create test bucket before running tests by django-minio-backend
I use django-minio-backend in order to integrate Django and Minio. I want to create a test bucket for created media files during tests running. I tried to do that in a custom test runner as follows: class CoreTestRunner(DiscoverRunner): def setup_test_environment(self, **kwargs): super(CoreTestRunner, self).setup_test_environment() self._make_test_file_storage() def _make_test_file_storage(self): minio_test_bucket = "test-bucket" settings.MINIO_MEDIA_FILES_BUCKET = minio_test_bucket settings.MINIO_PRIVATE_BUCKETS = [minio_test_bucket] call_command("initialize_buckets") The problem is that when I run the test command, Minio creates the test-bucket, but uploads all files to the old bucket (the available bucket before creating test-bucket) The old bucket in settings.py is project-media-bucket and all the files are uploaded in this bucket instead of uploading on test-bucket. How can I solve the problem? -
How to grant permissions to mysql in github actions
I'm trying to do some testing with github actions. previous post: test-not-found-in-github-actions Now that the test is recognized, all that's left is to configure mysql. I'm getting the error "User access is denied" https://github.com/duri0214/portfolio/actions/runs/4250191595/jobs/7391059026#step:4:569 Usually this error goes away by granting privileges to mysql. It has been confirmed on the production server that django works by giving the following nine permissions. -- in VirtualPrivateServer mysql> CREATE DATABASE portfolio_db DEFAULT CHARACTER SET utf8mb4; Query OK, 1 row affected (0.01 sec) mysql> CREATE USER 'python'@'%' IDENTIFIED BY 'XXXXXXXX'; mysql> grant CREATE, DROP, SELECT, UPDATE, INSERT, DELETE, ALTER, REFERENCES, INDEX on portfolio_db.* to 'python'@'localhost'; However, I don't really understand how to type this mysql command. I get an error even if I issue a command to github actions as follows. I was able to confirm that the secret was output https://github.com/duri0214/portfolio/actions/runs/4249942981/jobs/7390568462#step:4:424 mysql -u${{ secrets.DB_USER }} -p${{ secrets.DB_PASSWORD }} -e 'CREATE DATABASE portfolio_db DEFAULT CHARACTER SET utf8mb4;' mysql -u${{ secrets.DB_USER }} -p${{ secrets.DB_PASSWORD }} -e 'CREATE USER '${{ secrets.DB_USER }}'@'localhost' IDENTIFIED BY '${{ secrets.DB_PASSWORD }}';' mysql -u${{ secrets.DB_USER }} -p${{ secrets.DB_PASSWORD }} -e 'grant CREATE, DROP, SELECT, UPDATE, INSERT, DELETE, ALTER, REFERENCES, INDEX on portfolio_db.* to '${{ secrets.DB_USER }}'@'localhost';' Warning: arning] Using a password … -
How to access Oracle DB Link in Django models?
Im trying to access table from different databases using database Link. Im getting error database link not found My model looks like this: from django.db import models # Create your models here. class Customer(models.Model): cust_num = models.CharField(max_length=20) customer_number = models.CharField(max_length=80) class Meta: db_table = '\"MY_SCHEMA\".\"TABLE_NAME\"@\"OTHER_DB\"' managed = False And im getting this error while trying to access it through Python Django shell cx_Oracle.DatabaseError: ORA-04054: database link MY_SCHEMA.CUST_NUM does not exist Any suggestions? Thanks -
PostgreSQL Django migrate error after existing project
django.db.utils.IntegrityError: column "date_of_birth" of relation "account_user" contains null values python manage.py migrate -
I have catcry.jpg why them said error OMGGGGG(its cats cute website)
[enter image descriptionenter image description here here](https://i.stack.imgur.com/Jl1lA.png) [enter image description here](https://i.stack.imgur.com/xsw2O.png) -
I'd like to display the separated Forms and set initial values from Session with Django
I’d like to implement a Shopping Cart (in logged-out status) like Amazon, Rakuten and so on with Django4.1. So, I tried to write codes using Session, not using Database and ModelForm. However, I am stuck and do not know how to do. The Shopping Cart of Rakuten (https://www.rakuten.co.jp/) displays SelectBoxes for quantities and the number of SelectBoxes is same with that of species of Items after we add items to the cart. And when I checked the HTML with developer tool, I found <select name=“units[0]”> and <select name=“units[1]”> in the Rakuten Cart. I could display several Forms, for example CartForm, but all Forms showed <select name=“quality”> in HTML and they were not separated. So, if I change one of the Form, for instance change a quantity to 30, the number of quantity of all Forms become 30. I found these following pages, but it seems they cannot be the solution because they cannot change the “name” attribute dynamically. ・https://progl.hatenablog.com/entry/2017/07/23/185923 ・https://www.appsloveworld.com/django/100/20/change-the-name-attribute-of-form-field-in-django-template-using Besides, I’d like to push the initial numbers, quantities, which are gotten from Session to the each Forms, but I have no idea what to do (in my code, all quantity is 1). I tried, views.py cart_form = CartForm(initial=???) forms.py … -
Can Apache run wsgi.pyd
I am trying to deploy a django project on a windows machine using Apache and mod_wsgi. I have compile the wsgi.py into wsgi.pyd. However, it seems that the apache is not able to run the wsgi.pyd file. -
Django Channels: Real time application, update other rooms when any action appears
For now I've created a consumer that can handle one-to-one connections as a private chat. In my UI I display previous conversations and I'd love to somehow update their content if new message or conversation appears and then apply some actions, so for example slide the previous conversation to the top if it contains a new message. So it's like in any bigger application as instagram or facebook. When you're chatting with someone and if any new message appears from other sender, not the one that you're chatting with, the previous conversations are being updated, so in this case slide the previous or new conversation to the top of conversations. I'm not really familiar with websockets and I want to find the way how can I do that. As I understand if consumer let's two users connect to one room (layer?) how can other messages be updated? websocket does not know anything about it? I've tried brainstorming, but I still didn't get it right. This is my consumer as i've mentioned before, it only can only support two connections between two users. class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.user = self.scope["user"] self.private_chat_room_id = self.scope['url_route']['kwargs']['private_chat_room_id'] self.room_group_name = f'private_{self.private_chat_room_id}' if self.user.is_anonymous: await self.close() … -
'Client' object has no attribute 'text' Django
I have models in my project class Client(models.Model): """Аккаунт, с которого рассылаются сообщения""" name = models.CharField(max_length = 25) last_name = models.CharField(max_length = 25) description = models.TextField(max_length = 70) avatar = models.ImageField('Аватар', upload_to = 'sender/', blank = True) phoneNumberRegex = RegexValidator(regex = r"^\+?\d{8,15}$") phone_number = models.CharField(validators = [phoneNumberRegex], max_length = 16, unique = True) api_id = models.CharField(max_length=9) api_hash = models.CharField(max_length=33) proxy = models.ForeignKey( Proxy, blank=True, on_delete=models.CASCADE ) owner = models.ForeignKey( User, on_delete=models.CASCADE, related_name='owner', verbose_name='Владелец', ) class Meta: ordering = ('name',) verbose_name = 'Аккаунт' verbose_name_plural = 'Аккаунты' def __str__(self): return self.text class Sender(models.Model): """Рассылка""" NUMBER_PHONE = 'По номеру телефона' USER_NAME = 'По имени пользователя' SENDER_CHOICES = ( (NUMBER_PHONE, 'По номеру телефона'), (USER_NAME, 'По имени пользователя'), ) name = models.CharField( 'Название рассылки', max_length=10, ) text = models.TextField( 'Сообщение', max_length=4096, ) type = models.CharField( 'Тип рассылки', max_length=30, choices=SENDER_CHOICES, default=NUMBER_PHONE, db_index=True, ) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='Mailer', verbose_name='Автор', ) sender_man = models.ForeignKey( Client, on_delete=models.CASCADE, related_name='Sender_man', verbose_name='Отправитель', null=True, blank=True, ) def __str__(self): return self.name From these models I create forms class SenderForm(forms.ModelForm): class Meta: model = Sender fields = ('name', 'text', 'type', 'author', 'sender_man') class ClientForm(forms.ModelForm): class Meta: model = Client fields = ('name', 'last_name', 'description', 'avatar', 'phone_number', 'api_id', 'api_hash', 'proxy') When I create an … -
Django query stock price a year ago
I want to find the ticker prices which are greater than the price on the same day a year ago. How do I run the django query to get those prices? from django.db import models class Ticker(models.Model): symbol = models.CharField(max_length=50, unique=True) class TickerPrice(models.Model): ticker = models.ForeignKey( Ticker, on_delete=models.CASCADE, related_name="ticker_prices" ) price = models.DecimalField(max_digits=7, decimal_places=2) close_date = models.DateField() I'd like to run the query like below, but couldn't figure out how to get the ticker_price_a_year_ago. TickerPrice.objects.filter(price__gte=ticker_price_a_year_ago). -
Django TemplateDoesNotExist at /inicio/
A url do django está renderizando um caminho que não existe, mesmo estando indicado na view TemplateDoesNotExist at /inicio/ modelo.html Request Method: GET Request URL: http://127.0.0.1:8000/inicio/ Django Version: 4.1.7 Exception Type: TemplateDoesNotExist Exception Value: modelo.html Exception Location: C:\Users\vickc\OneDrive\Área de Trabalho\form_django\venv\Lib\site-packages\django\template\backends\django.py, line 84, in reraise Raised during: sgc.views.IndexView Python Executable: C:\Users\vickc\OneDrive\Área de Trabalho\form_django\venv\Scripts\python.exe Python Version: 3.11.1 Python Path: ['C:\\Users\\vickc\\OneDrive\\Área de Trabalho\\form_django\\form', 'C:\\Program Files\\Python311\\python311.zip', 'C:\\Program Files\\Python311\\DLLs', 'C:\\Program Files\\Python311\\Lib', 'C:\\Program Files\\Python311', 'C:\\Users\\vickc\\OneDrive\\Área de Trabalho\\form_django\\venv', 'C:\\Users\\vickc\\OneDrive\\Área de ' 'Trabalho\\form_django\\venv\\Lib\\site-packages'] Server time: Wed, 22 Feb 2023 21:02:11 -0300 View do app: from django.views.generic import TemplateView # Create your views here. # class ModeloView(TemplateView): template_name = "sgc/modelo.html" class IndexView(TemplateView): template_name = "sgc/index.html" Url do app: from django.urls import path from .views import ModeloView, IndexView urlpatterns = [ #path('endereco/', MinhaView.as_view(), name='nome-da-url') path('modelo/', ModeloView.as_view(), name='modelo'), path('inicio/', IndexView.as_view(), name='inicio'), ] caminho da template está em: templates L__ sgc L__index.html L__modelo.html Já tentei tirar os arquivos html da pasta sgc e deixar apenas na template mas a renderização de outras templates em outros apps dá erro -
How to write to_internal_value for Nested Serializer
I'm trying to build an app using a Django REST API connected to JQuery Datatables Editor. The problem I'm having is that I am unable to use a referenced serailizer due to a key error (I cannot enter data into the InstitutionSerializer due to the added to_internal_value function) The inserted function to_internal_value however is necessary for InvestigatorDatatableSerializer to reference and edit data. For now I am able to get it working by simply having two serializers (ex. InstitutionDatatableSerializer and InstitutionSerializer), but I was wondering if there is a way to add conditions the to_internal_value so I can have a single serializer where it can both make new instances and still check for existing ones. Error This is the error I get while trying to enter data KeyError at /dashboard/api/institution/editor/ 'id' serializers.py class InstitutionDatatableSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) class Meta: model = Institution fields = ('__all__') datatables_always_serialize = ('id',) class InstitutionSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) def to_internal_value(self, data): return get_object_or_404(Institution, pk=data['id']) class Meta: model = Institution fields = ('__all__') datatables_always_serialize = ('id',) class InvestigatorDatatableSerializer(serializers.ModelSerializer): institution_name = serializers.ReadOnlyField(source='institution.name') institution = InstitutionSerializer() class Meta: model = Investigator fields = ('id', 'last_name', 'first_name', 'email', 'institution_name', 'institution', ) datatables_always_serialize = ('id',) models.py class Institution(models.Model): id = models.AutoField(unique=True, … -
How to use static image as watermark for every page when printing pdf using django-wkhtmltopdf
I need to be able to use a static image as watermark when printing a pdf from a django template using django-wkhtmltopdf. How can I do it? Here is the watermark I want to use for every page -
Deploy Django Application on Windows IIS Server
I am deploying a Django web app to the windows IIS Server. I have installed python, set up the env, and configured the database; now I am trying to install mod_wsgi. I installed Microsoft Build Tools 2017, but I am getting a Microsoft Visual C++ error. Here is the error: error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ Please, any help on this would be great Second question, I wanted to use FastCGI by installing a. IIS b. Configure FastCGI in IIS c. and Configure FastCGI in IIS Is FastCGI free to use? -
How to update two objects on the page when submitting data from the form to the view?
I have an application in which on one web page is - a form with a choice of date interval - start and end. submit button a table displaying information from the model table. figure chart with display of information from the table of the model. I tried to set up so that after the successful completion of the form, changes occur on the page - table update chart update I was trying to make calculations in code when filling out a form. Which would issue updated information and export it to page refresh. I tried to connect HTMX in order to update the objects on the page. But I can't update objects. I would appreciate any information. How to update two objects on the page when submitting data from the form to the view? index.html <form action="" class="post-form" method="POST" autocomplete="off" hx-get="{% url 'index' %}" hx-target="#table_itogi_1, #figure_itogi"> {% csrf_token %} {{ form_calendar.as_p }} <input type="submit" name="submit" class="ui button" value="Выбрать период"> </form> <div id="table_itogi"> <table id="table_itogi_1" class="ui fixed table"> <thead> <tr> {% for item in headers_it %} <th>{{ item }}</th> {% endfor %} </tr> </thead> {% for row in rows_it %} <tr> {% for value in row.values %} <td> {{ value … -
Django TemporaryUploadedFile
I need to transcode video file from request to H264. Transcoding works, file creates, but I can't pass it to create the Model object. It is created with file size 0. What args shoud I pass to TemporaryUploadedFile? Model: `class Video(models.Model): id = HashidAutoField(primary_key=True, allow_int_lookup=True, prefix='video_') media = models.ForeignKey(Media, on_delete=CASCADE) uri = models.FileField(upload_to='media/video') thumbnail = models.FileField(upload_to='media/video/thumbnail', blank=True)` Transcoder: def transcoding(row_file): output = f"{row_file[:-3]}mp4" ffmpeg = ( FFmpeg() .option("y") .input(row_file) .output( output, {"codec:v": "libx264", "filter:v": "scale=1280:-1"}, # resolution preset="slow", crf=24, ) ) @ffmpeg.on("progress") def on_progress(progress: Progress): print(progress) ffmpeg.execute() file = TemporaryUploadedFile( output, content_type='video/H264', size=f'{os.stat(output).st_size}', charset= None, content_type_extra={'real_file': output}) return file View: def post(self, request, *args, **kwargs): self.parent = self.get_parent(self, request, *args, **kwargs) # Getting order number order_init = self.get_serial_number() # Creation import os order = order_init user = CustomUser.objects.get(pk=request.user.id) for key in request.data: media = self.create_media(user, order) try: input_file = request.data[key] except FileNotFoundError: return Response(status=status.HTTP_400_BAD_REQUEST) uri = transcoding(input_file.temporary_file_path()) video = Video.objects.create( media=media, uri=uri ) video.save() os.remove(uri.content_type_extra['real_file']) order += 1 return Response(f'{order - order_init} video files were uploaded successfully', status=status.HTTP_201_CREATED) File is converted fine, Model objecte is created and saved in db with file.size = 0 -
How to configure MariaDB in Django on Fedora 37
I am creating a new Django project and would like to use mariadb instead of sqlite. I have checked few guides (like this one: https://medium.com/code-zen/django-mariadb-85cc9daeeef8) as well as Django documentation. And from what I understand I need to have both mysql and mariadb installed to make it work. I have installed mysqlclient in my virtual environment using pip3. Then, I started my django project and edited and saved the DATABASES section of settings.py as advised in the above guide (I chose my own project name, username and password): # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databasesDATABASES = { ‘default’: { ‘ENGINE’: ‘django.db.backends.mysql’, ‘NAME’: ‘myproject’, ‘USER’:’yourusername’, ‘PASSWORD’:’yourpassword', ‘HOST’:’localhost’, ‘PORT’:’’, } } This is where the issue starts. I followed the guide and tried to install mariadb then: sudo dnf install mariadb But I got an error: Error: Problem: problem with installed package community-mysql-8.0.32-1.fc37.x86_64 - package community-mysql-8.0.32-1.fc37.x86_64 conflicts with mariadb provided by mariadb-3:10.5.16-3.fc37.x86_64 - package mariadb-3:10.5.16-3.fc37.x86_64 conflicts with community-mysql provided by community-mysql-8.0.32-1.fc37.x86_64 - package community-mysql-8.0.30-2.fc37.x86_64 conflicts with mariadb provided by mariadb-3:10.5.16-3.fc37.x86_64 - package mariadb-3:10.5.16-3.fc37.x86_64 conflicts with community-mysql provided by community-mysql-8.0.30-2.fc37.x86_64 - conflicting requests - package community-mysql-8.0.32-1.fc37.x86_64 conflicts with mariadb provided by mariadb-3:10.5.18-1.fc37.x86_64 - package mariadb-3:10.5.18-1.fc37.x86_64 conflicts with community-mysql provided by community-mysql-8.0.32-1.fc37.x86_64 - package community-mysql-8.0.30-2.fc37.x86_64 conflicts with … -
Javacsript: Displaying Typed in Info Instantaneously [closed]
What do I need to learn to be able to type in an input box and get it to display below on the same page instantaneously, like the app picture below does. Thank you -
Django Admin Two screen are overlapping
enter image description hereplease help me out with such a problem what to do so that I get my normal admin interface? I had upgrade my Django version from 2.2 to 4.1.7 and now I am facing such an annoying issue at admin. please help me out. -
'home' is not a registered namespace Django
I want to create an a way that you can get the product information by licking on a product and then loading that information into 1 html file, I looked up a couple of tutorials up and they al says this code works, but for me it gives me an error named "'home' is not a registered namespace Django" does anyone know how to fix this? views.py (home app directory from django.shortcuts import render from django.http import HttpResponse from .models import albums from django.views.generic import ListView, DetailView def album(request): return render(request, 'home/album.html') def artists(request): return render(request, 'home/artists.html') class homeview(ListView): model = albums template_name = "home/home.html" class albuminfo(DetailView): model = albums template_name = "home/AlbumInfo.html" models.py class albums(models.Model): title = models.CharField(max_length=100) description = models.TextField() release_date = models.CharField(max_length=10) artist = models.CharField(max_length=100) genre = models.CharField(choices=GENRE_CHOICES, max_length=20) image = models.ImageField(default='default2.jpg', upload_to='album_pics') slug = models.SlugField() def __str__(self): return self.title def get_absolute_url(self): return reverse("home:AlbumInfo", kwargs={ 'slug': self.slug }) urls.py from . import views urlpatterns = [ path('', views.homeview.as_view(), name='home'), path('albums/', views.album, name='Nartonmusic-album'), path('artists/', views.artists, name='Nartonmusic-artists'), path('albuminfo/<slug>/', views.albuminfo.as_view(), name='AlbumInfo') ] home.html {% extends 'home/base.html' %} {%block content%} {% for album in object_list %} <li><a href="{{album.get_absolute_url}}">{{ album.title}} </a></li> {% endfor %} {%endblock%} can somebody help my out?