Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get hotels near a location using Google places api in a django framework?
I am working on a project using django framework. I want to use google places api to get hotels near a location(location as an input from the user). How to do that? I am new to django framework and integrating different APIs and there is not much information about this anywhere. -
How to use django.shortcuts.redirect outside the view function?
I am making a STT app on my website which uses openai-whisper. repo in need https://github.com/AkioKiyota/arge-test General Purpose Giving users a display/feedback about the process, and running a process without intervening the page. Working steps are like this: You upload your mp4-mp3 file throught form, You click the STT button next to your audio-clip-name, It downloads the whisper model(small), which happens once, Whisper transcribes the mp3 throught its path, Returns the result. Just ignore the div says 'last speech to text' its normaly where it should be showing it. Current script views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .forms import AudioStoreForm from .models import AudioStore import whisper def index(request): audios = AudioStore.objects.all() if request.method == 'POST': form = AudioStoreForm(request.POST, request.FILES) print(form.is_valid()) if form.is_valid(): form.save() return HttpResponseRedirect('') else: form = AudioStoreForm() return render(request, 'index.html', {'form': form, 'audios': audios}) def stt(request, audio_name): module = whisper.load_model('small') audio = AudioStore.objects.get(name=audio_name) result = module.transcribe(audio.audio_file.path, verbose=False) return HttpResponse(result['text']) The Issue The problem is, page just keep loading while the transribe on the process. But i atleast want to add a reloading icon to show user that its actualy working and he should wait. I have tried using Threads like this: views.py def … -
How to get installed package from broken virtual environment python
I had venv that installed Django and python version3.8. After upgrading my ubuntu my virtual environment doesn't work anymore and it doesn't recognize the pip command and it returns: ModuleNotFoundError: No module named 'pip' After searching I found out the virtual environment is broken after upgrading and the best way is to remove venv directory and create again and install your packages again but I don't have my installed package list (using pip freeze > list.txt) so now how can I get installed package list from the broken virtual environment? I can see the list of directories here: $ ls venv/lib/python3.8/site-packages/ but I don't have it -
Timezone in JavaScript(Frontend) and Python(Backend) in Django
I could get the timezone Asia/Tokyo with Intl.DateTimeFormat().resolvedOptions().timeZone in JavaScript in index.html Django Template (Frontend) as shown below: {% "templates/index.html" %} <script> console.log(Intl.DateTimeFormat().resolvedOptions().timeZone) // Asia/Tokyo </script> And, I could get the timezone Asia/Tokyo with tzlocal.get_localzone_name() in Python in test Django View (Backend) as shown below: # "views.py" from django.http import HttpResponse import tzlocal def test(request): print(tzlocal.get_localzone_name()) # Asia/Tokyo return HttpResponse("Test") Now, I set San Francisco to Location in my browser Google Chrome: Then, I could get the timezone America/Los_Angeles with Intl.DateTimeFormat().resolvedOptions().timeZone in JavaScript in index.html Django Template (Frontend) as shown below: {% "templates/index.html" %} <script> console.log(Intl.DateTimeFormat().resolvedOptions().timeZone) // America/Los_Angeles </script> But, I could still get the timezone Asia/Tokyo with tzlocal.get_localzone_name() in Python in test Django View (Backend) as shown below: # "views.py" from django.http import HttpResponse import tzlocal def test(request): print(tzlocal.get_localzone_name()) # Asia/Tokyo return HttpResponse("Test") My questions: Why does tzlocal.get_localzone_name() in Python in test Django View (Backend) still get the timezone Asia/Tokyo? Which timezone does Intl.DateTimeFormat().resolvedOptions().timeZone in JavaScript in index.html Django Template (Frontend) get, my browser timezone or my computer timezone? Which timezone does tzlocal.get_localzone_name() in Python in test Django View (Backend) get, my browser timezone or my computer timezone? -
why does it show "No installed app with label 'learning_logs' " when i try to migrate while I have it in the list of installed apps in settings.py?
i have made an app for a project in django and wrote a class in models.py . i have also included the name of app in the list of INSTALLED_APPS in settings.py . after it, when i try to migrate this change, it says "No installed app with label 'learning_logs'" the relevent screenshots: please help. i tried to do the same thing many times and it didn't work. i expected to get a success message but it showed other( as seen in screenshot) -
How to pass a variable from template to a view
My page has two models into it. They all inherit from one base model: Entry. class Entry(models.Model): author_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) author_id = models.PositiveIntegerField() author = GenericForeignKey("author_type", "author_id") text = models.TextField() class Meta: abstract=True ordering = ["date_created", "date_updated"] class Post(Entry): comments = GenericRelation(Comment, related_query_name="post") def __str__(self): return f"POST(ID{self.id})" class Discussion(Entry): head = models.CharField(max_length=60) comments = GenericRelation(Comment, related_query_name="discussion") def __str__(self): return f"DISCUSSION(ID{self.id})" Template: {% block main %} {% for entry in entries %} <div class="card" style="width: 18rem;"> <img src="{{entry.image}}" class="card-img-top" alt="..."> <div class="card-body"> {% if entry.head %} <h5 class="card-title">{{ entry.head }}</h5> {% else %} <p class="card-text">{{entry.text|slice:"0:20"}}</p> {% endif %} <a href="{% url 'posts:comments' entry.id %}" class="btn btn-primary">Comments</a> </div> </div> {% endfor %} {% endblock %} How can I pass a variable that will distinguish them in a corresponding view, or are there any better ways of doing it? <a href="{% url 'posts:comments' entry.id %}" class="btn btn-primary">Comments</a> My guess is that I need to pass a variable in a URL tag, that will be passed in a view, but I don't know how to do it. Is it the way? Or can I implement it in some better way? -
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!