Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Vscode extension suggestion not working on some folders
When I tried to create a HTML file inside my django project folder (appfolder/templat/test/page.html) it's not suggesting any tags when I type. But same time it's working on html files that are outside those folder it works perfectly Now I'm creating html file outside and paste it to that folder . How can I solve this ?? -
Firefox can’t establish a connection to the server in django channels echo server
I wrote an echo server with Django Channels, which I will give you the link channels_echo_server When I try to connect to Echo Server, I get this error in the console Firefox can’t establish a connection to the server at ws://127.0.0.1:8000/ws/ Socket closed unexpectedly I get the same error in the Chrome browser I uninstalled and reinstalled Channels and even the Django project several times But it didn't work where is the problem from? -
Django concurrent requests
I'm using Django as a framework, but I'm encountering an issue with concurrent requests. The application consistently responds to (n-1) requests and handles the last one, but it fails to send a response to the end user. I'm seeking assistance to resolve this problem. Can anyone help me with this? -
apache reverse proxy with django authentication and geoserver
i want to use django authentication before redirectiong to geoserver using apache reverse-proxy, i can Redirect to login page but after submitting the /login/?next=/geoserver return me to first page not to geoserver i tried a lot of configuratin but now success: <VirtualHost *:9443> ServerName localhost ProxyPreserveHost On # Proxy requests for GeoServer to Django ProxyPass /geoserver http://localhost:8080/geoserver ProxyPassReverse /geoserver http://localhost:8080/geoserver ProxyPassReverseCookiePath /geoserver / # Redirect /geoserver requests to Django authentication <Location /geoserver> Redirect /geoserver /login/?next=/geoserver </Location> # Proxy all other requests to Django ProxyPass / http://localhost:8000/ ProxyPassReverse / http://localhost:8000/ -
Django - Celery - How to handle complex tasks
Following problem needs to get solved: In my Django project I have to collect, manipulate and save specific data on regular basis. Example: Every minute I have to retrieve data from a heating-system via REST-API and process them Every minute I have to retieve data from a PV-inverter via REST-API and process them Every six hours I have to retrieve data from an external data provider and do some processing on it. After midnight I have to do some calculation on data from previous day ... and more to come in future From my perspective the Django/Celery/Beat approach would fit for above scenarios. I'm aware it's not a real message-based use case - more a batch processing use case to not setup cronjobs. In my Django project I have created apps (for the specific subsystems) and some general packages on project level. Described scenarios can be called (from Python shell and via Bash script outside development via cronjob. Now I tried to use Celery Beat to orchestrate above scenarios. But I'm not able to call the scripts from inside the celery tasks. Simply nothing happens - I guess importing all packages and scripts fail. I worked with several tutorials to … -
Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE
I'm trying to debug url.py in my project but i got this error all the time, I tried almost everything, any ideas? Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Agents of Faust streaming stop event consumption after some days
I have an application using faust-streaming. The application has around 20 agents each consuming events from different Kafka topics. The problem is, after several day, the agents stop consuming and I have to restart application container. Here is an example agent: @app.agent(event_sent_topic, concurrency=20) async def send_event_agent(stream): """""" task_name = asyncio.current_task().get_name() interface = Interface() async for records in stream.take(10, 1): for record in records: send_event_tasks_queue[record.user_id].append(task_name) await _wrap_send_event(record=record, interface=interface) await asyncio.sleep(0) # Skipping current event loop run for giving execution chance to other tasks. Container logs now only contains some warnings like below: * m_consumer.m_agent -----> ============================================================ ['Stack for <coroutine object movie_updated_agent at 0x7f303428bce0> (most recent call last):\n File "/project/m_consumer/movie_updated_consumer.py", line 22, in movie_updated_agent\n async for records in stream.take(faust_config.max_stream_take, 1):\n File "async_generator_asend", line -1, in [rest of traceback truncated]\n'] * z_consumer.retry_send_product_agent -----> ============================================================ ['Stack for <coroutine object retry_send_product_agent at 0x7f30341506b0> (most recent call last):\n File "/project/z_consumer/retry_consumer.py", line 29, in retry_send_product_agent\n async for records in stream.take(faust_config.max_stream_take, 1):\n File "async_generator_asend", line -1, in [rest of traceback truncated]\n', 'Stack for <coroutine object retry_send_product_agent at 0x7f303428bf00> (most recent call last):\n File "/project/z_consumer/retry_consumer.py", line 29, in retry_send_product_agent\n async for records in stream.take(faust_config.max_stream_take, 1):\n File "async_generator_asend", line -1, in [rest of traceback truncated]\n', 'Stack for <coroutine object retry_send_product_agent … -
How to pass a Django object from template to view by POST request?
I trying to pass the value of a checkbox to my views.py in the following way: my_template.html <input type="checkbox" name="playlist" value='{{ playlist }}'> views.py json_str_list = request.POST.getlist('playlist') The serialized JSON in json_str_list looks like this: '{\'id\': \'UUkfDws3roWo1GaA3pZUzfIQ\', \'title\': "Item 1", \'created_on\': datetime.datetime(2023, 6, 12, 20, 44, 41, 392273, tzinfo=datetime.timezone.utc)}' This seems not to be a valid JSON string. Can I adjust the way how Django serializes the object? I want to deserialize the JSON back to an object with json.loads() and get following error Expecting property name enclosed in double quotes -
Django signals post_save method
I am creating API for online-store with django-rest-framework and can't get my post_save signal working for some reason. The idea is: I have a model Product and Category. Product model has a field named in_stock, which is True by default. As for model Category, it also has field in_stock, but here it is False. When the product instance created, I want assign Category field in_stock to True value using singals. Here is the code of models: class Category(models.Model): category_name = models.CharField(max_length=255, verbose_name='Категория') description = models.TextField(verbose_name='Описание') in_stock = models.BooleanField(default=False, verbose_name='В наличии') slug = models.SlugField() image_url = models.ImageField(upload_to='categories/uploads/%Y/%m/%d/', null=True, blank=True, default='media/images.png', verbose_name='Изображение') parent = models.ForeignKey('self', on_delete=models.PROTECT, related_name='children', null=True, blank=True, verbose_name='Родительская категория') def __str__(self): return f'{self.parent}, {self.category_name}' class Product(models.Model): product_name = models.CharField(max_length=255, verbose_name='Товар') description = models.TextField(verbose_name='Описание') price = models.IntegerField(verbose_name='Цена') discount_percent = models.IntegerField(default=0, verbose_name='Процент скидки') in_stock = models.BooleanField(default=True, verbose_name='В наличии') amount = models.IntegerField(verbose_name='Количество') vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, verbose_name='Поставщик') category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория') brand = models.ForeignKey(Brand, on_delete=models.CASCADE, verbose_name='Бренд') image = models.ForeignKey(ProductImage, on_delete=models.SET_DEFAULT, default=1, verbose_name='Изображение') Here is signals: @receiver(post_save, sender=Product) def update_category_is_active(sender, instance, created, **kwargs): print(instance) if created and instance.in_stock: instance.category.in_stock = True instance.category.save() -
django annotate add key inside child object
I am fetching blogs with author as fetch_related, i want to add new key inside author but working but adding 'qq' in blog object is working but i want to add keys inside author like isAuthorFollowing, isAuthorBlocked, but i am not able to add any key inside author object this is the error i am getting Cannot resolve keyword 'new_key' into field. post_query = Blog.objects.select_related( 'author').annotate(qq=Value(1), author__new_field=Value(1)).get(filters) post_serializer = blogsSerializers.PostUserSerializer2( post_query, context={'request': request, 'user': user}) class PostUserSerializer2(serializers.ModelSerializer): author = usersSerializers.BlogPostAuthorDataSerializer2(read_only=True,) qq = serializers.IntegerField() class Meta: model = Blog fields = ('id', 'title', 'slug', 'created_at', 'updated_at' 'author', 'topic', 'poster_size', 'description', 'content_count', 'content','qq') class BlogPostAuthorDataSerializer2(serializers.ModelSerializer): new_field = serializers.IntegerField() class Meta: model = User fields = ['id', 'username', 'full_name', 'new_field'] -
How can i start a django project?
So in command prompt i did python -m django-admin startproject mysite And i got this error while trying with env: C:\Users\DR\Desktop\ChatMat\env\Scripts\python.exe: No module named django-admin First i tried without a env same error and when i tried with env still same error Here is the error without env: C:\Users\DR\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\python.exe: No module named django-admin Im trying to make a django project but the command prompt command is not working Anyone got a solution for this? -
TypeError: 'NoneType' object is not callable (DjangoAdmin)
I am trying to register one of my Models in the Django admin page (code below): class Collection(models.Model): title = models.CharField(max_length=255) featured_product = models.ForeignKey( 'Product', on_delete=models.SET_NULL, null=True, related_name='+') def __str__(self): return self.title class Meta: ordering = ['title'] code from admin.py: @admin.site.register(models.Collection) class CollectionAdmin(admin.ModelAdmin): list_display = ['title', 'products_count'] def products_count(self, collection): return collection.products_count def get_queryset(self, request): return super().get_queryset(request).annotate(products_count=Count) But I get this error for the collection Model for some reason and for no other model that i registered. Traceback: C:\Users\jonas_6xnnk8f\PycharmProjects\storefront\store\admin.py changed, reloading. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\threading.py", line 980, in _bootstrap_inner self.run() File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\threading.py", line 917, in run self._target(*self._args, **self._kwargs) File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\apps\registry.py", line 124, in populate app_config.ready() File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\contrib\admin\apps.py", line 27, in ready self.module.autodiscover() File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\contrib\admin\__init__.py", line 50, in autodiscover autodiscover_modules("admin", register_to=site) File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\utils\module_loading.py", line 58, in autodiscover_modules import_module("%s.%s" % (app_config.name, module_to_search)) File "C:\Program Files (x86)\Microsoft … -
filling in an html template from ModelForm
Hello Everyone. I need to fill out a template using ModelForm by fields with a drop-down list. I know that the form can be filled out as {{form.as_p}}. But is it possible to fill it out without using {{form.as_p }}? And how to do it? The way I'm trying to do it is highlighted in the template. I understand that there is a lot of text, but I really need your help, do not pass by :) model.py class Product(models.Model): name = models.CharField(max_length=40) def __str__(self): ` return self.name`` class Variety(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) name = models.CharField(max_length=40) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class Tender(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) variety = models.ForeignKey(Variety, on_delete=models.CASCADE) price = models.DecimalField(max_digits=4, decimal_places=2,) delivery_date = models.DateField(default=date.today) category = models.ForeignKey(Category, on_delete=models.CASCADE) delivery_basis = models.CharField(max_length=3, choices=[('CPT', 'CPT')]) payments = models.CharField(max_length=20, choices=[('Наличный расчет', 'Наличный расчет')]) comment = models.TextField(max_length=4000, blank=True, default='Комментарий отсутствует.') def __str__(self): return self.product forms.py class AddTenderForm(forms.ModelForm): class Meta: model = Tender fields = '__all__' views.py def index(request): form = AddTenderForm() if request.method == 'POST': form = AddTenderForm(request.POST) if form.is_valid(): form.save() return redirect('add') return render(request, 'fmtender/form_for_adding_a_tender.html', {'form': form}) part of the template (for convenience) <div class="col-12"> <label for="id_product" class="form-label">Продукт</label> <select class="form-select" … -
Issue creating relational tables for Django models with django-taggit and django-treebeard
I am trying to create hierarchical tags for my Django blog project using django-taggit and django-treebeard. However, I am encountering issues with the creation of the relational tables. Here is my models.py file: from django.db import models from django.contrib.auth.models import User from django.template.defaultfilters import slugify from taggit.models import TagBase, ItemBase from taggit.managers import TaggableManager from treebeard.mp_tree import MP_Node class Tag(TagBase, MP_Node): name = models.CharField(max_length=10, unique=True) parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) node_order_by = ['name'] class TaggedPost(ItemBase): post = models.ForeignKey('Post', on_delete=models.CASCADE) tag = models.ForeignKey('Tag', related_name="tagged_posts", on_delete=models.CASCADE) class Meta: unique_together = ('post', 'tag') def __str__(self): return self.tag.name class Post(ItemBase): title = models.CharField(max_length=125, unique=True) slug_title = models.SlugField(max_length=255, unique=True) summary = models.TextField(max_length=100) body = models.TextField() published_date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) status = models.BooleanField(default=True) tags = TaggableManager(through='TaggedPost') class Meta: ordering = ['-published_date'] def __str__(self): return self.title def save(self, *args, **kwargs): self.slug_title = slugify(self.title) super(Post, self).save(*args, **kwargs) I ran python manage.py makemigrations and python manage.py migrate successfully, but the relational tables (blog_tag and blog_taggedpost) are not being created. When I try to create a new tag using Tag.objects.create(name='Parent Tag'), I receive the following error: django.db.utils.ProgrammingError: relation "blog_tag" does not exist I am not sure why the tables are not being created and how to … -
Django form, dynamic number of fields based on another field
The following is my Django model for different type of questions: class Question(models.Model): QUESTION_TYPES = [ ('SBA', 'Single Best Answer (MCQ)'), ('EMQ', 'Extended Matching (Matching)'), ('SAQ', 'Short Answer Question'), ] question_type = models.CharField(max_length=3, choices=QUESTION_TYPES) class Option(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) option = models.TextField(default="Option") class Subquestion(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) subquestion = models.TextField(default="subquestion") I need a form to create new questions with all relevant fields. The fields needed on the form are dynamically decided based on a field in Question model. If question type if SBA is chosen, there should be 5 options fields (no subquestions) appearing and saving to the related models. If EMQ is chosen there should be 5 subquestions, and 7 options fields appearing. if SAQ is chosen no subquestions and options should appear. I tried using formsets but due to poorly written tutorials I could not understand. As the changes in question type should instantly change the remaining field, I am interesting in dynamic form fields. Any one can help? -
base.css does not apply in Django project
I have a following structure of my folders: And I try to import the base.css to base.html so that it applies everywhere: MY HTML: <!DOCTYPE html> {% load static %} <html> <head> <link rel="stylesheet" href="{% static 'base.css' %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> (...) </html> MY SETTINGS: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') Tried different combinations, but nothing seems to work. Please help :) -
How i can create query in django
I have the following model: class PointsforUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(null=True, default=0) slug = models.SlugField(max_length=255, blank=True, unique=True) class RunningTasks(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) fixed = models.BooleanField(default=False) slug = models.SlugField(verbose_name='URL', max_length=255, blank=True, unique=True) task = models.ForeignKey(Task, on_delete=models.CASCADE) points = models.IntegerField(null=True, default=0) class TaskCreateForm(forms.ModelForm): class Meta: model = RunningTasks fields = ('task',) class RunTaskCreateUserView(LoginRequiredMixin,CreateView): model = RunningTasks template_name = 'usersboard/tasks_create.html' form_class = TaskCreateForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context How can I create a task for a user where `pointsforuser.points = task.points? -
¿como puedo soluciona Error en el deploy de railway?
hola Estoy haciendo una api en django y trato de hacer el deploy en railway pero me sale un error enter image description here asi tengo el archivo requirements.txt contourpy==1.0.7 cycler==0.11.0 distlib==0.3.6 Django==4.2.2 djangorestframework==3.14.0 filelock==3.12.2 fonttools==4.39.4 kiwisolver==1.4.4 matplotlib==3.7.1 mpmath==1.3.0 mysqlclient==2.1.1 numpy==1.22.4 packaging==23.1 pandas==1.4.2 Pillow==9.5.0 platformdirs==3.5.3 PyMySQL==1.0.3 pyparsing==3.0.9 python-dateutil==2.8.2 pytz==2022.1 six==1.16.0 sqlparse==0.4.4 sympy==1.12 typing_extensions==4.6.3 tzdata==2023.3 virtualenv==20.23.0 ``` en procfile web: python manage.py migrate && gunicorn ap_Softseguros.wsgi -
How to let user pick date AND time in the form?
I am trying to create a sort of To Do List. Majority of it is done. I can get user to enter the task, along with its detail and pick the starting and ending date. However, since I am rendering the fields in a form, I want the user to easily and conveniently enter the date and time. For that I have added a datepicker type widget. The datetime stored in database is still in ISO format. Now, the issue is that user can pick or enter the date perfectly fine. But it does not allow the user to enter the time. Once the date has been picked, the user can't enter the time. The code goes as under: class TaskForm(ModelForm): class Meta: model = TaskModel exclude = ["completed"] widgets = { 'title': TextInput(attrs={"class": "form-control"} ), 'detail': Textarea(attrs={"class": "form-control"}), 'start_time': DateInput(format = ['%d/%m/%Y %H:%M'], attrs={"type":"date", 'class': 'form-control datetimepicker-input', 'data-target': '#datetimepicker1'}), 'end_time': DateInput(format = ['%d/%m/%Y %H:%M'], attrs={"type": "date", 'class': 'form-control datetimepicker-input'}) } And the Model.py file is: class TaskModel(models.Model): title = models.CharField(max_length=30) detail = models.TextField(blank=True) start_time = models.DateTimeField() end_time = models.DateTimeField() completed = models.BooleanField(blank = True, null=True) The rest of the code is just simple and conventional Django based views and … -
Changing localhost to a custom domain name in Django
I have modified my ALLOWED_HOSTS variable to include "localhost", "127.0.0.1", and "mysite.com". Additionally, I have created a hosts file in the same directory as my manage.py file which contains the following line: 127.0.0.1 mysite.com Despite these changes, the localhost name does not appear to be updating. -
How can I pass a big html code block to a with variable in Django template?
I'm looking to pass a big html code block value to a with variable. How can I achieve that elegantly? Example: {% include "includes/template.html" with info="big html code block" %} I'm wondering how I can accomplish this elegantly. One option would be to escape all quotes and new lines. Is there any other better way to do that? -
I was testing my API the"GET" Request went fine, but when i tried the "POST" request it showed:405 "Method POST is not allowed" Django REST framework
405 Method Not Allowed "detail": "Method "POST" not allowed." #views.py from django.shortcuts import render from rest_framework.decorators import api_view from rest_framework.response import Response from . models import Product from . serializers import ProductSerializer @api_view(['GET']) def product_list(request): if request.method == 'GET': products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) if request.method == 'POST': serializer = ProductSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) -
How to fix Typeerror : unsupported operand type(s) for +: 'DeferredAttribute' and 'int'
I'm trying to count the number of reviews I've got for a movie. Here I'm increasing number_rating by 1 value every time you add a new review by new user. here is my views.py code. class ReviewCreate(generics.CreateAPIView): serializer_class = ReviewSerializer def get_queryset(self): return Review.objects.all() # ************ def perform_create(self, serializer): # provides overring | Save and deletion hooks | concrete class views pk = self.kwargs.get('pk') # also have perform_update perform_destroy watchlist_movie = watchlist.objects.get(pk=pk) review_user = self.request.user # we are getting current user / ERROR review_queryset = Review.objects.filter(watchlist=watchlist_movie, review_user=review_user) if review_queryset.exists(): # ERROR raise ValidationError('You have already reviewed this movie.') if watchlist.number_ratings == 0: # here providing validated data from serializers watchlist.avg_rating = serializer.validated_data['rating'] else: # (old rating + new rating) / 2 watchlist.avg_rating = (watchlist.avg_rating + serializer.validated_data['rating']) / 2 # for number of ratings == current ratings + one. watchlist.number_ratings = watchlist.number_ratings + 1 watchlist.save() serializer.save(watchlist = watchlist_movie, review_user = review_user) error is coming to the else part, adding + 1 to existing count to show the actual number count. What's this error about, How to solve this kind-of errors in future? -
I tried to run my django project and it shows the following error
(venv) PS C:\Users\User\OneDrive\Desktop\student-management-using-django-main> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 1348, in do_open h.request(req.get_method(), req.selector, req.data, headers, File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1282, in request self._send_request(method, url, body, headers, encode_chunked) File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1328, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1277, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1037, in _send_output self.send(msg) File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 975, in send self.connect() File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 941, in connect self.sock = self._create_connection( File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\socket.py", line 845, in create_connection raise err File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\socket.py", line 833, in create_connection sock.connect(sa) TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection f ailed because connected host has failed to respond During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "D:\student-management-using-django-main\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "D:\student-management-using-django-main\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "D:\student-management-using-django-main\venv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "D:\student-management-using-django-main\venv\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "D:\student-management-using-django-main\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config … -
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'accounts.User'
Im getting the following error AttributeError: Manager isn't available; 'auth.User' has been swapped for 'accounts.User' in my django project when I try to click on register button i have made where the email and password is sent to the backend. I have acoounts app where I have the following code in the files: backend.py: from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model class EmailBackend(ModelBackend): def authenticate(self, request, email=None, password=None, **kwargs): User = get_user_model() try: user = User.objects.get(email=email) except User.DoesNotExist: return None else: if user.check_password(password): return user return None models.py: from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.contrib.auth import get_user_model from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' objects = CustomUserManager() def __str__(self): return self.email views.py: from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login as auth_login from django.contrib.auth import authenticate from .models import User from django.contrib import messages def register(request): if request.method == 'POST': …