Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ModuleNotFoundError: No module named 'model_db' using django.setup() outside django project
Im trying to use django ORM on a project, im using django 5.0.1, i read to acomplish i need this configuration, this would be on main.py: the link import django from django.conf import settings from DATABASE.Django_ORM.Django_ORM import settings as st settings.configure(default_settings=st, DEBUG=True) django.setup() #Importing Models from DATABASE.Django_ORM.model_db import models However it returns a Error: ModuleNotFoundError: No module named 'model_db' model_db is the app i create on django here is the settings.py: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'model_db', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Django_ORM.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Django_ORM.wsgi.application' # Database # https://docs.djangoproject.com/en/5.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / … -
Installing Django-tailwindCSSS fails on tailwind strart
I'm installing Django-Tailwind following the instructions: https://django-tailwind.readthedocs.io/en/latest/installation.html The Django part works but the part that updates the CSS by runniong the command" "python manage.py tailwind start" fails. the node that executed the command in, package.json, "dev": "tailwindcss -i ./src/styles.css -o ../static/css/dist/styles.css -w", fails with a message that ends with: "Object.loadConfig (D:\DjangoTailwind__Starter\node_modules\tailwindcss\lib\cli\bu il\plugin.js:135:49) {'code: 'MODULE_NOT_FOUND', requireStack: [ 'D:\DjangoTailwind__Starter\src\djtailwind\theme\static_src\tailwind.config.js ']} I tried running: "npm install -D tailwindcss" but without success I' using Windowes 11 Node version 21.5.0 -
Installing mysqlclient python package
I want using mysql in django and I should install mysqlclient package in virtual env . My OS is ubuntu 20 . I run : pip install mysqlclient but I get this error : Collecting mysqlclient Using cached mysqlclient-2.2.1.tar.gz (89 kB) Installing build dependencies ... done Getting requirements to build wheel ... error error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [24 lines of output] Trying pkg-config --exists mysqlclient Command 'pkg-config --exists mysqlclient' returned non-zero exit status 1. Trying pkg-config --exists mariadb Command 'pkg-config --exists mariadb' returned non-zero exit status 1. Trying pkg-config --exists libmariadb Command 'pkg-config --exists libmariadb' returned non-zero exit status 1. Traceback (most recent call last): File "/home/caspian/Desktop/projects/django_project4/django-react1/React-Django-To-Do-App/lib/python3.8/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in main() File "/home/caspian/Desktop/projects/django_project4/django-react1/React-Django-To-Do-App/lib/python3.8/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/home/caspian/Desktop/projects/django_project4/django-react1/React-Django-To-Do-App/lib/python3.8/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel return hook(config_settings) File "/tmp/pip-build-env-l_o48981/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 325, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) File "/tmp/pip-build-env-l_o48981/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 295, in _get_build_requires self.run_setup() File "/tmp/pip-build-env-l_o48981/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 311, in run_setup exec(code, locals()) File "", line 155, in File "", line 49, in get_config_posix File "", line 28, in find_package_name Exception: Can not find valid pkg-config name. Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually [end of output] note: … -
How Debug This error? "Method Not Allowed (POST)"
Hello. My friends, when I complete the form on the HTML side and send it to the Django side for validation. I get "Django Method Not Allowed (POST)" error. this is my model class ContactUs(models.Model): name = models.CharField(max_length=20, null=True, ) surname = models.CharField(max_length=20, null=True, ) email = models.EmailField(max_length=30, null=True, ) subject = models.CharField(max_length=20, null=True, ) text = models.TextField(null=True, ) this is my form class ContactModelForm(forms.ModelForm): class Meta: model = ContactUs fields = \['name', 'email', 'surname', 'subject', 'text'\] widgets = { 'name': forms.TextInput(), 'surname': forms.TextInput(), 'email': forms.EmailInput(), 'subject': forms.TextInput(), 'text': forms.Textarea(),} This my view,this is not a complete view, it is just for testing class ContactView(View): def get(self, request): form = ContactModelForm() return render(request, 'contact/contact_us.html', {'forms': form}) def post(self, request): form = ContactModelForm(request.POST)`` if form.is_valid(): form.save() return redirect('home') return render(request, 'contact/contact_us.html', {'forms': form}) -
Is it wise to construct a custom string (combination of entity, year and alphanumeric) to have as a primary key for a postgres database in Django?
I'm working on creating a Django backend for an application and I want the primary key of our entities to fulfil certain criteria. First criteria is that it is always 10 characters long so that it is easy to read and share verbally if needed. Second criteria is that it always follows the same format:- First 2 characters => Code for the entity (for example "US" is for User records, "TO" is for topics, "BO" for books etc.) so that anyone can easily say what a certain ID is for Second 2 characters => Year of the date of creation ('24', '23 etc.) Remaining 6 characters are randomly generated alphanumeric characters I've written the following code to generate the id:- def auto_increment_id(): alphanumeric_chars = string.ascii_letters + string.digits last_chars = ''.join(random.choice(alphanumeric_chars) for _ in range(6)) user_id = 'US' + str(datetime.date.today().year)[2:] + str(last_chars) return user_id And I have it setup in the user model like this class User(models.Model): id = models.CharField(max_length=10, primary_key=True, default=auto_increment_id, editable=False) My question is, will this lead to performance issues or other issues as we scale up? Is this a wise setup? -
Which database is more reliable Postgres or MySQL? [closed]
I am currently using a Postgres database, but I am encountering issues such as tables getting dropped automatically. As a result, I have concerns about the reliability of Postgres. What is you opinion ? Here is the link to the issue of table getting dropped. link I would like know which database should I choose ? -
Connecting an old MySQL server to the latest Django installation
I'm making a Django project that connects to an external MySQL database for a college project. The problem is that the database is outdated, and I keep getting the error message, "MySQL 8.0.11 or later is required (found 5.6.40)." I cannot update the database server and I would like to keep using the latest version of Django. If I were to create a middleware to convert the response from the database to a format readable to the Django 5.0.1, what would be the topics I would need to learn? I added the external database to the settings.py along with the main database. I also used connections from django.db to make queries so I would not have to add the entire database to models.py. -
Cannot generate instances of abstract factory (Django factory_boy)
this factories: `import factory from .models import * from factory.faker import * FAKE = faker.Faker(locale = 'ru_RU') class RoleFactoryManager(factory.django.DjangoModelFactory): class Meta: model = Role abstract = False role_name = 'manager' class RoleFactoryAdmin(factory.django.DjangoModelFactory): class Meta: model = Role abstract = False role_name = 'admin' class RoleFactoryUser(factory.django.DjangoModelFactory): class Meta: model = Role abstract = False role_name = 'user' class ClientFactory(factory.django.DjangoModelFactory): class Meta: model = Client abstract = False client_surname = factory.Faker('second_name') client_name = factory.Faker('first_name') client_date_of_registration = factory.Faker('date') client_email = factory.LazyAttribute(lambda a: '{}.{}{}@gmail.com'.format(a.client_surname, a.client_name, a.client_id).lower()) client_phone = factory.Faker('phone_number') client_photo = ('/images/profile_photo.png') ` this models: `from django.db import models class Role(models.Model): role_id = models.AutoField(primary_key=True) role_name = models.CharField(max_length=30, null=False) class Client(models.Model): client_id = models.AutoField(primary_key=True) client_surname = models.CharField(max_length=30, null=False) client_name = models.CharField(max_length=30, null=False) client_date_of_registration = models.DateField(null=False) client_email = models.CharField(max_length=99, null=False) client_password = models.CharField(max_length=99, null=False) client_phone = models.CharField(max_length=11, null=False) client_photo = models.CharField(max_length=500, null=False) def __str__(self): return f'{self.client_surname} {self.client_name}'` and i get this for all of this factories: error is factory.errors.FactoryError: Cannot generate instances of abstract factory RoleFactoryManager; Ensure RoleFactoryManager.Meta.model is set and RoleFactoryManager.Meta.abstract is either not set or False. how to fix it i tried to indicate the model specifically, change imports and etc -
django form resubmitted upon refresh pag
After I submit the form for the first time and then refresh the form it gets resubmitted and and I don't want that. How can I fix this ? Here's my views: from django.shortcuts import render from django.http import HttpResponse from free.models import contact `def index(request):` `if request.method == 'POST':` `fullname = request.POST.get('fullname')` `email = request.POST.get('email')` `message = request.POST.get('message')` `en = contact(fullname=fullname, email=email, message=message)` `en.save()` `return render(request, 'index.html')` -
Why paginating a ListView in django does not work?
I am doing the CS50W, the Network project, when I want to move to next / go back to the pagination of my web. Nothing happened. I tried to debug the view.py file, anytime I click the next or previous button in script.js , it all returned page_number as none in views.py . I have no idea why this happened. Can you guys help me? Here are the code in my views.py : def index(request): return render(request, "network/index.html") def allPosts(request): # Get all posts data - json allPosts = Post.objects.all() # Return emails in reverse chronologial order allPosts = allPosts.order_by("-timestamp").all() # Show 2 contacts per page. paginator = Paginator(allPosts, 2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) # return json all posts data = { 'posts': [post.serialize() for post in page_obj], 'page': { 'has_previous': page_obj.has_previous(), 'previous_page': page_obj.has_previous() and page_obj.previous_page_number() or None, 'has_next': page_obj.has_next(), 'next_page': page_obj.has_next() and page_obj.next_page_number() or None, 'num_pages' : page_obj.paginator.num_pages, 'current_page' : page_number } } return JsonResponse(data, safe=False) Code in my script.js file: document.addEventListener('DOMContentLoaded', function() { // Use buttons to toggle between views document.querySelector('.showallPosts').addEventListener('click',showallPosts); showallPosts(); }); function showallPosts(){ // Clear out composition field document.querySelector('#allPosts-view').value = ''; // Show the mailbox name document.querySelector('#allPosts-view').innerHTML = ` <h3>All Posts</h3> `; // Get … -
KeyError: 'fields', but key 'fields' is works at the same time
This is kind of weird: The print wint ex_pur['fields'] is working, and at the same time I have a KeyError: 'fields' abote this print(). Halp me please to understand what I'm doing wrong. Thank you! ... try: existed_purchases_queryset = Purchases.objects.filter(name__in=purchases_names, list_id=list_id) existed_purchases = serializers.serialize('python', existed_purchases_queryset) response["existed"] = existed_purchases print(f"----------------\n{existed_purchases = }\n----------------") existed_purchases_names = [pur['fields']['name'] for pur in existed_purchases] except Purchases.DoesNotExist: print("Все позиции новые.") for purchase in purchases: print(f"{type(existed_purchases[0]) = }") purchases_serializer = PurchaseAddSerializer(data=purchase) do = False if purchase['name'] in existed_purchases_names: for ex_pur in existed_purchases: print(f"----------------\n{('description' in **ex_pur['fields']**.keys()) = }\n----------------") if ex_pur['fields']['name'] == purchase['name']: ... ---------------- ('description' in ex_pur['fields'].keys()) = True ---------------- ---------------- ('description' in ex_pur['fields'].keys()) = True ---------------- ---------------- ('description' in ex_pur['fields'].keys()) = True ---------------- Internal Server Error: /purchases/add/ Traceback (most recent call last): File "C:\Users\lars5\OneDrive\Programming\Python\shopping_list_telegram_bo t_02_django\.venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lars5\OneDrive\Programming\Python\shopping_list_telegram_bo t_02_django\.venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lars5\OneDrive\Programming\Python\shopping_list_telegram_bo t_02_django\.venv\Lib\site-packages\django\views\decorators\csrf.py", line 6 5, in _view_wrapper return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lars5\OneDrive\Programming\Python\shopping_list_telegram_bo t_02_django\.venv\Lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lars5\OneDrive\Programming\Python\shopping_list_telegram_bo t_02_django\.venv\Lib\site-packages\rest_framework\views.py", line 509, in d ispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lars5\OneDrive\Programming\Python\shopping_list_telegram_bo t_02_django\.venv\Lib\site-packages\rest_framework\views.py", line 469, in h andle_exception self.raise_uncaught_exception(exc) File "C:\Users\lars5\OneDrive\Programming\Python\shopping_list_telegram_bo t_02_django\.venv\Lib\site-packages\rest_framework\views.py", line 480, in … -
Internal server error on cmd,TemplateDoesNotExist at / index.html
I'm working on building a web app using Django and encountering the following error: Internal Server Error: / Traceback (most recent call last): File "D:\New folder\env\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "D:\New folder\env\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\New folder\core\home\views.py", line 10, in home return HttpResponse(render(request, 'index.html')) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\New folder\env\Lib\site-packages\django\shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\New folder\env\Lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\New folder\env\Lib\site-packages\django\template\loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: index.html' path: D:\New folder\core\home\template file name:index.html basic html code D:\New folder\core file name = setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] EXTERNAL_APPS = [ 'home', ] INSTALLED_APPS += EXTERNAL_APPS file name:views.py code: from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'index.html')) def success_page(request): print("* "*10) return HttpResponse("""<h1>Page has Been created successfully</h1> </br> <hr> <p1> Hello world</p1>""") D:\New folder\core file name:urls.py code: from django.contrib import admin from django.urls import path from home.views impor urlpatterns = [ path('admin/', admin.site.urls), path('', home, name="home"), path('Success-page',success_page,name ="success_page") ] 'tried many approaches from stack over flow still same error. help me fixing this … -
Django model structure for question with type and subtype
is this type of model schema okay i have a question which will for sure have a type but the subtype is optional class QuestionType(models.Model): question_type = models.CharField(max_length=255) def __str__(self): return self.question_type class QuestionSubType(models.Model): question_type = models.ForeignKey(QuestionType, on_delete=models.CASCADE) question_sub_type = models.CharField(max_length=255) class Question(QuestionAbstractModel): chapter = models.ForeignKey(Chapter, blank=True, null=True, on_delete=models.CASCADE) type = models.ForeignKey(QuestionType, on_delete=models.CASCADE, blank=False) type_subtype = models.ForeignKey(QuestionSubType, on_delete=models.CASCADE, blank=True, null=True) solution_url = models.URLField(max_length=555, blank=True) def __str__(self): return f" {self.chapter.subject.grade} {self.chapter.subject.name} {self.chapter.name} {self.type}" is this model schema okay or can i improve it in any way -
Large number of rejected connections in memcached using django
I'm using Django-4.6.2 with memcached-1.5.22. The Django Cache settings (django.conf.settings.CACHES) are as follows: { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211' } } memcached is configured to use 1GB of memory (-m 1024), uses port 12111 (-p 11211), listens to localhost (-l 127.0.0.1) and has a maximum object size of 32MB (-I 32M). Despite this, there seem to be a large number of rejected connections in memcached stats (obtained via telnet): STAT max_connections 1024 STAT curr_connections 1 STAT total_connections 2462353 STAT rejected_connections 2462352 STAT connection_structures 11 Django is configured with wsgi, with processes=12, threads=12. Is this large number of rejected connections normal? What is the likely cause? -
'str' object has no attribute 'name' Django rest api video post error
Here is my django rest api app for uploading videos,my models.py file is below, from django.db import models from django.contrib.auth.models import User from likevideos.models import Likevideo class Video(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255,blank=True) video_file = models.FileField(upload_to='videos/') description = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_at'] def __str__(self): return f"Video by {self.id}: {self.title}" @property def like_count(self): return self.likevideos.count() @property def comment_count(self): return self.videocomments.count() Here is my views.py file, from rest_framework import generics, permissions, filters from friends_chats.permissions import IsOwnerOrReadOnly from rest_framework.response import Response from .models import Video from .serializers import VideoSerializer class VideoListCreateView(generics.ListCreateAPIView): permission_classes = [permissions.IsAuthenticated, IsOwnerOrReadOnly] queryset = Video.objects.all() serializer_class = VideoSerializer filter_backends = [ filters.OrderingFilter, filters.SearchFilter, ] search_fields = [ 'owner__username', 'title', ] ordering_fields = [ 'like_count', 'comment_count', 'likevideos__created_at', ] def perform_create(self, serializer): serializer.save(owner=self.request.user) class VideoDetailView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsOwnerOrReadOnly] queryset = Video.objects.all() serializer_class = VideoSerializer Here is my serializer, from rest_framework import serializers from django.core.validators import FileExtensionValidator from django.core.exceptions import ValidationError as DjangoValidationError from .models import Video from .models import Likevideo class VideoSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') is_owner = serializers.SerializerMethodField() likevideo_id = serializers.SerializerMethodField() like_count = serializers.ReadOnlyField() comment_count = serializers.ReadOnlyField() class Meta: model = Video fields = ['id', 'owner', 'title', 'video_file', 'description', 'created_at', 'updated_at', 'is_owner','likevideo_id','like_count','comment_count'] … -
How to override form field in Django function based view?
I like to use a form in a function based view but I like to override the kategoria select field to show only the objects that related to the user. models.py class Blog_poszt(models.Model): def __str__(self): return str(self.user) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_szerzo") datetime = models.DateTimeField(auto_now_add=True, auto_now=False) cim = models.CharField(max_length=300) cim_slug = models.CharField(max_length=300, null=True, blank=True) szoveg = models.CharField(max_length=10000, null=True, blank=True) kategoria = models.ForeignKey('Blog_kategoriak', on_delete=models.CASCADE, null=True, blank=True) kep = models.FileField(upload_to="blog/", null=True, blank=True) class Blog_kategoriak(models.Model): def __str__(self): return str(self.user) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="kategoria_szerzo") datetime = models.DateTimeField(auto_now_add=True, auto_now=False) kategoria = models.CharField(max_length=200) forms.py class UjBlogposztForm(forms.ModelForm): class Meta: model = Blog_poszt fields = '__all__' exclude = ('user',) views.py def blog_poszt(request): form = UjBlogposztForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid: form.instance.user = request.user form.save() context = { 'form': form, } html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-dark">Mentés</button> </form> -
I'm creating a website with the Django framework and I have a problem
path('accounts/login/', auth_view.LoginView.as_view(template_name='app/login.html', authentication_form=LoginForm), name='login'), path('logout/', auth_view.LogoutView.as_view(next_page='login'), name='logout'), when i want to use logout function i have set in my urls.py as above and also i have linked it well in my base.html like this href="{% 'logout' url %}" but after I tried the logout page it didn't work please help me please -
Django authenticate() always returns None
I am building a web project with Django to facilitate distribution in case of an earthquake. The user needs to be a member as a Mukhtar or a Helper. The registration system works successfully. But the login part is constantly returning None value even though my login information is absolutely correct. models.py: from django.db import models from django.contrib.auth.models import AbstractUser from base64 import b32encode from hashlib import sha1 from random import random # Create random id def pkgen(): rude = ('lol',) bad_pk = True while bad_pk: pk = b32encode(sha1(str(random())).digest()).lower()[:24] bad_pk = False for rw in rude: if pk.find(rw) >= 0: bad_pk = True return pk # Create your models here. class User(AbstractUser): muhtar = models.BooleanField(null=False,default=False) username = models.CharField(max_length=28, null=False, unique=False) email = models.EmailField(null=False, unique=True) tc = models.CharField(max_length=11, null=False, unique=True) address = models.TextField(null=False) need_help = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'tc' #Uyarı! Bu benzersiz olmasını ister REQUIRED_FIELDS = ['username'] def __str__(self): return f"{self.username}" class sos(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) sos_key = models.CharField(max_length=24, primary_key=True, default=pkgen, unique=True) address = models.TextField(null=False, unique=False) def __str__(self): return f"{self.user}" views.py: from django.shortcuts import render, redirect from .models import User from django.contrib.auth import authenticate, login, logout # Create your views here. def index(request): return render(request, "harita.html") def … -
UnboundLocalError: local variable 'client' referenced before assignment in Celery task
I am working on a Django project with Celery and Channels for handling MQTT connections. I have a Celery task (mqtt_client_task) that connects to an MQTT broker, and I am encountering the following error: File "/home/<user>/../../iot/tasks.py", line 30, in mqtt_client_task logger.error("Failed to connect, return code %d", rc) UnboundLocalError: local variable 'client' referenced before assignment Here's a simplified version of the relevant code: tasks.py: # iot/task.py from celery import shared_task from paho.mqtt import client as mqtt_client_module from asgiref import sync from channels.layers import get_channel_layer from django.conf import settings import logging from django.core.exceptions import ObjectDoesNotExist from django.db import close_old_connections logger = logging.getLogger(__name__) @shared_task(bind=True) def mqtt_client_task(self, device_client_id): from iot.models import Device try: device = Device.objects.get(client_id=device_client_id) topic = device.topic except ObjectDoesNotExist as e: logger.error(f"Device not found: {device_client_id}") return def on_connect(client, userdata, flags, rc): nonlocal mqtt_client_instance if rc == 0: logger.info("Connected to MQTT Broker!") else: logger.error("Failed to connect, return code %d", rc) client.subscribe(topic) def on_message(client, userdata, msg): logger.info(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic") channel_layer = get_channel_layer() sync.async_to_sync(channel_layer.group_send)( f"{device.id}", {"type": "device.message", "message": msg.payload.decode()} ) mqtt_client_instance = mqtt_client_module.Client(device_client_id) mqtt_client_instance.on_connect = on_connect mqtt_client_instance.on_message = on_message try: mqtt_client_instance.connect( settings.MQTT_HOST, settings.MQTT_PORT, settings.MQTT_KEEPALIVE ) mqtt_client_instance.loop_start() except Exception as e: logger.error(f"Failed to connect to MQTT Broker: {e}") return finally: close_old_connections() Consumer.py # iot/channels/consumers.py … -
Do I need to always have a server running to make every command after starting an app?
I'am reading a book Python Crash Course 2nd Edition 3rd project, creating a django web app. It's said that to start an app I need to have the server running in other terminal tab. In the first tab: python manage.py runserver And in the second tab: python manage.py startapp learning_logs And after these manipulations I need to further do those: defining a model, activating a model, and making migration, etc. Do I need to have a server running to make other commands after starting an app? Or do I only need it running to start an app? So for example, do I need to have server running when further making a migration? python manage.py makemigrations learning_logs -
Django Rest Framework Async Error: "'async_generator' object is not iterable"
I am working on a Django Rest Framework project with asynchronous views. I have an endpoint for streaming responses, here's my code: from adrf.views import APIView as View class ChatAPI(View): permission_classes = [IsAuthenticated] async def process_dataframe(self, file_urls): data_frames = [] for file_url in file_urls: if file_url.endswith('.csv'): df = pd.read_csv(file_url) data_frames.append(df) elif file_url.endswith(('.xls', '.xlsx')): xls = pd.ExcelFile(file_url) sheet_names = xls.sheet_names for sheet_name in sheet_names: df = pd.read_excel(file_url, sheet_name=sheet_name) data_frames.append(df) return data_frames async def get_cached_data(self, cache_key): return cache.get(cache_key) async def check_file_extension(self, file_ext, csv_agent_type): print(f"Checking file extension: {file_ext}") return file_ext in csv_agent_type async def check_all_file_extensions(self, file_extensions, csv_agent_type): tasks = [self.check_file_extension( file_ext, csv_agent_type) for file_ext in file_extensions] print(tasks, "tasks") results = await asyncio.gather(*tasks) print(f"Results: {results}") return all(results) async def post(self, request, thread_id, user_id): try: a = time.time() print("Start===========") csv_agent_type = ['csv', 'xls', 'xlsx'] file_ids = request.GET.get('file_ids', []) message = request.data.get('message') chat_history = "" streamed_text = "" image_url = None # Use sync_to_async here generate_graph = await ais_graph_required(message) print(generate_graph, "....") print(thread_id, '==========thread_id') # Use sync_to_async here thread = await sync_to_async(Thread.objects.get)(id=thread_id) file_ids = await sync_to_async(lambda: list( thread.files.all().values_list('id', flat=True)))() file_types = await sync_to_async(lambda: list( User_Files_New.objects.filter(id__in=file_ids).values_list('file_name', flat=True)))() # Use sync_to_async here file_extensions = [file_name.split( ".")[-1] for file_name in file_types] cache_key = f"kibee_agent_cache_{user_id}_{thread_id}" print(cache_key) cached_data = await self.get_cached_data(cache_key) print("got … -
Module not found error with Django Channels
I'm completely new to using channels, but have tried two separate installations, and setups to just get a basic version of channels running and am encountering a small issue. I'm assuming I'm probably just missing a small thing, but I cannot figure it out. The error is at handshake error I'll also show the current file structure, as well as the files that I've actually made modifications to. asgi.py settings.py settings.py consumers.py consumers.py routing.py Originally, in settings.py having ASGI_APPLICATION set as mysite.asgi.application was resulting in an error so I changed that to mysite.settings and it seemed to work correctly when starting. However, on handshake now this issue occurs, so I feel like that could potentially contribute to it. I've tried on different projects and both encounter this issue. -
"Why is the table in my PostgreSQL database hosted in Azure being dropped automatically?"
I have backend in Django and my postgresql database hosted in azure. There is one table named "devicedata" got dropped from database automatically two times yesterday. All the other tables are working fine. What might be the reason ?. Is it postgres related or azure ? I have no idea. Please help me out. I had to delete all the tables and migrate to create all the table in Postgres including devicedata table. -
django-how to upload image using ImageField in a model form?
My form doesn't save the uploaded image in the path given, my code: models.py: class MyClass(models.Model): user = models.OneToOneField(SomeClass, on_delete=models.CASCADE) address_line_1 = models.CharField(blank=True, max_length=100) address_line_2 = models.CharField(blank=True, max_length=100) profile_picture = models.ImageField(blank=True, upload_to='static/zzz/xxx/') forms.py class edit_profile_form(forms.Form): profile_picture = forms.ImageField(label='Avatar',widget=forms.FileInput( attrs={ 'class': 'form-control input_data', 'placeholder': 'Upload',})) views.py def validate_edit_profile(request): template = loader.get_template('account/edit_.html') user_form = edit_profile_form(request.POST,request.FILES) userprofile = EcomCustomerProfile.objects.get(user_id=request.user.id) #if user submit if request.POST: if user_form.is_valid(): # get the data first_name = user_form.cleaned_data['first_name'] last_name = user_form.cleaned_data['last_name'] phone = user_form.cleaned_data['phone'] profile_picture = user_form.cleaned_data['profile_picture'] #change db get_user = EcomCustomer.objects.get(id = request.user.id) get_user.first_name = first_name get_user.last_name = last_name get_user.phone = phone get_user.profile_picture = profile_picture user_form.save() get_user.save() return HttpResponse(template.render({'userprofile':userprofile}, request)) I'm using two forms: one for text, the other for uploading the image. But it doesn't upload anything. What's the problem ? -
Can you explain me how to deploy a django website
I need a good explanation in step by step in how to deploy my django website online. I tried github at first but thn i understood that github doesn't work that way and then I tried PythonAnywhere but I don't know the proper way to make a deployment so I need a help in that.