Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I resolve the Django error "object of type 'int' has no len()" when creating an object in the admin site?
I'm aware of what the error means, the length function is being called on an integer, whereas it only takes a string. However, the tracelog is not particularly helpful and I'm struggling to identify where this error is happening. C:\Users\callu\PycharmProjects\DjangoTests\venv\Lib\site-packages\django\forms\boundfield.py, line 162, in _has_changed return field.has_changed(initial_value, self.data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … Local vars C:\Users\callu\PycharmProjects\DjangoTests\venv\Lib\site-packages\django\forms\models.py, line 1650, in has_changed if len(initial) != len(data): ^^^^^^^^^^^^ It happens when I try and create a new Post object in the admin site so I'm assuming there's an error somewhere in my Post Model, have I created one of the wrongs as the wrong type? class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, default=None, null=True) title = models.CharField(max_length=100) slug = models.SlugField(blank=True) description = models.TextField(max_length=500) date = models.DateTimeField(auto_now_add=True) url_link = models.URLField(default=None, blank=True) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="post_support", default=0, blank=True) tags = models.ManyToManyField(Tag, blank=True) class Meta: ordering = ('-date',) def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:post_detail", args=(str(self.id),)) Weirdly I can create a Post object fine from my front end, it's just when I try to use the admin site that it throws the error. -
Django register error not fully translated
Standard error massage during registration is: "user account with this email already exists." After I changed LANGUAGE_CODE to 'pl' in settings.py I get: "Istnieje już user account z tą wartością pola email." Instead of "user account" should be "konto użytkownika". Translation mistake is so obvious that I thought that "user account" is somewhere in my project files so I searched my django project and there is no single string in any of my files. How to fix this translation? In django I use 'rest_framework' and 'rest_framework_simplejwt' -
Django Rest framework
I have getting a error 400 bad request when registration. How can I fix it? Suggest something to fix it. I have done authentication in views, sent mail class to sending mail for otp verification to user I'm expecting a suggestion to fix it -
When I click to reserve, I can't save the reservation
I have received the value from the search page and shown in the booking page but also want to record that value as room, details, booking date, booking end and total price of the booking. but cannot save the value view.py def booking_cat_hotel(request, room_number, check_in_date, check_out_date): one_room = Room.objects.get(room_number=room_number) num_days = (datetime.strptime(check_out_date, '%Y-%m-%d').date() - datetime.strptime(check_in_date, '%Y-%m-%d').date()).days total_price = num_days * one_room.price if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): booking = form.save(commit=False) booking.room = one_room booking.start_date = datetime.strptime(check_in_date, '%Y-%m-%d').date() booking.end_date = datetime.strptime(check_out_date, '%Y-%m-%d').date() booking.total_price = total_price booking.save() return redirect('completed', booking_id=booking.id) else: form = BookingForm(initial={ 'room': one_room, 'room_number': one_room.room_number, 'start_date': check_in_date, 'end_date': check_out_date, }) context = { "one_room": one_room, "check_in_date": check_in_date, "check_out_date": check_out_date, "form": form, "total_price": total_price, } return render(request, 'cat_hotel/cat_hotel.html', context=context) html <form action="{% url 'booking_cat_hotel' room_number=one_room.room_number check_in_date=check_in_date check_out_date=check_out_date %}" method="POST"> {% csrf_token %} <div class="container"> <div class="card p-4 mt-5"> <div class="row g-3"> <div class="col-12 mb-4"> <div class="col-12 mb-4"> <h4>Room {{ one_room.room_number }}</h4> <span class="text-muted">{{ one_room.description }}</span> <input type="hidden" name="room_number" value="{{ one_room.room_number }}"> <input type="hidden" name="room_description" value="{{ one_room.description }}"> </div> </div> <div class="col-lg-2 col-md-6 ml-3"> <h5>Check-in Date</h5> <p class="text-primary">{{ check_in_date }}</p> <input type="hidden" name="check_in_date" value="{{ check_in_date }}"> </div> <div class="col-lg-6 col-md-12"> <h5>Check-out Date</h5> <p class="text-primary">{{ check_out_date }}</p> <input type="hidden" … -
Instance deployment failed to install Django application dependencies
I'm trying to deploy my Django app with MySql database into AWS Elastic Beanstalk. Following the official AWS tutorial, after running the command eb deploy I receive the following: Creating application version archive "app-a676-230715_151203074474". Uploading training_centre/app-a676-230715_151203074474.zip to S3. This may take a while. Upload Complete. 2023-07-15 07:12:36 INFO Environment update is starting. 2023-07-15 07:12:39 INFO Deploying new version to instance(s). 2023-07-15 07:12:45 ERROR Instance deployment failed to install application dependencies. The deployment failed. 2023-07-15 07:12:45 ERROR Instance deployment failed. For details, see 'eb-engine.log'. 2023-07-15 07:12:49 ERROR [Instance: i-0cd43d89a29ebb953] Command failed on instance. Return code: 1 Output: Engine execution has encountered an error.. 2023-07-15 07:12:50 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2023-07-15 07:12:50 ERROR Unsuccessful command execution on instance id(s) 'i-0cd43d89a29ebb953'. Aborting the operation. 2023-07-15 07:12:50 ERROR Failed to deploy application. ERROR: ServiceError - Failed to deploy application. Here is the output of eb logs: ============= i-0cd43d89a29ebb953 ============== ---------------------------------------- /var/log/eb-engine.log ---------------------------------------- Command 'pkg-config --exists mariadb' returned non-zero exit status 1. Traceback (most recent call last): File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/pip/_vendor/pep517/in_process/_in_process.p y", line 351, in <module> main() File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/pip/_vendor/pep517/in_process/_in_process.p y", line 333, in main json_out['return_val'] = hook(**hook_input['kwargs']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/pip/_vendor/pep517/in_process/_in_process.p y", line 118, in get_requires_for_build_wheel return hook(config_settings) File "/tmp/pip-build-env-098fsfb8/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", … -
Who renders a django TemplateResponse if I don't?
Suppose I return a TemplateResponse object from a view in Django. Even if I don't manually call response.render() anywhere in my code, what is returned is a rendered object. Which middleware or other part of Django automatically renders TemplateResponses? I tried going through the code but couldn't find it. -
How to use django asynhronous programming with drf API views?
I am trying to implement asynchronous programming with django rest framework and I am using api_view decorators for my function based API views. So I was trying to convert my synchronous method to asynchronous with asgiref.sync.sync_to_async decorator but seems like using this django is not able to route to my API view. Here is my function based api view. from rest_framework.decorators import permission_classes, api_view, authentication_classes from rest_framework.permissions import AllowAny, IsAuthenticated from asgiref.sync import sync_to_async from ..customauth import CustomAuthBackend from ..utils.auth_utils import AuthUtils @api_view(['POST']) @permission_classes([AllowAny]) @authentication_classes([]) @sync_to_async def login(request): email = request.data.get('email') if email is None or email == '': return Response(data={'success': False, 'message': 'Invalid credentials'}) user = User.get_by_email(email=email) if user is not None and user.is_active and user.check_password(raw_password=request.data.get('password')): serializer = UserSerializer(user) tokens_map = AuthUtils.generate_token(request=request, user=user) return Response({'success': True, 'user': serializer.data, 'tokens': tokens_map}) return Response(data={'success': False, 'message': 'Invalid login credentials'}, status=status.HTTP_403_FORBIDDEN) If I use async def that is also not working with django rest framework. How do I make the use of event loop here efficiently ? -
In Django how can I use string concatenation (||"-"||) for fields in a database and display them in the form?
I would like to use this ||"-"|| SQL string concatenation between x = models.CharField(max_length=30) and y = models.CharField(max_length=30). Next in the combobox on the form, I would like to display all x and y fields of the database, like this: x-y Being new to Django, I don't know how to pass the parameter in views.py in this line: object_voyage = form.cleaned_data['voyage'], considering that 'voyage' is not a database field because there are x and y in the database. voyage is the name of the containment. I tried using CharField and Concat, but I don't know if it's the right solution. Maybe I've completely got the wrong approach and need a different way, I don't know.The error is that the combobox of the form is not displayed at all The SQL code, to make you understand better, would be this: SELECT x||"-"||y FROM Table1 Here is my code: models.py from django.db import models class MyVoyage(models.Model): x = models.CharField(max_length=30) y = models.CharField(max_length=30) def __str__(self): return self.x, self.y forms.py from django import forms from .models import MyVoyage from django.db.models import CharField, Value from django.db.models.functions import Concat class Form_MyVoyage(forms.Form): voyage = forms.ModelChoiceField(queryset=MyVoyage.objects.annotate(match=Concat('x', Value('-'), 'y', output_field=CharField()))) views.py def View_MyVoyage(request): object_voyage = None if request.method == … -
How to set up header and footer in every page of a pdf without overlapping them with inner contents using python weasyprint?
as you can see i have header and footer and in between them there is a order item table which is kind of overlapping with the footer I have tried this way there is a header , a main section then a footer the header is set to fix and main is set to relative and the footer is set to fixed here is the html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> @page { size: A4; margin: 10mm 15mm; padding: 0; @top-center{ content: element(header); } @bottom-center{ content: element(footer); } } header { position: fixed; top: 0; width: 100%; } footer { position: fixed; bottom: 0; font-size: 10px; text-align: center; width: 100%; padding: 5px; margin: -10mm; } main { position: relative; top: 250px; width: 100%; } *{ font-family: Verdana, Geneva, Tahoma, sans-serif; } .logo{ height: 70px; width: 80px; } .qr_img { height: 80px; width: 80px; } .flex{ display: flex; flex-wrap: nowrap; flex-direction: row; align-items: center; justify-content: space-between; } .vertical { border-left: 3px solid gray; height: 70px; position:absolute; } .invoice-word{ font-size: 45px; font-weight: bolder; } .order-info{ font-size: 12px; } .order-info p{ margin: 0; } .py-2{ padding: 2px 2px 2px 2px; } … -
Django error: 'tuple' object has no attribute 'get'
So, I started to make my first Django project, everything was okay but when I make my second site and Runserver this message popped up: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.2.3 Python Version: 3.10.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home'] Installed 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'] Traceback (most recent call last): File "C:\Users\hungp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\hungp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\deprecation.py", line 136, in __call__ response = self.process_response(request, response) File "C:\Users\hungp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\middleware\clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: Exception Type: AttributeError at / Exception Value: 'tuple' object has no attribute 'get' Here is my code: views.py: from django.shortcuts import render # Create your views here. def home(request): return render(request, 'home/home.html'), def product(request): return render(request, 'home/product.html'), def register(request): return render(request, 'home/register.html'), I have try looking in my views.py file, my urls.py and even setting.py but I couldn't find any tuple as mentioned in the error. I have also tried reinstalling Django but it didn't work. The last thing that I did was check my views.py as suggested on some previous error posts on StackOverflow but it didn't work either. Edit 1: I found the solution. The error is … -
Sql Field Recursive Limit Exceeded: Model with a parent reference to another of itself
So far. I can understand that there is a sql/database querying issue related to this. The symptoms of the bug is also a long wait time, typical of a recursive method. Although, imo it shouldnt be recursive, it should just list categories that match the parent category. I am doing this all from the admin part at the moment, and I am not quite sure how to work with django enough to know how to solve this issue correctly, at the moment. So the rundown: Slow response to an error (recursive function behaviour within database?) Occurs when accessing the admin/category/create page (GET request) Something to do with having a parent 'category' in itself *edit: I think it may have to do with looking into itself, when it shouldnt. Here is the code, all in the same module: # models.py class Category(models.Model): title = models.CharField(max_length=32, unique=True) parent_category = models.ForeignKey( "self", related_name="sub_categories", on_delete=models.SET_NULL, null=True, blank=True, ) featured_product = models.ForeignKey( "Product", on_delete=models.SET_NULL, null=True, blank=True, related_name="+" ) def __str__(self) -> str: if self.parent_category: return f"{self.parent_category} - {self.title}" return self.title class Meta: ordering = ["title"] # admin.py @admin.register(models.Category) class CategoryAdmin(admin.ModelAdmin): autocomplete_fields = ["featured_product"] list_display = ["title", "products_count"] search_fields = ["title"] @admin.display(ordering="products_count") def products_count(self, category): url … -
I have a lsitview that return a list pf product but i want to be able to sort it by price in ascending and descending other and also by discount price
view.py class HomeView(ListView): model = Item template_name = "home.html" paginate_by = 12 template <div class="header-dropdown"> <a href="#">A to Z</a> <div class="header-menu"> <ul> <li><a href="#">A to Z</a></li> <li><a href="#">Z to A</a></li> <li><a href="#">Discount</a></li> <li><a href="#">Low to high price</a></li> <li><a href="#">High to low price</a></li> </ul> </div> </div> Pls how can I get queryset for each list such that it reorder the list in different ways and display it in the template without reloading the page. -
Can't convert a HTTP response to JSON
I'm fetching my own API, fetch('/guidebook/api/peak-data/') .then(response => response.json()) .then(response => JSON.stringify((response))) .then(data => { console.log('Raw JSON data:', data); console.log('Type of data:', typeof data); console.log('Type of features:', typeof data.features); }) .catch(error => { console.log('Error:', error); }); The data come from this function, it's published in api/peak-data urlpatterns = [ path('', views.returnPage), path('api/peak-data/', views.get_peak_data, name='peak_data'), ] def get_peak_data(request): peaks = Peak.objects.all() peak_data = serialize('geojson', peaks, geometry_field='peak_coordinates') return JsonResponse(peak_data, safe=False, content_type='application/json') Here is the associated django model : class Peak(models.Model): peak_id = models.BigIntegerField() peak_name = models.CharField(max_length=80) peak_coordinates = postgismodel.PointField(geography=True, default=Point(0, 0), blank=True, null = True) peak_elevation = models.IntegerField() I Convert it to JSON, and for some reason, I obtain a string Type of data: string Type of features: undefined No features found in the JSON data. I'm struggling to understand why. In particular, I'd like to isolate the coordinates attributes using the Json, but since I do not have one, I can't -
Celery can't send tasks to queue when running in docker
I tested it on windows and it worked, but now I want to do it using docker. The problem is when I try to execute task to send email to user I get error: [Errno 111] Connection refused, but celery starts successfully and connects to rabbitmq. Why can't celery send tasks to rabbitmq? Traceback (most recent call last): File "/usr/local/lib/python3.11/dist-packages/kombu/utils/functional.py", line 32, in __call__ return self.__value__ ^^^^^^^^^^^^^^ During handling of the above exception ('ChannelPromise' object has no attribute '__value__'), another exception occurred: File "/usr/local/lib/python3.11/dist-packages/kombu/connection.py", line 472, in _reraise_as_library_errors yield ^^^^^ File "/usr/local/lib/python3.11/dist-packages/kombu/connection.py", line 459, in _ensure_connection return retry_over_time( File "/usr/local/lib/python3.11/dist-packages/kombu/utils/functional.py", line 318, in retry_over_time return fun(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/kombu/connection.py", line 941, in _connection_factory self._connection = self._establish_connection() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/kombu/connection.py", line 867, in _establish_connection conn = self.transport.establish_connection() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/kombu/transport/pyamqp.py", line 203, in establish_connection conn.connect() ^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/amqp/connection.py", line 323, in connect self.transport.connect() ^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/amqp/transport.py", line 129, in connect self._connect(self.host, self.port, self.connect_timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/amqp/transport.py", line 184, in _connect self.sock.connect(sa) ^^^^^^^^^^^^^^^^^^^^^ The above exception ([Errno 111] Connection refused) was the direct cause of the following exception: File "/usr/local/lib/python3.11/dist-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File … -
Printing from Django
I've been doing some googling and I am not turning up the answer I am searching for. Essentially I have a Django web app. One of the models is a Blueprint which contains a link to a PDF stored someplace. I want to be able to write an admin action so that if the user selects one or more of these models I can print the PDFs attached one after another to a physical printer. 90% of the stuff I'm finding is about how to create PDFs. I don't want to create them, they already exist. Essentially all I need to do is allow the user to select a printer to send the pdfs to in a sequential order. I'm a little confused on what needs to be done , but I might just be overthinking it. From inside the admin action I have access to all the selected Objects. But the actual PDF files would be in memory not sitting in disk someplace. They do exist in storage. However, this is running inside a browser so I suppose all I need to do is trigger the browser's inborn print capability and pass it some sort of reference to the … -
Error: Incorrect padding when decoding encrypted payload data in Django registration view function
I want to encode my payload data for a form so that on submission the view function for my registration decodes the data and performs necessary validation on the data and saves it to the database. However, I keep getting the error below. Error at /register/ Incorrect padding Here is the complete Traceback Environment: Request Method: POST Request URL: http://localhost:8003/register/ Django Version: 4.2 Python Version: 3.9.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'authentication', 'rest_framework', 'rest_framework_simplejwt.token_blacklist', 'corsheaders'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/dubsy/virtualenvs/djangoproject/digirepo2/authentication/views.py", line 86, in post cipher = AES.new(base64.b64decode(encryption_secret_key), AES.MODE_ECB) File "/home/dubsy/anaconda3/lib/python3.9/base64.py", line 87, in b64decode return binascii.a2b_base64(s) Exception Type: Error at /register/ Exception Value: Incorrect padding Below are the code snippet that … -
How to call python function from javascript in django?
I'm making a Cubing Timer app. I have a django app which loads python function that generates a scramble from file in views.py. I have a JS file that runs timer by clicking Space bar. I want to generate new scramble everytime timer stops. How to do that? Here is my views.py file: from .scramble_generator import * def home(request): s = scramble_replace(scramble_gen()) scramble = sprint(valid(s)) return render(request, 'timer/index.html', {'scramble':scramble}) main.js: let state = 'stopped'; const transitions = { waiting: state => ResetTimer(), started: state => StartTimer(), stopped: state => PauseTimer(), }; document.addEventListener('keydown', changeState); document.addEventListener('keyup', changeState); function changeState({code, repeat, type: action}){ if(code !== 'Space' || repeat){ return; } // this allows to have more event types and states in the future without cluttering const actions = { keydown: () => state === 'stopped' ? 'waiting' : 'stopped', keyup: () => state === 'stopped' ? state : 'started', }; // determine the next state const next = actions[action](); // if the next state is different, commit it to the current and execute transition next === state || transitions[state = next](state); } -
How can I automatically attach a comment to a post?
I have a form for creating comments that already knows how to determine which user the message is from, but it does not know how to join the post to which it is written. Here are models.py: class Post(models.Model): title = models.CharField(max_length=150) text = models.CharField(max_length=8000) data = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='media/', null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) connect_category = models.ManyToManyField('Category') def __str__(self): return self.title def save(self): super().save() if self.image: img = Image.open(self.image.path) if img.height > 300 or img.width > 300: new_img = (500, 600) img.thumbnail(new_img) img.save(self.image.path) def get_absolute_url(self): return reverse('post', args=[str(self.id)]) class Category(models.Model): title = models.CharField(max_length=30) class Comments(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.CharField(max_length=800) approved = 'Approved' refused = 'Refused' choice = ( (approved, 'Одобрено'), (refused, 'Отказано') ) status = models.CharField(max_length=8, choices=choice, default='Ожидание') connect_post = models.ForeignKey('Post', on_delete=models.CASCADE, null=True) def get_absolute_url(self): return reverse('post', args=[str(self.id)]) views.py: class PostDetail(DetailView): model = Post template_name = 'post.html' context_object_name = 'post' form_class = CommentForm success_url = '' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comment_form'] = CommentForm(initial={'connect_post': self.object.id}) return context class CommentCreateView(CreateView): form_class = CommentForm success_url = '/' model = Comments def form_valid(self, form): form.instance.author = self.request.user post_id = form.cleaned_data['connect_post'] form.instance.connect_post = post_id return super().form_valid(form) forms.py: class CommentForm(forms.ModelForm): connect_post = forms.IntegerField(widget=forms.HiddenInput) class Meta: model = Comments … -
Using a database modeler with Django
I am trying to use Navicat as a visual way of designing the database Schema for a Django application. I saw the inspectdb command for Django, but it seems for migrating an old database to a new one, not continuous changes as the application is developed. What would the best way to integrate the both Navicat and Django together? Thanks in advance! -
ModuleNotFoundError when attempting runserver in a new Django project
Description: I'm encountering a ModuleNotFoundError while trying to run a developer server in a new Django project with a fresh virtual environment. The error refers to a project named "Carshering" and boostrap import that has no connection to the current project which is just created empty template. I'd like to understand the reason behind this error and how to resolve it. The error message includes <frozen importlib._bootstrap>, which prompted me to install two Bootstrap-related modules. (venv) C:\Users\karpi\PycharmProjects\WEB_QUIZ>python manage.py runserver Traceback (most recent call last): File "C:\Users\karpi\PycharmProjects\WEB_QUIZ\venv\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) ... ModuleNotFoundError: No module named 'Carshering' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\karpi\PycharmProjects\WEB_QUIZ\manage.py", line 22, in <module> main() ... ModuleNotFoundError: No module named 'Carshering' Expected Outcome: I expect the server to run successfully without any ModuleNotFoundError related to the "Carshering" project. Attempts so far: Created a new Django project in a fresh virtual environment. Installed Bootstrap using pip. Checked the installed packages and verified that the virtual environment is activated. Tried running the migration using the command python manage.py makemigrations, but encountered the ModuleNotFoundError. set PYTHONPATH Additional Information: Django version: 4.2.3 Python version: 3.11 django-bootstrap-form 3.4* crispy-bootstrap5 0.7* *These … -
Poetry can't find dependencies on installation
I'm trying to run a Django project. The project has the files poetry.lock and pyproject.toml and it runs on other computers, but I can't install it on my computer (macOS Monterey). On my computer with the newly created virtual environment (venv), when I run the poetry install command, I receive the message: "No dependencies to install or update." When I run the poetry show command, several libraries are listed. But when I run the project, Python doesn't find any libraries. (I can run older Python projects on my computer) -
Order a Django Queryset by how many times it appears in a Foreign Key
In my Django App i have a model called Room, class Room(models.Model): host = models.ForeignKey(User, on_delete=models.CASCADE, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null = True, blank = True) participants = models.ManyToManyField(User, related_name='participants', blank = True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name In my app, i want to show all the Topics ordered by counting how many rooms have that topic. class Topic(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name How can i order them? In my html file i can get this value by using <span>{{topic.room_set.all.count}}</span> that way i get the number of rooms that have this topic, which is useful, but don't work when using the order_by method. -
Reverse for url with arguments not found in Django
Error: Reverse for 'task_list_by_tag' with arguments '('оаип_1',)' not found. 1 pattern(s) tried: ['tag/(?P<tag_slug>[-a-zA-Z0-9_]+)/\Z'] views.py def index(request, tag_slug=None): task_list = Task.objects.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) task_list = task_list.filter(tags__in=[tag]) paginator = Paginator(task_list, 2) page_number = request.GET.get('page', 1) try: tasks = paginator.page(page_number) context = {"tasks":tasks, 'tag':tag} return render(request, 'main/index.html', context) urls.py app_name = 'main' ... path('tag/<slug:tag_slug>/', views.index, name = "task_list_by_tag"), index.html {% for tag in task.tags.all %} <a href="{% url "main:task_list_by_tag" tag.slug %}"> {{ tag.name }} </a> {% if not forloop.last %}, {% endif %} {% endfor %} I tried to fix that problem: 1) <a href="{% url "main:task_list_by_tag" tag_slug=tag.slug %}"> return the error: Reverse for 'task_list_by_tag' with keyword arguments '{'tag_slug': 'оаип_1'}' not found. 1 pattern(s) tried: ['tag/(?P<tag_slug>[-a-zA-Z0-9_]+)/\Z'] 2) `<a href="{% url "main:task_list_by_tag" slug=tag.slug %}">` Reverse for 'task_list_by_tag' with keyword arguments '{'slug': 'оаип_1'}' not found. 1 pattern(s) tried: ['tag/(?P<tag_slug>[-a-zA-Z0-9_]+)/\Z'] -
Issue With Anchor Tags Not Scrolling Far Enough in Django
I have a Django model called "prompt" that has particular properties, and I have linked these prompts to certain paragraphs (paragraph is another model) in the database depending on whether I want to display that prompt with that paragraph. Before I had starting displaying the prompts on the webpage alongside the paragraphs, my anchor tags inside the "sidebar" area worked properly and scrolled to the correct section of the page, but after I added in the prompts from the Django database, the anchor tag "jumping" functionality stopped working properly. Here is my code: {% extends 'prompt/base.html' %} {%block title%} Guidebook for Prompting {%endblock%} {%block content%} Guidebook on Prompting for Language Learning {%endblock%} {%block sidebar%} <div class="ml-3 mb-16 grid grid-cols-4 gap-4"> <div class="pb-6"> <div class="col-span-1"> <ul> {% for section in sections %} <li id="section{{section.id}}" class="py-2 px-2 rounded-xl"> <a href="{%url 'section:detail' section.id %}" class="section-link">{{section.section_title}}</a> <ul> {% for paragraph in section.paragraph_set.all %} <!-- here is the section where the links are--> <li id="paragraph{{paragraph.id}}" class="ml-3"> <a href="{%url 'section:detail' section.id %}#paragraph{{paragraph.id}}">{{paragraph.paragraph_title}}</a> </li> {%endfor%} </ul> </li> {%endfor%} </ul> </div> </div> <div class="space-y-10 mr-24 text-5xl col-span-3" id="section-text-container"> {{section.section_title}} <div class="mt-10 text-lg"> {{section.section_description}} </div> {%for paragraph in section.paragraph_set.all%} <!-- jump here --> <div id="paragraph{{paragraph.id}}" class="mt-10 text-3xl">{{paragraph.paragraph_title}}</div> <div class="text-lg">{{paragraph.paragraph_text … -
Content security policy blocking CKEditor write function in from bundled script in Django website application
In my Django website application, I am using CKEditor 5.1.1 and a bundled script is being blocked by my script-src directive in my content security policy. The offending file is bundle-5f73f48756.cms.ckeditor.min.js. Specifically, the write(a) function from the block of code below is being flagged in the console: write: function(a) { this.$.open("text/html", "replace"); CKEDITOR.env.ie && (a = a.replace(/(?:^\s*<!DOCTYPE[^>]*?>)|^/i, '$\x26\n\x3cscript data-cke-temp\x3d"1"\x3e(' + CKEDITOR.tools.fixDomain + ")();\x3c/script\x3e")); this.$.write(a); this.$.close() }, I have tried writing middleware (with the help of ChatGPT) to address the issue. I have successfully done this with other popup or inline scripts but in this case, the middleware does not work. The goal there was to inject my nonce into the script tag from the replace() function but nonetheless, the error persists. ChatGPT also suggested editing the configuration for CKEditor. However, since it is a "site-package" I am not sure where in my Django project I can actually update or override the configuration. For context, the path to my base.py (settings) file is marketing/marketing/settings/base.py