Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue when migrating from SQLite to PostgreSQL in Django
I'm trying to migrate from SQLite to PostgreSQL. "makemigrations" works fine, but when I run the "migrate" command, everything gets complicated. Hello, I'm new to using Django, and I'm encountering the following error when trying to migrate from SQLite to PostgreSQL with an new database image 1 When I started the development of the project, I used fields like TimeField in my model. I'm attaching a snippet from my 0001_initial.py. image 2 Later, I realized that I should use time values differently and decided to modify the model to make them of type FloatField. Snippet from my migrations file 0004_alter_test_time_human_and_more.py image 3 I believe I understand that the issue is when I run the 'migrate' command, Django goes through all migration files, and that's where the conflict with PostgreSQL arises. Has anyone faced the same issue? Any help would be greatly appreciated. -
In select2, the values always is a empty string
I have a Python/Django project where I'm trying to add 'select2' to facilitate user search from a list of banks: class BuyerNaturalPersonBankAccountForm(forms.ModelForm): select_bank = MajorBankList( label='Banco', required=False, ) class Meta: model = BuyerBankAccount fields = ( 'name', 'cpf', 'cnpj', 'select_bank', 'bank', 'bank_code', 'agency', 'account', 'account_type', ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['bank'].required = False self.fields['bank_code'].required = False self.fields['bank'].widget.attrs.update( { 'v-model': 'bank', ':disabled': 'isBankDisabled', } ) self.fields['bank_code'].widget.attrs.update( { 'v-model': 'bank_code', ':disabled': 'isBankDisabled', } ) self.fields['select_bank'].widget = forms.Select( choices=self.fields['select_bank'].choices, attrs={ 'v-model': 'selectedBank', '@change': 'onBankChange', 'data-select2-enabled': True, } ) In my base.html, i have added the select2: var app = new Vue({ el: '#app', delimiters: ['[[', ']]'], data: { street: '', district: '', city: '', state: '', country: '', cpf: '', name: '', mother_name: '', father_name: '', nationality: '', selectedBank: '', bank: '', bank_code: '', bankAccountOwnerName: '', bankAccountCPF: '', birth_date: '', public_person: false, isLoading: false, isPostalCodeFound: true, isCPFFound: true, display_form_address: false, display_form_bank: false, hasError: '{{ error }}', }, beforeMount: function () { this.bank = this.$el.querySelector('#id_form-0-bank').value this.bank_code= this.$el.querySelector('#id_form-0-bank_code').value this.postal_code = this.$el.querySelector('#id_form-0-postal_code').value <script> $(document).ready(function() { $('[data-select2-enabled]').select2({ closeOnSelect: true, theme: "bootstrap" }); }); </script> In the HTML template, I perform these check: computed: { isBankDisabled: function() { return this.selectedBank ==! ''; } }, If I … -
Understanding TTFB Latency in DJango - Seems absurdly slow after DB optimizations even locally
Our team has been undergoing optimizing our Django DRF / Graphene stack for latency we can't quite understand the source of our slowdowns Our Stack: Python 3.11 Django 4.2.8 DRF 3.14.0 Django Graphene 3.1.5 We've done the 'basic' optimizations of implementing prefetch / select related removed all n+1 generated SQL queries And of course, scrounged the internet looking for answers, and saw the ModelSerializer issue posted here: https://hakibenita.com/django-rest-framework-slow Which as I understand it is 'mostly' fixed in the latest Django? We've manually optimized our QuerySets . SQL, and got our worst case SQL latency is around 200ms, most in the 10-100 range. However, our TTFB, is anywhere from 1 to 3 seconds as measured in dev tools on a browser performing a graphiQL query, as well as in our test suites Here are some numbers from GraphiQL Console: One GQL QUery generates 6 optimzied SQL Queries resulting in a response of a 1.4 MB JSon file which has a heavy amount of nested of elements (necessary for our workload) Django Debug Toolbar numbers: 101.9ms for SQL access Chrome Dev Tools 6 SQL Querues 56.44 ms (not sure how it knows this?) 44us to send request 937 ms waiting for server … -
Django Authentication error when connecting to local postgresql
I keep getting this error "password authentication failed for user postgres". I am trying to launch a django server on my computer using WSL (ubuntu 20.04) to my local laptop postgres database. I have my settings set correctly , i am able to connect to the psql from my ubuntu using, so the connection is fine. I set the pg_hba to trust postgres. But when i try to run my django i get the same password authentication error. Please help ,my pg_hba,wsl can connect using psql -U postgres,django settings,error,pg_ident tried this didnt help psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: Peer authentication failed for user "postgres" (Ubuntu) -
The test database of django return error collation case_insensitive for encoding "UTF8"
I am using django 4.2 and the CICharField was depreciated. And we need to use db_collation in CharField. I create a migration bellow to create collation case_insensitive # Generated by Django 4.2.8 on 2023-12-08 17:11 from django.db import migrations from django.contrib.postgres.operations import CreateCollation def create_collaction(apps, schema_editor): try: CreateCollation( 'case_insensitive', provider='icu', locale='und-u-ks-level2', deterministic=False ) except Exception: pass class Migration(migrations.Migration): dependencies = [ ('module', ''), ] operations = [ migrations.RunPython(create_collaction), ] In the normal database, all things run normal, but when I run python manage.py test, I receive the error: Creating test database for alias 'default'... Got an error creating the test database: database "test_database" already exists Type 'yes' if you would like to try deleting the test database 'test_database', or 'no' to cancel: yes Destroying old test database for alias 'default'... Traceback (most recent call last): File "/home/epitacio/.cache/pypoetry/virtualenvs/project-jss6nqd0-py3.9/lib/python3.9/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) psycopg2.errors.UndefinedObject: collation "case_insensitive" for encoding "UTF8" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/epitacio/workspace/smart-one/manage.py", line 41, in <module> main() File "/home/epitacio/workspace/smart-one/manage.py", line 37, in main execute_from_command_line(sys.argv) File "/home/epitacio/.cache/pypoetry/virtualenvs/project-jss6nqd0-py3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/epitacio/.cache/pypoetry/virtualenvs/project-jss6nqd0-py3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/epitacio/.cache/pypoetry/virtualenvs/project-jss6nqd0-py3.9/lib/python3.9/site-packages/django/core/management/commands/test.py", line 24, … -
Django Custom User model not updating
I have a custom user model with subclassing AbstractUser I want to update it with an Update view models.py: class UserManager(models.Manager): def New_Requests(self): return super.get_queryset().filter(is_seller="I") class User(AbstractUser): nickname = models.CharField(max_length=50,verbose_name="Nick Name",default='User') is_seller_status = ( ('N','Not accepted'), ('I','Investigate'), ('A','Accepted') ) is_seller = models.CharField(default='N',max_length=1,choices=is_seller_status,verbose_name='seller') user_id = models.UUIDField(default = uuid.uuid4,editable = False,unique=True) profile = models.ImageField(upload_to="user_profile",blank=True,null=True) admin_reject_reason = models.TextField(default='Not reviewed yet') views.py: class AccountView(LoginRequiredMixin,UpdateView): model = User form_class = UserProfileForm template_name = "user/profile.html" success_url = reverse_lazy("user:profile") def get_object(self): return User.objects.get(pk = self.request.user.pk) def get_form_kwargs(self): kwargs = super(AccountView, self).get_form_kwargs() kwargs['user'] = self.request.user # Pass 'user' directly to the form return kwargs urls.py: app_name = "user" urlpatterns = [ ... path('profile/',AccountView.as_view(),name='profile'), ... ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)` profile.html: {% extends 'user/base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <!-- Begin Page Content --> <div class="container-fluid"> <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h1 class="h3 mb-0 text-gray-800">Profile</h1> </div> <div class="col-md-12"> <div class = "card card-primary"> <div class="card-header"> <h3 class = "card-title mb-0 float-left">User Update</h3> </div> <div class="card-body"> <form method="post" action="{% url 'user:profile' %}" enctype="multipart/form-data">{% csrf_token %} <div class="row"> <div class="col-6"> {{ form.username|as_crispy_field }} </div> <div class="col-6"> {{ form.email|as_crispy_field }} </div> <div class="col-6"> {{ form.first_name|as_crispy_field }} </div> <div class="col-6"> {{ … -
Problems with CSRF token in django REST Framework integration with React
I'm doing a website using Django REST Framework as a backend with session authentication, React in the frontend and django-cors-headers to comunicate between the two. Each is served in the same IP adress but in different ports. I've implemented an authentication system using SessionAuthentication and the User model from django. The problem is that when I do post requests to the backend it always returns error 403 although the cors headers config seems to be correct and the csrftoken and X-CSRFToken are included in the headers. Here a part of the frontend responsible for the api calls: import axios from 'axios'; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'x-csrftoken'; axios.defaults.withCredentials = true; export const client = axios.create({ baseURL: "http://127.0.0.1:8000" }); export const Register = (credentials) => { return client.post('/api/register', credentials) } export const Login = (credentials) => { return client.post('/api/login', credentials, {'withCredentials': true}) } And the views.py: @method_decorator(csrf_protect, name='dispatch') class UserRegister(APIView): permission_classes = (permissions.AllowAny,) #authentication_classes = (SessionAuthentication,) def post(self, request): clean_data = custom_validation(request.data) serializer = UserRegistrationSerializer(data=clean_data) if serializer.is_valid(raise_exception=True): user = serializer.create(clean_data) if user: return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) @method_decorator(csrf_protect, name='dispatch') class UserLogin(APIView): permission_classes = (permissions.AllowAny,) #authentication_classes = (SessionAuthentication,) def post(self, request): data = request.data assert validate_username(data) assert validate_password(data) serializer = UserLoginSerializer(data=data) if … -
AttributeError 'NoneType' has no attribute 'name' on Django Project
I'll be very gratefull if someone could help me! I'm having some problems when try to access my dashboard page on my django project. The error is saying: AttributeError at /dashboard/ 'NoneType' object has no attribute 'name' Request Method: GET Request URL: http://localhost:8000/dashboard/ Django Version: 4.2.1 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'name' ............ My view.py file contains the function "dashboard_view": def dashboard_view(request): ........ plano_atual_usuario, preco_atual, conversas_a_pagar = user.current_user_plan_price_and_conversas_a_pagar(STANDART_PERIOD) numero_de_pedidos = pedidos.count() numero_de_conversas = conversas.count() numero_de_conversas_do_periodo = conversas_do_periodo.count() if numero_de_conversas > 0: taxa_conversao = round((numero_de_pedidos / numero_de_conversas) * 100, 2) else: taxa_conversao = 0.0 dias_para_pagamento = user.days_to_next_payment(STANDART_PERIOD) data_proximo_pagamento = today + timedelta(days=dias_para_pagamento) nome_do_plano = plano_atual_usuario.name -----> Problem is here!!! minimo_conversas_plano_atual = plano_atual_usuario.minimo_conversas limite_conversas_plano_atual = plano_atual_usuario.maximo_conversas valor_por_conversa_do_plano_atual = preco_atual gasto_atual_do_periodo = conversas_a_pagar * valor_por_conversa_do_plano_atual limite_atual_conversas = int(user.conversation_limit_set_by_user) ......... context = { 'user' : user, 'conversas': conversas, 'pedidos' : pedidos, 'dados_clientes' : dados_clientes, 'numero_de_pedidos' : numero_de_pedidos, 'numero_de_conversas' : numero_de_conversas, 'numero_de_conversas_do_periodo' : numero_de_conversas_do_periodo, 'taxa_conversao' : taxa_conversao, 'dias_para_pagamento' : dias_para_pagamento, 'nome_do_plano' : nome_do_plano, 'gasto_atual_do_periodo' : gasto_atual_do_periodo, 'valor_por_conversa_do_plano_atual' : valor_por_conversa_do_plano_atual, 'minimo_conversas_plano_atual' : minimo_conversas_plano_atual, 'limite_conversas_plano_atual' : limite_conversas_plano_atual, 'data_proximo_pagamento' : data_proximo_pagamento, 'conversas_a_pagar' : conversas_a_pagar, 'userIsPremium' : user.userIsPremium(), 'limite_atual_conversas': limite_atual_conversas, 'conversas_per_months': json.dumps(conversas_per_months), 'conversas_per_days': json.dumps(conversas_per_days), } return render(request, 'dashboard.html', context) I already make all migrations … -
Django - 'NoneType' object is not iterable
I have reviewed my code quite a bit and can't understand why this isn't working. My Products have a Category Model to put products in a specific category. I have sorting on the website to link to specific categories. I created a similar model for Special Offers so I can apply a sub category (special offers) and have a product appear either under the original category and the special offer category. Yet even with an identical configuration, just different variable names, I keep getting 'NoneType' object is not iterable. Any ideas what I'm doing wrong? views.py def all_products(request): """ A view to show all products, including sorting and search queries """ products = Product.objects.all() query = None categories = None sort = None direction = None special_offers = None if request.GET: if 'sort' in request.GET: sortkey = request.GET['sort'] sort = sortkey if sortkey == 'name': sortkey = 'lower_name' products = products.annotate(lower_name=Lower('name')) if sortkey == 'category': sortkey = 'category__name' if sortkey == 'special_offers': sortkey = 'special_offers__name' if 'direction' in request.GET: direction = request.GET['direction'] if direction == 'desc': sortkey = f'-{sortkey}' products = products.order_by(sortkey) if 'category' in request.GET: categories = request.GET['category'].split(',') products = products.filter(category__name__in=categories) categories = Category.objects.filter(name__in=categories) if 'special_offers' in request.GET: speical_offers … -
configuring supervisor Django on Centos/RedHat/Fedora
My django project is (using pwd) at: /usr/share/nginx/myweb.com/here I have cloned my repository name (alvar) I have got the gunicorn file like this GNU nano 7.2 gunicorn_start /bin/bash NAME="estate" DIR=/usr/share/nginx/myweb.com/alvar/ USER=boardsalvaro GROUP=boardsalvaro WORKERS=13 BIND=unix:/usr/share/nginx/myweb.com/alvar/run/gunicorn.sock DJANGO_SETTINGS_MODULE=estate.settings DJANGO_WSGI_MODULE=estate.wsgi LOG_LEVEL=error cd $DIR source ../venv/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../venv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- and the added block to the supervisord file like this [program:boards] command=/usr/share/ngingx/myweb.com/gunicorn_start user=boardsalvaro autostart=true autorestart=true redirect_stderr=true stdout_logfile=/usr/share/nginx/myweb.com/logs/gunicorn.log but when I try to reread the supervisord file I get error: <class 'FileNotFoundError'>, [Errno 2] No such file or directory: file: /usr/lib/python3.11/site-packages/supervisor/xmlrpc.py line: 560 -
403 Error while uploading file to Azure Blob via Django app, retrieving html output
I'm a student. This is my first time working with Azure or Django in this capacity, so please bear with me. This is for a final project due in a few days. I did not expect app deployment to be so incredibly complicated! I have written a series of Python files that accept an xlsx file via a form, compare the data of that xlsx file to an API, and then generate an html report of the results. The html is stored on an Azure blob and the link is then provided to the user for download. All of this works when I run the app locally (including the Azure blob connection). When I deploy to Azure, the app runs, but blocks the upload of the xlsx file and a nondescript 403 error is returned. I am not really sure what to try next. Sorry if I'm not providing the correct amount of detail, but happy to discuss further. I'll include more details about packages, etc. below Python Packages: Django pandas azure-storage-blob jinja2 requests Other standard Django dependencies I have tried the following to remedy this so far (I am going insane.): -Environment Variables: Configured necessary environment variables in Azure … -
How can I retrieve the Aerodrone model name and code field values correctly?
I'm working on a Django project with two models, Aerodrone and Meteo. I defined a foreign key in the Meteo model to reference the Aerodrone model. However, the foreign key fields in the database are named aerodrone_id and code_aerodrone_id. I want to retrieve the values of the name and aerodrone_code fields from the Aerodrone model in the Meteo model. I wrote the admin part but the code_aerodrone field always retrieves the values of the name field instead of code. Help me solve this problem. Here is the code: class Aerodrone(models.Model): nom = models.CharField(verbose_name="Nom de l'aérodrone", max_length = 150, unique=True) code = models.CharField(verbose_name="Code de l'aérodrone", max_length = 50, unique=True) class Meta: verbose_name_plural = "Aérodromes" def str(self): return self.nom class Meteo(models.Model): id_message = models.ForeignKey(Idmessage,verbose_name="Id du message", on_delete=models.CASCADE) aerodrone = models.ForeignKey(Aerodrone,verbose_name="Nom de l'aérodromes", on_delete=models.CASCADE, to_field="nom", related_name = "meteo_aerodrone_nom") code_aerodrone = models.ForeignKey(Aerodrone,verbose_name="Code de l’aérodromes", on_delete=models.CASCADE, to_field="code", related_name = "meteo_aerodrone_code") id_station = models.CharField(verbose_name="Code de la station", max_length = 50) date_heure = models.DateTimeField(auto_now_add=True, verbose_name="Date et heure") direction_vent = models.CharField(verbose_name="Direction et la force du vent", max_length = 150) visibilite = models.CharField(verbose_name="Visibilité horizontale", max_length = 150) temps_significat = models.CharField(verbose_name="Temps significatif", max_length = 150) nuages_significatif = models.CharField(verbose_name="Nuages significatif", max_length = 150) temperature = models.CharField(verbose_name="Température de l’air sec et du … -
django-telegram-login error username invalid
Im using the module django-telegram-login. I insert the code from documenatation into my project. def index(request): # Initially, the index page may have no get params in URL # For example, if it is a home page, a user should be redirected from the widget if not request.GET.get('hash'): return HttpResponse('Handle the missing Telegram data in the response.') try: result = verify_telegram_authentication( bot_token=bot_token, request_data=request.GET ) except TelegramDataIsOutdatedError: return HttpResponse('Authentication was received more than a day ago.') except NotTelegramDataError: return HttpResponse('The data is not related to Telegram!') # Or handle it like you want. For example, save to DB. :) return HttpResponse('Hello, ' + result['first_name'] + '!') def callback(request): telegram_login_widget = create_callback_login_widget(bot_name, size=SMALL) context = {'telegram_login_widget': telegram_login_widget} return render(request, 'accounts/telegram_auth/callback.html', context) def redirect(request): telegram_login_widget = create_redirect_login_widget( redirect_url, bot_name, size=LARGE, user_photo=DISABLE_USER_PHOTO ) context = {'telegram_login_widget': telegram_login_widget} return render(request, 'accounts/telegram_auth/redirect.html', context) if I've logged into telegram before I got the 'Invalid username' in my page and I coudn't open the page of autorazation in telegram again. If I haven't logged into telegram before I got the 'Inavlid username' in my page and I could open the page of autarazation at once. I haven't errors from the server. The bot is configured correctly. Im using … -
Django: No file was submitted. Check the encoding type on the form
I wanna make a form that allows uploading multiple images by one submit. I already set enctype in my form to "multipart/form-data", my image input contains "multiple" argument and my form initialization contains "request.POST and request.FILES" (form=self.form_class(request.POST, request.FILES) ). So normally It should be working but I'm encountering with this form error: <ul class="errorlist"><li>image<ul class="errorlist"><li>No file was submitted. Check the encoding type on the form.</li></ul></li></ul> My models.py: class Photo(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) image = models.ImageField(upload_to='photos') description = models.TextField(null=True, blank=True) def __str__(self): return self.image.name def save(self, *args, **kwargs): img = Image.open(self.image.name) img.resize(size=(300, 300)) img.save(self.image.name) return super(Photo, self).save(*args, **kwargs) My forms.py: class CustomFileInput(forms.ClearableFileInput): allow_multiple_selected = True class AddPhotoForm(forms.ModelForm): image = forms.ImageField(widget=CustomFileInput(attrs={'multiple': True}), required=True) description = forms.CharField(widget=forms.Textarea(), required=False) class Meta: model = Photo fields = ['image', 'description'] def save(self, commit=True): if commit: photo = Photo.objects.create( user=self.instance, image=self.cleaned_data['image'], description=self.cleaned_data['description'] ) photo.save() return photo My views.py: class AddPhotoView(CreateView): template_name = 'app/add-image.html' form_class = AddPhotoForm success_url = ... def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, context={'form': form}) def post(self, request, *args, **kwargs): form = self.form_class( request.POST, request.FILES, instance=request.user ) if form.is_valid(): form.save() return redirect(self.success_url) return render(request, self.template_name, context={'form': form}) My add-image.html: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="d-flex justify-content-center"> {{ … -
Quick hack to get Google Maps to look good on Mobile, works fine on Desktop for me
I have got a random google map location embedded onto a test location page. It appears fine and looks fine on Desktop. When I test on mobile. The right side of the map is going outside the container while everything else stays inside the container. Is there a way to prevent this? Is the only way to use google api / JS? Is there no sneaky quick little hack to fix this? <div class="container"> <div class="row"> <div class="col-12 col-md-6 contact-1"> <hr> <h2 class="logo-font mb-4 text-center">Contact Drum Loot</h2> <h5 class="text-muted text-center">Complete our Contact Form below!</h5> <hr> </div> <div class="col-12 col-md-6 contact-2"> <hr> <h2 class="logo-font mb-4 text-center ">Contact Information</h2> <h5 class="text-muted text-center">Open 9am-5pm all week!</h5> <hr> </div> <div class="w-100 d-none d-md-block"></div> <div class="col-12 col-md-6 contact-3"> <form method="POST" href="#" class="form mb-2" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} {{ field | as_crispy_field }} {% endfor %} <button class="btn btn-black rounded-0" type="submit">Submit <i class="fab fa-telegram-plane pl-2"></i></button> </form> </div> <div class="col-12 col-md-6 text-center contact-4"> <h5>Email: info@drumloot.com</h5> <h5>Phone: 045 948 4590</h5> <h5>Address: 105 Tilted Towers, California, USA</h5> <div id="map"> <iframe class="googlemap-responsive" src="https://www.google.com/maps/embed?pb=!1m17!1m12!1m3!1d3152.1982920890246!2d-122.28525490832737!3d37.80882413795131!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m2!1m1!2zMzfCsDQ4JzMxLjgiTiAxMjLCsDE2JzQ5LjQiVw!5e0!3m2!1sen!2sie!4v1702042781451!5m2!1sen!2sie" width="600" height="450" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe> </div> </div> </div> </div> -
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x13f305e90> give this error in django and image path retrive from s3 is
When I open Image url given by django it gives this. This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>SignatureDoesNotMatch</Code> <Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message> <AWSAccessKeyId>AKIAR4APO3UQB6EPRHZK</AWSAccessKeyId> <StringToSign>AWS4-HMAC-SHA256 20231208T141342Z 20231208/eu-north-1/s3/aws4_request 7c1cadaceeabd5fd2551d7de369db9c9b1fdd0741e5077490b8b3f8599a157b4</StringToSign> <SignatureProvided>b9a5a710e118bb6fb3f7d442191a8a5be293fa8a3838465e466063c4b9214635</SignatureProvided> <StringToSignBytes>41 57 53 34 2d 48 4d 41 43 2d 53 48 41 32 35 36 0a 32 30 32 33 31 32 30 38 54 31 34 31 33 34 32 5a 0a 32 30 32 33 31 32 30 38 2f 65 75 2d 6e 6f 72 74 68 2d 31 2f 73 33 2f 61 77 73 34 5f 72 65 71 75 65 73 74 0a 37 63 31 63 61 64 61 63 65 65 61 62 64 35 66 64 32 35 35 31 64 37 64 65 33 36 39 64 62 39 63 39 62 31 66 64 64 30 37 34 31 65 35 30 37 37 34 39 30 62 38 62 33 66 38 35 39 39 61 31 35 37 62 34</StringToSignBytes> <CanonicalRequest>GET /media/images/pexels-jonas-f-13020734.jpg X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAR4APO3UQB6EPRHZK%2F20231208%2Feu-north-1%2Fs3%2Faws4_request&X-Amz-Date=20231208T141342Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host host:captiongenerator.s3.eu-north-1.amazonaws.com host UNSIGNED-PAYLOAD</CanonicalRequest> <CanonicalRequestBytes>47 45 54 … -
hosting django rest dependencies dependencies of Celery, Celery Beat, Redis, and Django Channels using Daphne
I'm currently facing challenges while deploying my Django REST project on AWS EC2. The project has dependencies on Celery, Celery Beat, Redis, and Django Channels using Daphne. If anyone has experience with this pls help me -
Can't connect Conda Psycopg in Django, only system-level python works
I have wanted to switch from using the system-level python packages (arch-linux) to mamba/conda virtual env. Note that postgresql.service is running fine system level. I have installed all the same packages in the virtual environment. It works perfect on main system python but fails in conda. I even set env-variables in zsh shell for postgresql and done chmod 0600 ~/.my_pgpass DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "OPTIONS": { "service": "my_service", // location - /home/zane/.pg_service.conf "passfile": ".my_pgpass", //location is project root "server_side_binding": True, }, } } Without conda virtual env:(works fine) python manage.py migrate Operations to perform: Apply all migrations: admin, auth, business, contenttypes, sessions Running migrations: No migrations to apply. **(All runs fine without virtual enviroment)** with conda virtual env- mamba activate django (django) Django-CRUD main ❯ python manage.py migrate Traceback (most recent call last): django.db.utils.OperationalError: connection is bad: No such file or directory Is the server running locally and accepting connections on that socket? I have also inserted zsh shell variables export PGPASSFILE="/home/zane/projects/Django-CRUD/.my_pgpass" export PGSYSCONFDIR=/home/zane/ export PGSERVICEFILE=/home/zane/.pg_service.conf Please help as none of the above worked -
while routing to "/room/id" page, it is redirecting to two room routes like "/room/room/id", when I should have one room
my home page i.e "/" is listing all the room names with links, which should redirect to that particular room with that name. For example clicking on "Test Room1" should redirect me to "/room/1" with that name. But it is redirecting me to "/room/room/1" and however giving me the room name with id 1. views.py rooms = [ {'id':1, 'name':'Test Room1'}, {'id':2, 'name':'Test Room2'}, {'id':3, 'name':'Test Room3'} ] def home(request) : context = {'rooms':rooms} return render(request, 'base/home.html', context) def room(request, pk) : room = None for i in rooms : if i['id'] == int(pk) : room = i context = {'room':room} return render(request, 'base/room.html', context) urls.py urlpatterns = [ path('', views.home, name='home'), path('room/<str:pk>/', views.room, name='room') ] html template {% for room in rooms %} <div> <h3>{{room.id}} : <a href="{% url 'room' room.id %}">{{room.name}}</a></h3> </div> {% endfor %} -
how to make an imag eand image content responsive in mobile device.now my image width is responsive ,but its height
I am doing a Django website. I am using bootstrap v5.3.2. In my home page there is the main image inside the image welcome to the company and in the next line another text and in next line 3 square shaped cards are placed horizontally .but these portion are not responsive in mobile device. The image width is responsive but the length is not ,the cards are overlaying the image text in mobile screen size, I want the 3 cards are inside the image just after the text in the image on mobile screen device. How to make that I want the 3 cards are inside the image just after the text in the image on mobile screen device. How to make that -
css/js is not working after hosting in aws ec2
settings.py is shown below: '''import os from pathlib import Path from dotenv import load_dotenv Build paths inside the project like this: BASE_DIR/ 'subdir'. BASE_DIR = Path(file).resolve().parent.parent load_dotenv() Quick-start development settings - unsuitable for production See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv("SECRET_KEY") SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['not showing'] ......... Static files (CSS, JavaScript, Images) https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = 'static/' STATIC_ROOT = [os.path.join(BASE_DIR, 'static')] Default primary key field type https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' ''' this is setting.py, I don't understand where it is going wrong. I did collectstatic,load static, and also html pages have bootstrap cdns and still CSS /bootstrap is not working. Can somebody help me, I am hosting (aws ec2) for the first time, having trouble. This is the error shown after entering "python manage.py collectstatic" or "python manage.py collectstatic --no-input" in cmd -"TypeError: expected str, bytes or os.PathLike object, not list". -
Show Name instead on Phone Number on Whatsapp
I have successfully integrated Twilio with WhatsApp using Python code, and our system is effectively sending SMS messages to WhatsApp. However, we are currently facing an issue where we want customers to see our company name instead of the WhatsApp application number when receiving messages. Despite searching through the Twilio documentation, I have not found information on how to replace the WhatsApp number with our company name. I need assistance in understanding and implementing the necessary steps to achieve this within the Twilio integration. Tried Twillio documenataion -
Is it possible to extend Django's User model just adding objects to its model form?
I am trying to create users with django's User Model but I want to add to it some extra boolean fields and choice fields. isn't there any way to do it without binding it with one to one field to another model? I tried adding objects straight to User model and when i rendered the form i could see the fields I added but when it comes to admin pannel, I can't see these fields. -
Should I list the contestants according to the selected division?
I'm new to web development and I use the Django framework! I ask you to help or guide me on the right path. It is necessary to implement a selection of contestants according to the division selected from the drop-down list. The contestant model has a secondary key to the division model, the template implements the output of two forms: class divisionForm(ModelForm): # Подразделения class Meta: model = division fields = ['name_division'] widgets = { "name_division": Select(attrs={}), } class contestantForm(ModelForm): # Конкурсанты class Meta: model = contestant fields = ['name_contestant'] widgets = { "name_contestant": Select(attrs={}), } enter image description here As far as I understand, Django acts as a server and when the page loads, it returns the data processed in views.py how to implement the withdrawal of all contestants from the selected division in the template? already on the client side without POST and GET requests. Do you have a javascript example for interacting with Django on a similar topic? -
Concatenate 2 RawQuerySets Django
so i have each entity their and they are from legacy system, thats why i cannot perform migration. For example : Entity1 Blog Entity1 Entry Entity2 Blog Entity2 Entry There are 9 entities, means 18 tables So here is my view.py but i cannot do entity1_data.union(entity2_data). How can i merge these, so i can present it in 1 table? Ps: i would try union SQL, but theres too long. entity1_data = BlogModel.objects.using("bcdb").raw("SELECT blog.id as id, blog.name," + "entry.title, " + "entry.date " + "FROM [Entity1 Blog] as blog " + "INNER JOIN [Entity1 Entry] as entry " + "on blog.id = entry.blog_id") entity2_data = BlogModel.objects.using("bcdb").raw("SELECT blog.id as id, blog.name," + "entry.title, " + "entry.date " + "FROM [Entity2 Blog] as blog " + "INNER JOIN [Entity2 Entry] as entry " + "on blog.id = entry.blog_id") I hope i can do it dynamically using dict of tables name. Merged table | Blog ID | Blog Name | Entry Title | Entry Date | | ------------------ | -------------------- | ---------------------- | --------------------- | | [Entity 1 Blog].ID | [Entity 1 Blog].name | [Entity 1 Entry].title | [Entity 1 Entry].date | | [Entity 2 Blog].ID | [Entity 2 Blog].name | [Entity 2 Entry].title …