Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to take images from Media folder from another domain?
I have 2 domains: naiuma.com and jp.naiuma.com. I have uploaded all images to Media Folder on naiuma.com and now I want to access them on jp.naiuma.com. In my models I have something like: thumbnail = models.ImageField(upload_to ='uploads/posts/') And in the settings I have: BASE_DIR = Path(__file__).resolve().parent.parent MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') But of course it doesn't work since it is constructed to be used in the frames of one single domain. Please let me know, what should I do to connect thumbnail = models.ImageField with the old, main naiuma.com domain and it's hosting? Thanks. -
Django; add integer primary_key in production
We have a running instance of a Django Backend. On a few model we used an CharField as an Primary Key because it was the best solution for the old requirements. Now we need to add a basic int id like id = models.AutoField(primary_key=True) and let the old charfield remain as primary_key=False. I removed the primary_key=True Flag from the old primary key attribute and triggerd ./manage.py makemigrations. If I dont declare any primary key Django is generating its normal id like mentioned above. But after trigger, Djang asks for default values for old entries of this model like: It is impossible to add a non-nullable field 'id' to anrede without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit and manually define a default value in models.py. Becaus its an unique Field, I cant use any static content. So how can I still make migrations without delete old migrations? -
In Django i'm having trouble calling a form. I see the button but not the textboxes
In the index.html page (home page) I am trying to display a form and i call the form like this: {% include 'registration/register.html' %} I would like to view the form directly on index.html (127.0.0.1:8000) and not on http://127.0.0.1:8000/register, but the problem is that in index.html, i see the button but not the textboxes (username, email, password): I don't know what I'm doing wrong This is App1: App1 .migrations .static .templates ..index.html ..registration ...register.html index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>University</title> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="https://getbootstrap.com/docs/5.3/assets/css/docs.css" rel="stylesheet"> <link href="/static/css/style.css" rel="stylesheet"> </head> <body> ....... ....... {% include 'registration/register.html' %} </body> </html> App1/templates/registration/register.html {% block content %} <!--Register--> <div class="container py-5"> <h1>Register</h1> <form method="POST"> {% csrf_token %} {{ register_form.as_p }} <button class="btn btn-primary" type="submit">Register</button> </form> <p class="text-center">If you already have an account, <a href="/login">login</a> instead.</p> </div> {% endblock %} App1/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User # Create your forms here. class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: … -
annotation with a table referred to by content_type + object_id in DjangoORM
So issue is I need to filter by title field that in many others tables. class Model uses contenttypes framework in django. It refers to several tables that have a title field (field I want to filter by) class Model(models.Model): content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, limit_choices_to={'model__in': ('model1', 'model2', 'model3', 'model4', 'model5')}, ) object_id = models.CharField(max_length=36) content_object = GenericForeignKey('content_type', 'object_id') Every table that has the title field has GenericRelation(Model, related_query_name='elements') class model1(models.Model): # and etc for model2, model3... title = models.CharField(max_length=255) myfield = GenericRelation(Model, related_name_query='elements') First I Tried Model.objects.annotate(title=F('elements__title')). But for some reasons it does not work for me because it joins only one table. It makes sence because anyway I need to handle these strings with Coalesce. So I figured it out by create my own SQL query but I cannot convert it to DjangoORM here is the query SELECT "mm"."id", COALESCE("model1"."title", "model2"."title", "model3"."title", "model4"."title", "model5"."title") AS "title" FROM "Model" AS "mm" LEFT OUTER JOIN "model1" AS "model1" ON ("mm"."object_id" = "model1"."id") LEFT OUTER JOIN "model2" AS "model2" ON ("mm"."object_id" = "model2"."id") LEFT OUTER JOIN "model3" AS "model3" ON ("mm"."object_id" = "model3"."id") LEFT OUTER JOIN "model4" AS "model4" ON ("mm"."object_id" = "model4"."id") LEFT OUTER JOIN "model5" AS "model5" ON ("mm"."object_id" … -
self.serializer = import_string(settings.SESSION_SERIALIZER)
I apologize for the bad English. I bought a new computer, moved my files, installed all my libraries, and wanted to get my work back on its feet. But I encountered an unexpected error, the problem is exactly as follows The error I received is like this. I did research on how to solve the problem, but I could not find a solution. I am grateful in advance to those who will solve this problem of mine. Good work. -
How to get uploaded file's path?
When I upload file through admin dashboard in Django dev server, I always get error that file doesnt exist. With that it is pointing in local folder and searching for <file_name> I want to upload it to supabase but Django isn't finding the file which i Choose in /admin This is my code: class PupinObject(models.Model): video = forms.FileField(upload_to='videos/') creation_date = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(PupinUser, on_delete=models.CASCADE) def save(self, *args, **kwargs): url = os.environ.get("SUPABASE_URL") key = os.environ.get("SUPABASE_KEY") supabase = create_client(url, key) bucket_name = "videos" new_file = self.video.path print(default_storage.path(self.video.name)) jwt = supabase.auth.sign_in_with_password({ "email": self.user.email, "password": self.user.password }) # Upload the file to the user's directory supabase.storage.from_(bucket_name).upload(f"/{jwt.user.id}/video.mp4", new_file) super().save(*args, **kwargs) I tried getting absolute path but no light. -
ExpoAV Video, video I get from Django server is not loading
I am working on an Expo app and I use the component from expo-av. When I source the video from my assets, it works. But when I try to display a video which is stored on my Django server, it is not loading. here is my code <Video style={{width: window.width * .93, height: window.width * .93 * 1.05,}} source={{uri: server + "media/" + media.uri}} shouldPlay usePoster /> When I do the url on http request, I get the video I want. But it is not working on the expo app. How can I fix this? -
Why do I have Broken links on my ecommerce project website dropdown menu?
I have a simple dropdown in my main navigation of my website buiot with django and python. The links are dead, although I can see the categories i the browser URL extension. I have looked at the code and I cant seem to find where to fix the issue. I have categories created in my django admin for my products and the correct category names oin the dropdown. I have manually added approximately 20 products through heroku front end deployed site and they have been added successfully, and also show in the correct category on their respective product page too. The main issue is the dropdown nav which gives 0 results when selected by category <div class="dropdown-menu border-0" aria-labelledby="soup-link"> <a href="{% url 'products' %}?category=soup" class="dropdown-item">Soups</a> <a href="{% url 'products' %}?category=stews" class="dropdown-item">Stews</a> <a href="{% url 'products' %}?category=broth" class="dropdown-item">Broth</a> <a href="{% url 'products' %}?category=hotpot" class="dropdown-item">Hotpot</a> </div> this shows my code which I have created in main-nav.html I think it is a URL routing issue -
Django with Docker is not allowing to access external API and is throwing Failed to resolve 'my-host-name' ([Errno -5] No address associated
I am new to django and Docker. The issue I am facing is when I want to fetch some data from external API and just display it in a view I am getting an error "Failed to resolve 'my-host-name' ([Errno -5] No address associated with hostname". But the API is working fine in postman and I tested it Here is my view file: import json from django.http import HttpResponse from django.shortcuts import render import requests def index(request): host='http://my_host:8190' token='My_Auth_Token' hd = {'Authorization': str({token})} data=requests.get(f"{host}/api/xyz" ,headers=hd) return render(request,"Loading/index.html",{'bundles':data}) In the html file I am just displaying the data. Please help me out with this. Thanks in advance :) I am trying to access an API endpoint for which I am getting Failed to resolve 'srd-web-apps-dev' ([Errno -5] No address associated with hostname when I use djangyour texto with docker. But If I use django without Docker it doesn't throw any error. -
My docker-compose can not run or build, causing issues
I am creating a django application and I am creating docker container for that application. I am using mySQL database. So after creating my entire project when I was succesfully running, I createrd Dockerfile and docker-compose.yml file. Here is the content of my file. Dockerfile ENV DockerHOME=/home/app/webapp RUN mkdir -p $DockerHOME WORKDIR $DockerHOME ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip COPY . $DockerHOME RUN pip install -r requirements.txt # Add Django migrations and apply them RUN python manage.py makemigrations RUN python manage.py migrate EXPOSE 8080 CMD ["python", "manage.py", "runserver", "0.0.0.0:8080"] and here is my docker-compose.yml version: '3' services: web: image: blogs:latest container_name: blogs_web ports: - "8080:8080" volumes: - .:/home/app/webapp environment: - PYTHONDONTWRITEBYTECODE=1 - PYTHONUNBUFFERED=1 - SECRET_KEY=${SECRET_KEY} - DEBUG=${DEBUG} - DATABASE_NAME=${DATABASE_NAME} - DATABASE_USER=${DATABASE_USER} - DATABASE_PASSWORD=${DATABASE_PASSWORD} - DATABASE_HOST=${DATABASE_HOST} - DATABASE_PORT=${DATABASE_PORT} depends_on: - db db: image: data:latest container_name: blogs_db environment: MYSQL_DATABASE: ${DATABASE_NAME} MYSQL_USER: ${DATABASE_USER} MYSQL_PASSWORD: ${DATABASE_PASSWORD} MYSQL_ROOT_PASSWORD: ${DATABASE_ROOT_PASSWORD} ports: - "3306:3306" command: --default-authentication-plugin=mysql_native_password When I run docker-compose build it gives me this response [+] Building 0.0s (0/0)``` The build isn't right. and when I do ```docker-compose up``` here is my error [+] Running 2/2 ✘ web Error 3.8s ✘ db Error 3.8s Error response from daemon: pull access denied … -
How to annotate field for the right sorting
I annotate queryset in Django like this: q_set = q_set.annotate( period=Concat( ExtractYear(date_field), Value(' - '), ExtractMonth(date_field), output_field=CharField() ), ) But then I get this result: 2022 - 12 2023 - 1 2023 - 10 2023 - 11 2023 - 12 2023 - 2 2023 - 3 2023 - 4 2023 - 5 2023 - 6 2023 - 7 2023 - 8 2023 - 9 But I need to sort it in a right order... -
Django-Allauth MultipleObjectsReturned
I use django-sites model to seperate localhost:8000 and productive_server.de for test purpose. Django-Allauth with login from e.g. Github throws an exception "MultipleObjectsReturned" even though provider github is in the database with either "localhost:8000" or "productive_server.de" as SITE_ID. There is no additional list of providers in settings.py I have traced down the problem to env/Lib/site-packages/allauth/socialaccount/adapter.py -> DefaultSocialAccountAdapter(object) -> list_apps(self, request, provider=None, client_id=None) def list_apps(self, request, provider=None, client_id=None): """SocialApp's can be setup in the database, or, via `settings.SOCIALACCOUNT_PROVIDERS`. This methods returns a uniform list of all known apps matching the specified criteria, and blends both (db/settings) sources of data. """ # NOTE: Avoid loading models at top due to registry boot... from allauth.socialaccount.models import SocialApp # Map provider to the list of apps. provider_to_apps = {} # First, populate it with the DB backed apps. if request: db_apps = SocialApp.objects.on_site(request) # <-------- filter according "site_id" only if request is given else: db_apps = SocialApp.objects.all() in the error trace it turns out that on the way the "request" parameter is not handed over -> so no filter according "site_id" and a thus 2 providers are returned -> exception: Traceback (most recent call last): File "...\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File … -
django-waffle does not show proper flag status on waffle_status endpoint
I have created this flag: I'm trying to get the flag status using the waffle_status endpoint, but no matter if the user is logged or not I get the same response: { "flags": { "test_flag": { "is_active": false, "last_modified": "2023-12-21T16:03:38.922Z" } }, "switches": {}, "samples": {} } It is supposed that I have to get this flag as True for the user farid, the one with id 1, isn't? I made this exercise using django 4, django-waffle 4.1.0, and I have made this configs on settings.py . . . INSTALLED_APPS = [ 'django.contrib.admin', 'rest_framework', 'rest_framework.authtoken', 'django.contrib.auth', 'waffle', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'exammple' ] . . . MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'waffle.middleware.WaffleMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] . . . REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } . . . and in project's url.py file urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/v1/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path( 'api/v1/', include( [ path('', include(example_urls)) ] ) ), path('waffle/', include('waffle.urls')), ] Is this a bug/missing feature on waffle? or I'm missing some config in somewhere? P.S. The purpose of this is that I have to give this flag status to a FrontEnd app to show or hide some visual components depending … -
Django - Filter by Foreign Key
I have 2 models class Project(models.Model): name = models.TextField(max_length=150) class Asset(models.Model): name = models.TextField(max_length=150) project = models.ForeignKey('Project', related_name='ass') I can use this command to get a Project with all its Assets, it's cool. proj = Project.objects.get(pk='QQ') But I just want to get a Project with a specific Asset, this is my command: proj = Project.objects.get(pk='QQ', ass__pk=50) But it still returns all Assets. Then I turn on the SQL debug mode and find Django runs 2 SQLs. It executes 'SELECT project.* FROM project INNER JOIN asset ON ... WHERE project.pk='QQ' AND asset.pk=50 It executes 'SELECT asset.* FROM asset WHERE asset.project = 'QQ' I think the 1st SQL is enough, I have no idea why 2nd SQL is executed. I use Django 4.2 with Python 3.8.10, can anybody help it? -
Django not responding when i change DataBase to PostgreSQL
i changed the Django database to postgresql and when i command runserver or migrate or makemigrations, django wont response. also no error occurs im using Django 5 and PostgreSQL 10 i tried restarting the postgres server and making new projects but still stays that way -
Django Rest Framework Token Auth > Remove user foreign Key from POSTs while keeping it for GETs
I'm struggling to make this work. I have the following model: class Message(models.Model): text = models.CharField(max_length=500) date = models.DateTimeField("date published") user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) def __str__(self): return self.text Here is my serializer: class MessageSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer() class Meta: model = Message fields = ['id', 'text', 'date', 'user', 'room'] I've changed the serializer to have the user "expanded" when I retrieve my Message list with a GET request. So what I hoping to achieve - with my token authentication - is to avoid passing the user in my POST request. As I pass the token for authentication, there should be a way to retrieve the user with it. Here are my ViewSets: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class MessageViewSet(viewsets.ModelViewSet): serializer_class = MessageSerializer def get_queryset(self): authentication_classes = [] room_id = self.request.query_params.get('room_id') return Message.objects.filter(room=room_id) My settings: REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', ] } How can I do this? Thanks! -
Python - Django Beginner - Form to submit data to my database - Cannot find answer
I am quite new to Python - Django and I have only spent my spare time learning. I have successfully created a user registration form that posts data to my postgresql database: My code looks like this: Views: def signupr(request): if request.method == 'POST': username = request.POST\['username'\] email = request.POST\['email'\] password = request.POST\['password'\] password2 = request.POST\['password2'\] if password == password2: if User.objects.filter(email=email).exists(): messages.info(request, 'Email Already Exists') return redirect('registration') elif User.objects.filter(username=username).exists(): messages.info(request, 'Username Already Exists') return redirect('registration') else: user = User.objects.create_user(username=username, email=email, password=password) user.save(); return redirect('dashboard') else: messages.info(request, 'Passwords Do Not Match') return redirect('registration') else: return render(request, 'registration_form.html') (very basic but it works) I have a form that successfully creates users to a database. Note that Django understands "User.objects.create_user" and creates a new user row for me. The problem comes in when I try to use the same logic to create a property listing for example I have a basic version of my model called "Properties" : ` class Properties(models.Model): title = models.CharField(max_length=100, default='Not Set') feat_image = models.ImageField(upload_to='images', default='/images/scrolltop.png') gallery_images = models.ImageField(upload_to='images', default=False) external_property_listing_url = models.CharField(max_length=255) property_rules = models.CharField(max_length=500) ` Now when I try to create this in my views: def addpropertylisting(request): if request.method == 'POST': title = request.POST['title'] property = … -
Svelte menu with Django rest framework
The menu I made in django works correctly in html. But I want to implement the same code in svelte using django rest. How should I do this using django rest? Of course, I prepared django rest, I just want it to work properly in svelte. This is my code: HTML DJANGO {% load static %} <nav class="menu__main menu__vtl"> <ul class="menu"> {% for html_category in html_categories %} {% if not html_category.parent %} <li class="dropdown"> <a href="javascript:void(0);" class="dropdown__link{% if request.path == html_category.get_absolute_url %} active{% endif %}"> {% if html_category.select_svg.title_svg %} <svg class="dropdown__image"><use href="#{{ html_category.select_svg.title_svg }}"></use></svg> {% endif %} <span class="dropdown__text">{{ html_category.title }}</span> <svg class="dropdown__arrow"><use href="#arrow-down"></use></svg> </a> {% if html_category.subs.all %} <ul class="dropdown__list"> {% for html_category in html_category.subs.all %} {% if html_category.subs.all %} <li class="sub"> <a href="javascript:void(0);" class="sub__link"> <svg class="sub__arrow"><use href="#arrow-add"></use></svg> <span class="sub__text">{{ html_category.title }}</span> </a> <ul class="sub__list"> {% for child in html_category.subs.all %} <li class="sub__list__item"> <a href="{{ child.get_absolute_url }}" class="sub__list__link{% if request.path == child.get_absolute_url %} active{% endif %}"> <span class="sub__list__text">{{ child.title }}</span> </a> </li> {% endfor %} </ul> </li> {% else %} <li class="dropdown__list__item"> <a href="{{ html_category.get_absolute_url }}" class="dropdown__list__link{% if request.path == html_category.get_absolute_url %} active{% endif %}"> {% if html_category.select_svg.title_svg %} <svg class="dropdown__image"><use href="#{{ html_category.select_svg.title_svg }}"></use></svg> {% endif %} <span class="dropdown__list__text">{{ … -
How to filter the choice list in Django Forms?
I have 2 models: class Employee(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) lastname = models.CharField(max_length=50) end_user_id = models.CharField(max_length=8, help_text=u"Please enter the end user id, like ABC1WZ1") email = models.EmailField(max_length = 254, help_text=u'with domain ...@boschrexroth.pl', blank=True) history = HistoricalRecords() def __str__(self): return self.name + ' ' + self.lastname def save(self, *args, **kwargs): self.end_user_id = self.end_user_id.upper() super().save(*args, **kwargs) and class BDO_Procedor(models.Model): id = models.AutoField(primary_key=True) bdo_procedor = models.ForeignKey(Employee, verbose_name='bdo_procedor', on_delete = models.DO_NOTHING) def __str__(self): return self.bdo_procedor.name + ' ' + self.bdo_procedor.lastname class BDO_ProcedorAdmin(SimpleHistoryAdmin): list_display = ('id', 'bdo_procedor') list_filter = ('bdo_procedor',) search_fields = ['bdo_procedor'] At the view.py I have an assign function which assign some form to the user which also exists at the BDO_Procedor def form_assign_bdo(request, pk): current_form = get_form(pk) if request.method == 'POST': form = AssignForm(request.POST, instance=current_form) form.fields["assigned_to"].queryset = Employee.objects.filter(end_user_id__in=BDO_Procedor.objects.values_list('bdo_procedor__end_user_id', flat=True)) if form.is_valid(): form.save(commit=True) return redirect('material_request', pk=pk) else: form = AssignForm(request.POST, instance=current_form) return render(request, 'app/forms/form_assign.html', {'form':form}) Everything working but I want to filter this list also in form, so: class AssignForm(ModelForm): def __init__(self, request, *args, **kwargs): super(AssignForm, self).__init__(*args, **kwargs) self.fields["assigned_to"].queryset = Employee.objects.filter(end_user_id__in=BDO_Procedor.objects.values_list('bdo_procedor__end_user_id', flat=True)) class Meta: model = MissFormModel fields = ( 'assigned_to', ) Everything is looking good, but when I've cliked Submit nothing is going on. What I am dooing … -
How can I do mocked reverse_lazy from django.urls?
# views.py from django.contrib.auth import get_user_model from django.urls import reverse_lazy from django.views import generic from accounts import forms User = get_user_model() class UserRegisterView(generic.FormView): model = User template_name = 'accounts/register_form.html' form_class = forms.UserRegisterForm success_url = reverse_lazy('accounts:user-register-first-success') def form_valid(self, form): form.save() return super().form_valid(form) # test_views.py from unittest.mock import patch from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse User = get_user_model() class UserRegisterViewTest(TestCase): def setUp(self) -> None: self.url = reverse('accounts:user-register') self.data = { 'email': 'rick.sanchez@test.com', 'password': 'qwe123!@#', 'confirmed_password': 'qwe123!@#', } @patch('accounts.views.reverse_lazy', return_value='mock_url') def test_view_redirects_to_correct_page_POST(self, mock): response = self.client.post(self.url, self.data) self.assertRedirects(response, 'mock_url') @patch('django.urls.reverse_lazy', return_value='mock_url') def test_view_redirects_to_correct_page_POST_(self, mock): response = self.client.post(self.url, self.data) self.assertRedirects(response, 'mock_url') File "/home/branya/Документи/My Projects/Django/hotel/venv/lib/python3.10/site-packages/django/urls/resolvers.py", line 848, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'user-register-first-success' not found. 'user-register-first-success' is not a valid view function or pattern name. I don't understand why mock isn't work on reverse_lazy. I need it work without the made view with the url by name "user-register-first-success". Help me to find a solution. I used @patch('accounts.views.reverse_lazy', return_value='mock_url') and @patch('django.urls.reverse_lazy', return_value='mock_url'). I try to find a solution with chatGPT, but its answers raised that error. -
Django Razorpay integration working on test server but This payment has already been captured error in live session
I'm first time to use razorpay live mode, transaction is sucessful but get error Payment has already been captured.The payment collection works fine but when it comes to verifying the payment it seems to break on the live server. The order amount and details sent to razorpay seem to be working fine but response capture is maybe breaking. Below is my copy of views.py def process_booking_payment(self, request, *args, **kwargs): if request.method == "POST": params = request.POST razorpay_order_id = params.get('razorpay_order_id') razorpay_payment_id = params.get('razorpay_payment_id') razor_signature = params.get('razorpay_signature') MD = MasterData.objects.get() RAZORPAY_CLIENT = razorpay.Client(auth=(MD.razorpay_key, MD.razorpay_secret)) RAZORPAY_CLIENT.set_app_details({"title": MD.company_name, "version": "1.0"}) params_dict={ 'razorpay_order_id': razorpay_order_id, 'razorpay_payment_id': razorpay_payment_id, 'razorpay_signature': razor_signature } bookin = get_object_or_404(Booking,payment_id = kwargs.get('payment_id'), razorpay_order_id=razorpay_order_id) bookin.razorpay_payment_id = razorpay_payment_id bookin.razorpay_signature = razor_signature bookin.save() RAZORPAY_CLIENT.utility.verify_payment_signature(params_dict) try: with transaction.atomic(): rp_capture = RAZORPAY_CLIENT.payment.capture( razorpay_payment_id,float(bookin.booked_amount * 100) ) bookin.payment_status = '1' confirm = create_booking(request,payment_id = bookin.payment_id) if 'errorDetails' in confirm: bookin.booking_status = '6' else: bookin.booking_status = '2' bookin.booking_details.is_confirmed = True bookin.booking_details.save() bookin.save() messages.success(request, 'Payment Successful') log = LOG.objects.create( user = request.user, function = 'payment', response = 'payment success' ) log.save() return JsonResponse({ 'success': True, 'redirect_to': reverse('my-booking',args=[request.user.slug]) }) except Exception as e: bookin.booking_status = '6' bookin.payment_status = '2' bookin.save() print(e) log = LOG.objects.create( user = request.user, function = 'payment', response = … -
django.template.library.InvalidTemplateLibrary
im tried to install django-jalali-date module on Django5.0 . But I encountered the following error: django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'jalali_date.templatetags.jalali_tags': No module named 'distutils' i am tried install this module for convert Gregorian calendar to solar calendar. I installed it with pip install django-jalali-date and put it in the installed apps -
Please explain me this. I cant understand it
A common gotcha to be aware of is that the field type dictates how to use these values. Whenever you have a string-based field like CharField or TextField, setting both null and blank as we’ve done will result in two possible values for “no data” in the database. Which is a bad idea. The Django convention is instead to use the empty string "", not NULL I cant understand what will go wrong for charfiel and textfield? -
upload image and encode face with opencv and face_recognition
I want to take the photo file selected in the form using opencv and encode the face using face_recognition in Django before my information is saved in the database. But I can't get the photo file from cleaned data. please Help me my views.py from django.shortcuts import render, redirect from django.views import View from .models import ImageEncode from .forms import CreateEncodeImage from django.contrib import messages import cv2, os import face_recognition from django.conf import settings class AddCustomFaceView(View): form_class = CreateEncodeImage path = os.path.join(settings.BASE_DIR, 'face_lib/') def get(self, request, *args, **kwargs): form = self.form_class return render(request, 'home/custom-face.html', {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) if form.is_valid(): new_face = form.save(commit=False) img_name = form.cleaned_data['imgname'] img_add = form.cleaned_data['imgaddress'] img_face = cv2.imread(f'{img_add}') img_face = cv2.cvtColor(img_face, cv2.COLOR_RGB2BGR) face_loc = face_recognition.face_locations(img_face) y1, x2, y2, x1 = face_loc y1, x2, y2, x1 = y1, x2, y2, x1 image_frame = img_face[y1:y2, x1:x2] encode = face_recognition.face_encodings(img_face) if encode: new_face.imgencode = encode[0] new_face.imgname = img_name new_face.imgaddress = form.cleaned_data('imgaddress') new_face.save() cv2.imwrite(self.path + img_name, image_frame) messages.success(request, 'New Custom Face Saved', 'success') else: messages.warning(request, 'could not save this face', 'success') return redirect('home:face_custom') return redirect('home:list_img') else: messages.warning(request, 'not valid data', 'warning') return redirect('home:face_custom') my forms.py from django import forms from .models import ImageEncode … -
django.core.exceptions.AppRegistryNotReady and import models
My django project structure is like below. watcher |-config |-__init__.py |- asgi.py |- config.ini |- settings.py |- urls.py |- wsgi.py |-tower |-__init__.py |-admin.py |-apps.py |-models.py |-tests.py |-views.py |-manage.py My apps.py code is like below. # import os # os.environ.setdefault("DJANGO_SETTINGS_MODULE", "watcher.settings") # import django # django.setup() from .models import CryptoTicker, CryptoTrade, CryptoOrderbookMain, CryptoOrderbookSub class TowerConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'tower' def ready(self): print("Hello") socket = SocketClient() socket.start() class SocketClient(threading.Thread): def __init__(self): super().__init__() self.url = "wss://api.upbit.com/websocket/v1" self.ws = websocket.WebSocketApp( url=self.url, header=headers, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, on_open=self.on_open ) self.step = 0 def run(self): while True: self.ws.run_forever() def on_message(self, ws, message): data = message.decode('utf-8') self.process(data) if self.step < 0: print("----- ----- ----- ----- ----- ----- -----") print() print(data) print() print("----- ----- ----- ----- ----- ----- -----") self.step += 1 def on_error(self, ws, err): print(err) def on_close(self, ws, status_code, msg): print("closed!") def on_open(self, ws): print("connected!") ws.send('[{"ticket":"siren1"}, {"type":"ticker","codes":["KRW-BTC", "KRW-SOL"]}, {"type":"trade","codes":["KRW-BTC", "KRW-SOL"]}, {"type":"orderbook","codes":["KRW-BTC", "KRW-SOL"]}, {"format": "DEFAULT"}]') def process(self, data): pass After running 'python manage.py runserver --noreload 0.0.0.0:8000', I got below errors. File "D:\git\crypto-siren\venv\Lib\site-packages\django\apps\registry.py", line 138, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. My suspicion is that importing models make errors. (from .models import CryptoTicker, CryptoTrade, CryptoOrderbookMain, CryptoOrderbookSub) Could you give me some …