Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
App TemplateDoesNotExist in Django Project
I am struggling to figure out why I am receiving the TemplateDoesNotExist error in my project. This is my initial project layout. The project name is localassets, the initial app name is assetlist. I have registered the app in my settings.py file. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'assetlist.apps.AssetlistConfig', 'django_tables2', 'django_filters', 'widget_tweaks', 'django_bootstrap_icons', 'django_extensions', 'crispy_forms', 'crispy_bootstrap4', ] 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 = 'localassets.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', ], }, }, ] I have successfully created views and templates within this app and it displays all templates without issues. I now want to add another app to this project. This app is named workorders. I created the app the folder structure is shown below: I have also registered this app in the project settings.py file. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'assetlist.apps.AssetlistConfig', 'django_tables2', 'django_filters', 'widget_tweaks', 'django_bootstrap_icons', 'django_extensions', 'crispy_forms', 'crispy_bootstrap4', 'workorders.apps.WorkordersConfig', ] 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 = 'localassets.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', … -
Django: How to autocomplete user-creator field of a model in admin-panel
class Post(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) text = models.TextField() approved = models.BooleanField(default=False) total_media_count = models.PositiveIntegerField(default=0) group = models.ForeignKey('bot_users.BotUserGroup', on_delete=models.SET_NULL, null=True, blank=True) I log in in admin-panel (as a superuser, as a staff. Doesn't matter) and I want user field to be autocompleted with user who made this POST model instance in admin-panel. How can I do that? I've tried save() method, but it doesn't work for me. Also save_model method in admin.py P.S. Function of making posts in the project can only be made from admin-panel -
Celery: No result backend is configured
I am trying to use Celery to asynchronously webscrape course registration info from a school university website. Ultimately, I want to build something where users are notified if a seat opens up in a specific course. RabbitMQ is my message broker. I am using Django, when running my server I am met with an error. I don't know what I am missing but this is my first project using something like celery to query data asynchronously. If someone could be show me what i'm missing that would be greatly appreciated. Below is a screenshot of my RabbitMQ dashboard which I believe is running and configured with my project. Below is my code settings CELERY_BROKER_URL = 'amqp://localhost:5672' # RabbitMQ broker URL CELERY_RESULT_BACKEND = 'amqp://localhost:5672' views.py from django.shortcuts import render from bs4 import BeautifulSoup import requests from .forms import CourseRegistrationForm from .tasks import scrape_course_data def main(request): form = CourseRegistrationForm() if request.method == 'POST': form = CourseRegistrationForm(request.POST) if form.is_valid(): term = form.cleaned_data['semester'] subj = form.cleaned_data['subject'] crse = form.cleaned_data['course_number'] classes_result = scrape_course_data.delay(term, subj, crse) classes = classes_result.get() # Get the actual result print(classes) context = { 'form': form, 'classes':classes } return render(request, 'classes.html', context) else: form = CourseRegistrationForm() context = { 'form': form, } … -
Submitting jobs (to a postgre database) through django webpage, using slurm
I'm looking for advice on how to proceed, assuming at all this could be a viable course of action. I have coded a web-based interface (Django) to access some data stored on (an external) database. The role of the webpage is to serve as GUI to show the user what data can be downloaded, and where they are on a map. To avoid overwhelming the machine hosting the database, I am thinking in putting an intermediate layer between Django and the database, to manage submission of request to extract data. That would be slurm (or torque). It needs to be able to communicate through some python API. In essence, what I want to achieve is to allow the user to download data via either gui (Django amd plotly), OR by submitting a job file to slurm. The manager will, in turn, queue all the jobs and extract them one at the time. As an expected result, each registered user on the Django page, could access a dashboard (plugged to slurm) showing which jobs are running/pending, how long to completion, and possibly purge the ones that have already completed (or are no longer wanted). Note: I have only a few months … -
dotenv can not load read.dotenv
I have a django application. And I have dockerized the app. But I have a problem with the django-dotenv package. I have installed the django-dotenv package and not the python-dotenv. But if I try on my local machine: dotenv.read_dotenv() I get this error: Module 'dotenv' has no 'read_dotenv' member So I checked with pip freeze in my virtual environment if I have installed the correct package: (env) PS C:\repos\DWL_backend> pip freeze asgiref==3.6.0 attrs==23.1.0 certifi==2022.12.7 cffi==1.15.1 charset-normalizer==3.0.1 cryptography==39.0.0 defusedxml==0.7.1 Django==4.1.6 django-allauth==0.52.0 django-cors-headers==3.13.0 django-dotenv==1.4.2 djangorestframework==3.14.0 drf-spectacular==0.26.2 idna==3.4 inflection==0.5.1 jsonschema==4.17.3 oauthlib==3.2.2 Pillow==9.4.0 psycopg2==2.9.6 pycparser==2.21 PyJWT==2.6.0 pyrsistent==0.19.3 python3-openid==3.2.0 pytz==2022.7.1 PyYAML==6.0 requests==2.28.2 requests-oauthlib==1.3.1 sqlparse==0.4.3 tzdata==2022.7 uritemplate==4.1.1 urllib3==1.26.14 And now the funny part. I can run docker with: dotenv.read_dotenv() And the requirements.txt looks like: Django>=4.0.4 djangorestframework>=3.13.1 psycopg2>=2.9.3 drf-spectacular>=0.22.1 Pillow>=9.1.0 drf-yasg==1.20.0 django-cors-headers==3.10.1 django-dotenv So the package name django-dotenv are the same. oke. when I do a uninstall. I see this two packages: Found existing installation: django-dotenv 1.4.2 Uninstalling django-dotenv-1.4.2: Would remove: c:\repos\dierenwelzijn_backend\env\lib\site-packages\django_dotenv-1.4.2.dist-info\* c:\repos\dierenwelzijn_backend\env\lib\site-packages\dotenv.py what is dotenv.py? And I have read the official documentation: https://github.com/jpadilla/django-dotenv Question: how to run dotenv.read_dotenv on my localhost? -
How can we use Django property decorator in Django rest framework?
Hello I trying to use Django property decorator in Django rest framework here my code Model.py class TempCalculate(models.Model): items = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField() create_at = models.DateField(auto_now_add=True) create_by = models.ForeignKey(User, on_delete=models.CASCADE) @property def Price(self): self.price = (PriceMaster.objects.get(items = self.items)) * self.quantity Serializer.py from rest_framework import serializers from base.models import TempCalculate class TempCalSerializer(serializers.ModelSerializer): class Meta: model = TempCalculate fields = "__all__" api/view.py @api_view(['GET']) def TempItem(request): queryset = TempCalculate.objects.all() serializer_class = TempCalSerializer(queryset, many=True) return Response(serializer_class.data) **I trying to access self.price (which I have make property decorator in models.py) in rest api ** -
Django - working example of graphene aiodataloader
I've been looking into using a DataLoader in Django to optimise Graphene resolvers. I have been having trouble finding a working example of this as it requires multi threading. Based on what I can tell, there is no longer a way to specify executors in the latest versions of GraphQL in python. Does anyone have a working setup as an example? I was following the example below, and everytime I use async for my resolvers, I get: RuntimeError: There is no current event loop in thread 'ThreadPoolExecutor-1_0'. Which I think makes sense because GraphQL is using a sync executor by default (I stand corrected). I got this example from: https://docs.graphene-python.org/en/latest/execution/dataloader/ -
Django - 403 error while accessing static files in ec2 ubuntu server with nginx
I have used nginx default port 80. Deployed successfully django app. But got 403 error while accessing static files.. I know it is permission related issue. So I tried all the ways. but nothing is workout. gave 777 permission and www-data user. still I got permission denied error. file path structure location /static/ { root /home/ubuntu/FunQuiz-backend/FunQuizAPI/staticfiles/; autoindex on; } -
Is there any way to relay the data(stud.id) to the POST form?
{% for stud in student %} <tr> <td class="text-center">{{stud.id}}</td> <td class="text-center">{{stud.name}}</td> {% if x %} <td class="text-center">{{stud.main_sub}}</td> <td class="text-center">{{stud.fourth_sub}}</td> {% endif %} <td class="text-center"> <div> <a class="btn btn-outline-primary rounded " href="{% url 'updatestudent' stud.id %}" style="width: 0.75in;"> Edit </a> <button type="button" class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#exampleModal" style="width: 0.75in;"> Delete </button> </div> </td> </tr> {% endfor %} </tbody> </table> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Confirmation</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> Are you sure want to delete? {{stud.id}} </div> <div class="modal-footer"> <form action="" method="post"> {% csrf_token %} <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <input type="submit" class="btn btn-danger" value="Delete"> </form> </div> </div> </div> </div> Or maybe you could point me to some docs I could read. I'm new into programming and I'm learning based of off what my demo project needs. In this code, I used django templating for loop to loop through all the objects and posted em in a table. table has an option to delete which leads to a popup confirmation. Problem is I couldn't find any way to relay the data from the for loop part to the popup part where the post form is. -
auto-fill a form field with currently logged in user django
i have a form and when rendering should have some of the fields pre-filled and disabled with currently logged-in user, django. This is the rendered django form and under the username field should show only the current logged-in user and not all the registered users. views.py @login_required def teacherRecordForm(request): if request.user.is_authenticated: teacher_form = TeacherRecordForm if request.method == 'POST': teacher_form = TeacherRecordForm(request.POST, request.FILES) if teacher_form.is_valid(): teacher_form.save() messages.success(request, 'Details Saved Successfully') return redirect ('teacher-record-form') else: messages.success(request, 'check your information provided well') return render(request, 'schRecords/teacherRecordForm.html', {'teacher_form':teacher_form}) else: return render(request, 'schRecords/teacherRecordForm.html', {'teacher_form':teacher_form}) else: messages.success(request, 'kindly sign in first') return redirect('sign-in') -
In my python django projuct tried to host in godaddy cpanel but the pillow is not installing
In file included from src/libImaging/Imaging.h:688, from src/libImaging/XbmEncode.c:16: src/libImaging/ImagingUtils.h:35: warning: 'inline' is not at beginning of declaration cc1: warning: unrecognized command line option "-Wno-unused-result" cc1: warning: unrecognized command line option "-Wno-unused-result" cc1: warning: unrecognized command line option "-Wno-unused-result" gcc -Wno-unused-result -Wsign-compare -DNDEBUG -D_GNU_SOURCE -fPIC -fwrapv -O2 -pthread -Wno-unused-result -Wsign-compare -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -D_GNU_SOURCE -fPIC -fwrapv -D_GNU_SOURCE -fPIC -fwrapv -O2 -pthread -Wno-unused-result -Wsign-compare -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -fPIC -DHAVE_LIBJPEG -DHAVE_LIBZ -DHAVE_LIBTIFF -DHAVE_XCB -DPILLOW_VERSION=\"10.0.0\" -I/usr/include/freetype2 -I/usr/include -I/home/xhpnfadbs797/virtualenv/public_html/shopwithambro.com/3.9/include -I/opt/alt/python39/include/python3.9 -c src/libImaging/ZipDecode.c -o build/temp.linux-x86_64-cpython-39/src/libImaging/ZipDecode.o In file included from src/libImaging/Imaging.h:688, from src/libImaging/ZipDecode.c:18: src/libImaging/ImagingUtils.h:35: warning: 'inline' is not at beginning of declaration cc1: warning: unrecognized command line option "-Wno-unused-result" cc1: warning: unrecognized command line option "-Wno-unused-result" cc1: warning: unrecognized command line option "-Wno-unused-result" gcc -Wno-unused-result -Wsign-compare -DNDEBUG -D_GNU_SOURCE -fPIC -fwrapv -O2 -pthread -Wno-unused-result -Wsign-compare -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -D_GNU_SOURCE -fPIC -fwrapv -D_GNU_SOURCE -fPIC -fwrapv -O2 -pthread -Wno-unused-result -Wsign-compare -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -fPIC -DHAVE_LIBJPEG -DHAVE_LIBZ -DHAVE_LIBTIFF -DHAVE_XCB -DPILLOW_VERSION=\"10.0.0\" -I/usr/include/freetype2 -I/usr/include -I/home/xhpnfadbs797/virtualenv/public_html/shopwithambro.com/3.9/include -I/opt/alt/python39/include/python3.9 -c src/libImaging/ZipEncode.c -o build/temp.linux-x86_64-cpython-39/src/libImaging/ZipEncode.o In file included from src/libImaging/Imaging.h:688, from src/libImaging/ZipEncode.c:17: src/libImaging/ImagingUtils.h:35: warning: 'inline' is not at beginning of declaration cc1: warning: unrecognized command line option "-Wno-unused-result" cc1: warning: unrecognized command line option "-Wno-unused-result" cc1: warning: … -
Django/MSSQL: Issues counting objects depending on attribute
environment: Database: MSSQL Django 3.2.20 mssql-django 1.3 models class ChangeOrder(models.Model): # ...fields... class GroupChange(models.Model): order = models.ForeignKey( AssignmentChangeOrder, related_name='groupchanges' ) action = models.CharField(max_length=10, choices=['assignment', 'removal']) # ...other fields... class UserChange(models.Model): order = models.ForeignKey( AssignmentChangeOrder, related_name='userchanges' ) action = models.CharField(max_length=10, choices=['assignment', 'removal']) # ...other fields... objective For each ChangeOrder, I want to annotate/calculate: ant_assignment_count: Count of 'assignment' actions in both GroupChange and UserChange. ant_removal_count: Count of 'removal' actions in both GroupChange and UserChange. query ChangeOrder.objects.annotate( ant_assignment_count=Sum( Case( When(userchanges__action='assignment', then=1), When(groupchanges__action='assignment', then=1), default=0, output_field=IntegerField() ) ), ant_removal_count=Sum( Case( When(userchanges__action='removal', then=1), When(groupchanges__action='removal', then=1), default=0, output_field=IntegerField() ) ) ) objects co = ChangeOrder.objects.create() GroupChange.objects.create(order=co, action='removal', ..) GroupChange.objects.create(order=co, action='removal', ..) UserChange.objects.create(order=co, action='assignment', ..) If I run the query with those created objects I receive ant_assignment_count=2 and ant_removal_count=2. But it should be ant_assignment_count=1 and ant_removal_count=2. I've attempted various methods including annotations, subqueries, and Count with Case statements. However, I'm encountering issues and getting incorrect results. It seems to be a problem with the LEFT OUTER JOIN on GroupChange and UserChange. I'd appreciate any help! -
The cause of the error "List matching query does not exist."
I'm writing a Django auction program, and in the last levels of the program, when I wrote the code to select the winner of the auction and created the corresponding table with sqlite, I encountered this error. After this bug, no products will be displayed on the main page and product information cannot be seen. What is the cause of this error? I changed the names of the columns of the table, but it had no effect, and the rest of the code was working before creating this table. Exception Type: DoesNotExist at /auctions/1 Exception Value: List matching query does not exist. -
Django SearchFilter exists relationship without DISTINCT
Table search is implemented through rest_framework.filters SearchFilter with the addition of DISTINCT, which is not suitable for a large database, how to avoid this, what are the hacks for this class UserList(generics.ListAPIView): queryset = User.objects.order_by('-created') filter_backends=( SearchFilter, DjangoFilterBackend, ) search_fields = ( 'id', 'email', 'comments__id', ) thought about adding annotate(cnt=Count('comments',filter=Q(comments__id__icontains=search)).filter(cnt) to get_queryset, but then it's not clear when to do 'OR' -
Why is the django for traceback happening on my code wsv chapter 7?
File "/Users/russellanderson/Desktop/code/blog/.venv/lib/python3.11/site-packages/django/views/generic/edit.py", line 127, in get_success_url raise ImproperlyConfigured( ^ Exception Type: ImproperlyConfigured at /post/new/ Exception Value: No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model. -
Search with parent foreignkey, grandparent foreignkey in django-admin
I wanna be able to search a product with the category that isnt directly linked to it but the category is grandfather or great_great grandfather and so on above on the category tree of the category that is actually linked to the product itself. The only way i could implement was with the following which is ofcourse not scalable and proper way to do it: def get_queryset(self, request): queryset = super().get_queryset(request).select_related('brand', 'category', 'category__parent') category_name = request.GET.get('category__name', None) if category_name: # Filter the queryset to include products with the specified category or its ancestors queryset = queryset.filter( Q(category__name=category_name) | Q(category__parent__name=category_name) | Q(category__parent__parent__name=category_name) | # Add more levels as needed based on the depth of your category tree ) return queryset And here are the code as of now: Product``models.py class Product(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(blank=True, null=True) description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='product_images/') category = models.ForeignKey(Category, on_delete=models.SET_NULL,related_name='product_category', null=True, blank=True) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, related_name='product_brand', null=True, blank=True) tags = GenericRelation(TaggedItem, related_query_name='product') ratings = GenericRelation(Rating, related_query_name='product') active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) state = models.CharField(max_length=2, choices=PublishStateOptions.choices, default=PublishStateOptions.DRAFT) publish_timestamp = models.DateTimeField( # means that the publish_timestamp field will not automatically be set to the current date … -
Save the user prompt that is sent from web terminal to django
I am running a terminal on browser using xterm.js. The program sends the input to django working in backend. The code in views.py is a modified version from MahmoudAlyy github page. The input in the pty_input method receives all the keys that user presses. It can be modified to get only the command but it would take a long time and be open to bugs. Is there another way to get only the user prompt by changing frontend or backend code? views.py: async_mode = "eventlet" sio = socketio.Server(async_mode=async_mode) fd = None child_pid = None def index(request): return render(request, "index.html") def set_winsize(fd, row, col, xpix=0, ypix=0): winsize = struct.pack("HHHH", row, col, xpix, ypix) fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize) def read_and_forward_pty_output(): global fd max_read_bytes = 1024 * 20 while True: sio.sleep(0.01) if fd: timeout_sec = 0 (data_ready, _, _) = select.select([fd], [], [], timeout_sec) if data_ready: output = os.read(fd, max_read_bytes).decode() sio.emit("pty_output", {"output": output}) else: print("process killed") return @sio.event def resize(sid, message): if fd: set_winsize(fd, message["rows"], message["cols"]) @sio.event def pty_input(sid, message): if fd: os.write(fd, message["input"].encode()) @sio.event def disconnect_request(sid): sio.disconnect(sid) @sio.event def connect(sid, environ): global fd global child_pid if child_pid: os.write(fd, "\n".encode()) return (child_pid, fd) = pty.fork() if child_pid == 0: subprocess.run("bash") else: print() sio.start_background_task(target=read_and_forward_pty_output) @sio.event … -
How can make api using fastapi for django project
I want my projects to be more faster and i decided to use fastapi for them.But can't import my django models and form to fastapi.can someone help me to make api using fastapi for django projects? any code? (for example blog project) -
Django + Gunicorn: how to run background worker thread?
I need to run a background thread in my Django application. During development i could run a thread that accesses my models launching it from the ready() function inside apps.py: def ready(self): from .tasks.mqtt_worker import MqttHandler mqtt_handler = MqttHandler() th1 = threading.Thread(target=mqtt_handler.task) th1.daemon = True th1.start() In Production using Gunicorn this approach seems to fail.. How can I start a background python thread that accesses some models in my application in production? I am running my app behind nginx like this: /software/cloud/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock iotapp.wsgi:application -
How to edit parents objects as a child?
I have two classes in my project. User has a parent object . class User(AbstractUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) parent = models.ForeignKey("self",on_delete=models.DO_NOTHING,related_name='child_sections', blank=True, null=True) class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='articles') caption = models.CharField(max_length=250) timestamp = models.DateTimeField(auto_now_add=True)``` Here a parent and the child itself can edit any objects class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ("id","author","caption","timestamp") def validate(self, attrs): attrs = super().validate(attrs) if attrs.get('parent').id == self.context['request'].user.pk return attrs elif attrs.get('id') == self.context['request'].user.pk return attrs raise ValidationError('Unauthorized Request') Here parent can edit its child's object and a user can edit its own object. What I want to do is simple: A child can also edit parents object. Can anyone help me? -
Passing a variable in django class based views by extracting the value from a different model
I have two models namely categoreis and products. on my home page I have listed multiple categories and when I click on any category I want to open new page where products belonging to that category are displayed. I am passing the category_id through the url to products view page. but what I want to extract the category.title by using the category_id and the category model so that I can display it on top of products page. I have attached the code of my model class category(models.Model): title = models.CharField(max_length=30) image = models.ImageField(null=True, blank=True) def __str__(self): return self.title class product(models.Model): name = models.CharField(max_length=50, null=True, blank=True) slug = models.SlugField(null=True, blank=True) description = models.TextField(max_length=500,null=True, blank=True ) category = models.ForeignKey(category, on_delete=models.CASCADE) cost = models.PositiveIntegerField() image = models.ImageField(null=True, blank=True) def save(self, *args, **kwargs): # new self.slug = slugify(self.name) return super().save(*args, **kwargs) def __str__(self): return self.name the best I could do is append the category_id to context, but it isn't helpul in anyway. class products(ListView): model = product template_name = 'products/productList.html' context_object_name = 'products' def get_context_data(self, **kwargs): context = super(products, self).get_context_data(**kwargs) context['category'] = self.kwargs['cat_id'] return context I referred to some stackoverflow questions but couldn't find anything helpul. -
How can I pass a list of objects in Django?
stackoverflow! I'm working on small project that make's short links from full urls, but I have the issue. How can I do "GET" method that will be return list of my objects? I wrote "POST" method, but when I tried to write the same thing I got error and my request required to use "full_url" to get data. Model class: class Links(models.Model): full_url = models.URLField(unique=True) short_url = models.CharField( max_length=20, unique=True, db_index=True, blank=True ) requests_count = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) class Meta: ordering = ('-created_at'), def save(self, *args, **kwargs): if not self.short_url: while True: self.short_url = ''.join( random.choices( settings.CHARACTERS, k=settings.TOKEN_LENGTH ) ) if not Links.objects.filter( short_url=self.short_url ).exists(): break super().save(*args, **kwargs) def __str__(self) -> str: return f'{self.short_url} -> {self.full_url}' another function from views.py: class LinkAPIView(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def post(self, request): serializer = LinkSerializer(data=request.data) if serializer.is_valid(raise_exception=True): token, status_code = serializer.create( validated_data=serializer.validated_data ) return Response(LinkSerializer(token).data, status=status_code) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Error installing uWSGI always when i try it in linux
when i install uWSGI with: pip install uwsgi raise error: *** uWSGI compiling server core *** [x86_64-linux-gnu-gcc -pthread] core/utils.o x86_64-linux-gnu-gcc: fatal error: cannot execute ‘cc1’: execvp: No such file or directory compilation terminated. ---------------------------------------- ERROR: Failed building wheel for uwsgi my ubuntu: 20.04 python: 3.8.10 also i have installed all required packages like: python3-pip python3-dev build-essential libssl-dev libffi-dev python3-setuptools as general question why i always have problem with uWSGI installation? in every VPS, in every Linux i had error Failed building wheel. I confused why others dont face with this problems! -
xterm.js term.onData is not a function
I am programming a terminal application using xterm.js in frontend and django at backend. Everything works fine but when i try to save the input from the user using onData i get it is not a function error. If you have another approach please tell me. I tried getting current line but run into problems if user press backspace or delete. index html: var socket = io.connect({ transports: ["websocket", "polling"] }); const status = document.getElementById("status") const button = document.getElementById("button") var term = new Terminal({ cursorBlink: true, }); term.open(document.getElementById('terminal')); var curr_line = ''; var entries = []; var currPos = 0; var pos = 0; var prompt_startpos = term._core.buffer.x term.onData(data => { console.log("Data received:", data); socket.emit("pty_input", { "input": data }); }); views py: async_mode = "eventlet" sio = socketio.Server(async_mode=async_mode) fd = None child_pid = None def index(request): return render(request, "index.html") def set_winsize(fd, row, col, xpix=0, ypix=0): winsize = struct.pack("HHHH", row, col, xpix, ypix) fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize) def read_and_forward_pty_output(): global fd max_read_bytes = 1024 * 20 while True: sio.sleep(0.01) if fd: timeout_sec = 0 (data_ready, _, _) = select.select([fd], [], [], timeout_sec) if data_ready: output = os.read(fd, max_read_bytes).decode() sio.emit("pty_output", {"output": output}) else: print("process killed") return @sio.event def resize(sid, message): if fd: set_winsize(fd, … -
Django passing extra context from Form View after working on form fields
So I have a form in which I get some data, and I use this data to retrieve an object from some model. But, I am not able to pass the data I retrieved from this object into the context in the is_valid function. It breaks the success redirect logic. What can I do for this situation?