Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
drf-spectacular hide Schemas from components in Swagger UI
In my Swagger UI, I'm trying to hide the Schemas section from components: I'm using drf-spectacular and I didn't find anything relating to Schemas in the Swagger Configuration. I tried removing schemas from the JSON response: from drf_spectacular.views import SpectacularJSONAPIView class CustomJSONAPIView(SpectacularJSONAPIView): def get(self, request, *args, **kwargs): response = super().get(request, *args, **kwargs) del response.data["components"]["schemas"] return response Which works, but corrupts rest of the Swagger functionality. Is it possible to simply hide this Schemas component without breaking rest of Swagger? -
Static files are not accessible on my website
I just deployed a website on a VPS but the static files are not being loaded. This is my settings.py file: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['founderslooking.com'] CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:8080", "http://localhost:file", ] CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_SAMESITE = None SESSION_COOKIE_SECURE = False CSRF_TRUSTED_ORIGINS = ["founderslooking.com"] INTERNAL_IPS = [ "127.0.0.1", ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = "static/" STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),) STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles/") MEDIA_ROOT = os.path.join(BASE_DIR, "storage").replace("\\", "/") MEDIA_URL = "/storage/" # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" CACHES = { "default": { "BACKEND": "django.core.cache.backends.memcached.PyMemcacheCache", "LOCATION": "127.0.0.1:11211", } } What, if anything, is wrong here? How should I change the values for the production server? -
API Stripe. Why I have ERROR 400 to confirm payment?
the site API STRIPE tells me there is an error in LOGS: For what exact reason do I get a 400 error when entering the test card numbers and clicking the "Confirm" button? This message contains all the details of my error. I have attached the code in which the payment is made. Processing tokens, etc. POST /v1/charges Status 400 ERR ID req_GKbBUprcIuSQ0X Time 5/25/24, 1:09:58 PM IP address 151.249.163.206 API version 2024-04-10 Source Stripe/v1 PythonBindings/2.37.2 Idempotency Key — badc22f3-4989-46e8-aec6-35347aa48d10 resource_missing - source No such token: 'tok_1PKHY1IRI3YGNQKDocTdMkPu' Was this useful? Yes No { "source": "tok_1PKHY1IRI3YGNQKDocTdMkPu", "amount": "4400", "currency": "usd" } Response body { "error": { "code": "resource_missing", "doc_url": "https://stripe.com/docs/error-codes/resource-missing", "message": "No such token: 'tok_1PKHY1IRI3YGNQKDocTdMkPu'", "param": "source", "request_log_url": "https://dashboard.stripe.com/test/logs/req_GKbBUprcIuSQ0X?t=1716631798", "type": "invalid_request_error" } } Request POST body { "source": "tok_1PKHY1IRI3YGNQKDocTdMkPu", "amount": "4400", "currency": "usd" } My API tokens STRIPE_SECRET_KEY=sk_test_51PKFiB03rDhpU9syC7RuPemfhPC6Z5IZvxaKWRR5MajKEE3tvE58VrbZjxp3y56VoGrC2QLkARr95QVuDpmmu8uv00TP46EZQM STRIPE_PUBLISHABLE_KEY=pk_test_51PKFiB03rDhpU9syvWsl9Mvlt0XLdWaDI9a8fdolFlN9SXcUSxPhd9rtolZSUKIbBikfuWoeYZkPrdxFvf1T3Pmw00DGaQtOPA VIEWS.PY class PaymentView(LoginRequiredMixin, View): def get(self, *args, **kwargs): order = Order.objects.filter(user=self.request.user, ordered=False).first() return render(self.request, 'checkout/payment.html', {'order': order}) def post(self, *args, **kwargs): order = Order.objects.filter(user=self.request.user, ordered=False).first() token = self.request.POST.get('stripeToken') try: charge = stripe.Charge.create( amount=round(float(order.get_total_amount() * 100)), currency="usd", source=token ) except stripe.error.CardError: messages.error(self.request, 'Payment could not be made') return redirect('products:home-page') except Exception: messages.error(self.request, 'Internal server error') return redirect('products:home-page') payment = Payment( user=self.request.user, stripe_id=charge.id, amount=order.get_total_amount() … -
I am unable to transfer the object to display_item.html page, from index page in Djanog page
I have been trying for a very long time to transfer item, which is obtained via a for loop in Django templating language. An item is an object. I have tried a lot of different arrangements, but nothing is working so far. It's the index file. {% extends "auctions/layout.html" %} {% block body %} <h2>Active Listings</h2> {% for item in listings %} <a href="{% url 'display_item' entry=item %}"> <img src="/media/{{ item.image_url }}" width="300" height="400" alt="Picture of the item."> <h3>{{ item.title }}</h3> </a> <p>{{ item.description }}</p> <h5>Starting bid: {{ item.starting_bid }}</h5> {% empty %} <h4>No listings to display!</h4> {% endfor %} {% endblock %} Its the file that is suppose to display the object. {% extends 'auctions/layout.html' %} {% block body %} <img src="/media/{{ item.image_url }}" width="400" alt="Picture of item here."> <p>{{ item.category }}</p> <h3>{{ item.title }}</h3> <p>{{ item.description }}</p> <br> <br> <h5>Created by {{ item.created_by }}</h5> <p>{{ item.created_at }}</p> {% endblock %} It's the URLS.py file. from django.conf import settings from django.conf.urls.static import static from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("new_listing", views.new_listing, name="new_listing"), path("display_item/<str:entry>/", views.display_item , name="display_item") ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, … -
Django chat app sorted messages by datetime
i have a chat and Message Model. How can i sort my Chat with the creation_date of Message example:consider that i am in two chats(A and B): i want that everytime i receive a message from B so that B should be the bottom of A and when i receive a message from A so that A should be the bottom of B. I've spent a lot of time to do this but there was no success. Models.py `class Chat(models.Model): creation_date = models.DateField(default=timezone.now) id = models.AutoField(primary_key=True) content = models.TextField() sender = models.ForeignKey( BasicUserProfile, on_delete=models.CASCADE, blank=True, null=True, related_name="sender" ) reciever = models.ForeignKey( BasicUserProfile, on_delete=models.CASCADE, blank=True, null=True, related_name="reciever" ) class Meta: ordering = ["-creation_date"] def __str__(self): return "chat: " + str(self.sender)` views.py # admin user session pop # admin user session pop # Deleting any sessions regarding top-tier type of users # Get the current users current_basic_user = get_current_user(request, User, ObjectDoesNotExist) current_basic_user_profile = get_current_user_profile( request, User, BasicUserProfile, ObjectDoesNotExist ) # Topics to follow topics_to_follow = get_topics_to_follow(Topic, ObjectDoesNotExist, random) # Who to follow box cells who_to_follow = get_who_to_follow( BasicUserProfile ) # Get the current followings try: current_followings = Follower.objects.filter( follower=current_basic_user_profile ) except ObjectDoesNotExist: current_followings = None # Get the current text reciever (user) … -
How to convert http.wsgi.Response object to dict in gunicorn log
I want to add a custom atom to atoms of gunicorn in logging class that indicates the response of the request. Something like this: from gunicorn.glogging import Logger class MyLog(Logger): def atoms(self, resp, req, environ, request_time): from django.urls import resolve atoms = super().atoms(resp, req, environ, request_time) url_name = resolve(environ.get('PATH_INFO')).url_name # This is what I want to do: if url_name == 'xxxx': response_body = ... # TODO atoms['R'] = response_body.get('yyy') Is there any way to convert resp in atoms function to real response (in text or json)? -
Difficulty Accessing SQLite Tables in Django Environment
My Testing Environment: Operating System: Windows 10 Pro 22H2 Anaconda Version: 24.1.2 (Python 3.11.7) Integrated Development Environment: Visual Studio Code 1.89.1 Django Version: 5.0.6 Problem: I'm new to Django and currently exploring its documentation. I successfully completed the first section, Writing your first Django app, part 1 (How to setting up your first App) as per the instructions provided. However, I'm encountering difficulties understanding the second section, Writing your first Django app, part 2 (How to work with databases) particularly in working with databases. The documentation mentions that SQLite is the default database and should be accessible without additional installation, which aligns with my understanding. Following the instructions, I ran the command python manage.py migrate without any issues. However, when attempting to show the created tables using the SQLite command .tables, I encountered the following error: (.venv) PS C:\Users\marco\Desktop\DjangoProject\EuroChampBettingSite> .tables .tables : The term '.tables' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + .tables + ~~~~~~~ + CategoryInfo : ObjectNotFound: (.tables:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Additionally, … -
How can i import successfully bootstrap in html?
That's my code: <!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"> <title>WebCamera</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> </head> <body> <div> <img src="{% url 'livefy' %}"> </div> <br> <form action="http://localhost:8000/" method="post"> {% csrf_token %} <button type="submit">Check Face</button> </form> <h6>Name:{{n}}</h6> <h6>Id:{{i}}</h6> <div class="container-sm">100% wide until small breakpoint</div> <div class="container-md">100% wide until medium breakpoint</div> <div class="container-lg">100% wide until large breakpoint</div> <div class="container-xl">100% wide until extra large breakpoint</div> <div class="container-xxl">100% wide until extra extra large breakpoint</div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.min.js" integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script> </body> </html> and i want to know why my bootstrap is not working? I Using windows 11,python 3.11,bootstrap 5.3,django 5.0.2 Please Help ME! -
How to get django authentication working in development without ssl protocol
We are working on a django backend using django-ninja for all the APIs. The backend is deployed on a test server for our colleague who works on the react frontend. We have a login endpoint making use of djangos native authentication functionality. This seems to work if we test it using the swagger ui api doc page. However we are having issues with the frontend. We can login successfully from the frontend (running on localhost) but somehow the browser does not keep sending the returned cookie with the session_id and the csrf_token for all the subsequent calls. we are using the following cors and cookie setting and have tried finding a configuration that works: CORS_ALLOW_HEADERS = default_headers CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True ALLOWED_HOSTS = ["*"] SESSION_COOKIE_SAMESITE = "None" SESSION_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = "None" CSRF_COOKIE_SECURE = True Since we are not using the ssl protocol for development. We keep getting a warning in the browser saying we can not set Samesite None and secure over an unsecure connection. I think this may be the issue that is causing the authentication to not properly work. What would be the best way to resolve this? Do people usually use ssl for … -
ModuleNotFoundError: No module named 'pkg_resources' in vercel
I am trying to deploy a DRF Api on vercel, I tried upgrading setuptools and everything that I found on net but still not able to get it to work I am using python3.10.13 vercel.json { "builds": [{ "src": "./core/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.10" } }, { "src": "./build_files.sh", "use": "@vercel/static-build", "config": { "distDir": "staticfiles_build" } }], "routes": [ { "src": "/static/(.*)", "dest": "/static/$1" }, { "src": "/(.*)", "dest": "./core/wsgi.py" } ] } build_files.sh #!/bin/bash echo "BUILD START" # Activate virtual environment if needed # Replace 'venv' with your virtual environment directory name source env/bin/activate # Install dependencies python3 -m pip install -r requirements.txt # Collect static files python3 manage.py collectstatic --noinput --clear echo "BUILD END" I was trying to follow this article for deployment article please guide me on this. I am trying for last 2 days but not able to solve it -
Import CSV Django
I have an application that used for student assessment, so i have some attributes like 'absensi', 'tugas', 'uts' and 'uas' in app_nilai and the other used foreignkey that connected with their object it includes 'mahasiswa', 'kelas' and 'matakuliah' in app_matkul. That object has each variable to explain. When i put import file in html it doesn't work but in admin it's really work. Would you check my program and where's the problem ? Noted : No error or failure messages appeared, making me confused about where the problem was views.py in app_nilai def import_csv(request, kelas_id): kelas = get_object_or_404(Kelas, id=kelas_id) if request.method == 'POST': form = UploadCSVForm(request.POST, request.FILES) if form.is_valid(): csv_file = request.FILES['csv_file'] dataset = Dataset() imported_data = dataset.load(csv_file.read().decode('utf-8'), format='csv') nilai_resource = NilaiResource() result = nilai_resource.import_data(imported_data, dry_run=True, use_transactions=True, raise_errors=True, kelas_id=kelas_id) if not result.has_errors(): import_result = nilai_resource.import_data(imported_data, dry_run=False, use_transactions=True, raise_errors=True, kelas_id=kelas_id, update=True) messages.success(request, 'Data berhasil diimpor.') else: messages.error(request, 'Terjadi kesalahan saat mengimpor data.') else: messages.error(request, 'Form tidak valid.') return redirect('nilai_kelas', kelas_id=kelas_id) form = UploadCSVForm() return render(request, 'import_csv.html', {'form': form, 'kelas': kelas}) resource.py in app_nilai class NilaiResource(resources.ModelResource): data_id = fields.Field( column_name='id', attribute='pk' ) mahasiswa = fields.Field( column_name='mahasiswa', attribute='mahasiswa', widget=ForeignKeyWidget(Mahasiswa, 'id') ) matakuliah = fields.Field( column_name='matakuliah', # Ganti nama kolom ini untuk menghindari konflik … -
DJANGO: Sum number of professionals per district
I am trying to plot some numbers on my charts. But I have a problem summing the number of professionals per district(foreign key). Here is my model.py. class District(models.Model): name = models.CharField(max_length=50, blank=True, null=True) location = models.CharField(max_length=80, blank=True, null=True) population = models.IntegerField(blank=True, null=True) class Household(models.Model): district = models.ForeignKey(District, on_delete=models.CASCADE, null=True) family_name = models.CharField(max_length=50, blank=True, null=True) address = models.CharField(max_length=150, blank=True, null=True) members = models.IntegerField(blank=True, null=True) # no of members professionals = models.IntegerField(blank=True, null=True) # no of professionals ... Below is just an overall total of professionals. But how can I sum it by district? from django.db.models import Sum def dashboard(request): stats = Household.objects.annotate(total_prof=Sum('professionals')) -
in Django, I would like to show inventory
I try to show a list of product record in inventory models and link to a vendor. but I try to show the last record for each different product and its balance quatity. in my case, I've 3 vendors. for each product sale or purchase I save it. so a vendor can manage his own stock. vendor A can pruchase product1, product 2 and next day do the same. the vendor 2 can purchase the same product1 and product3. so I wanna know how to show onqty balance for product 1 for vendeur 1 do the same for product2 etc. vendor = Vendor.objects.filter(user=request.user) q = Inventory.objects.values('product').annotate(latest_id=Max('id')) stock = Inventory.objects.filter(id__in=[product['latest_id'] for product in q],vendor__in=vendor) context = { "vendor":vendor, "stock": stock, } return render(request, 'core/dashboard.html', context) -
Is this logic in Settings.py regarding database redunant
In the settings of a Django project I am working on this is the way the DATABASES has been set up. The person who has written this has explained that the if statement is a redundancy which doesn't make sense to me. As far as my understanding goes if the try fails that the if will also fail because they are setting 'default' the same way? Is this if statement redundant: try: DATABASES = { 'default': env.db(), } except environ.ImproperlyConfigured: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Override with DATABASE_URL if it exists if env('DATABASE_URL', default=None): DATABASES['default'] = env.db() And if not can someone please explain to me to me why? Thanks for any clarification. I have tried using an empty value for DATABASE_URL but it doesn't seem to make a difference whether the if is there or not. Please don't give me the same answer as ChatGPT either becauses after two questions I have it saying that it is redundant. -
Alternative to Local storage
I made a Django project, a calibration list with reference machines. Each calibration has a full page of calculations, another page takes data from the calculations and renders it on a digital certificate page. I pass the data from the calculation page to the certificate page using local storage, but the problem is that when I open multiple certificates, they don't update automatically. I have to open the calculation page of one certificate for it to render the certificate with the correct data. If I open another certificate, it still has the data from the previous one, and that will be a problem if I want to send these certificates to the client and they have data saved from other calculations. `function calculoErrorProm(rowElement) { let LCIBCElement = rowElement.querySelector('.LCIBC'); let LCPElement = rowElement.querySelector('.LCP'); let EPElement = rowElement.querySelector('.EP'); let EElement = rowElement.querySelector('.E'); let LCIBCText = LCIBCElement.textContent; let LCIBC = parseFloat(LCIBCText.replace(/,/g, '.')); let LCPText = LCPElement.textContent; let LCP = parseFloat(LCPText.replace(/,/g, '.')); let EPText = EPElement.textContent; let EP = parseFloat(EPText.replace(/,/g, '.')); let E = LCIBC - (LCP - EP); EElement.textContent = E.toPrecision(4); // Save the values of E in an array and store it in localStorage let valoresE = JSON.parse(localStorage.getItem('valoresE')) || []; valoresE.push(E.toPrecision(4)); localStorage.setItem('valoresE', … -
Check failed: ret == 0 (11 vs. 0)Thread tf_Compute creation via pthread_create() failed
when I run keras.load_model and make_predict_function on a django application that has been deployed on cpanel. an error occurs: Check failed: ret == 0 (11 vs. 0)Thread tf_Compute creation via pthread_create() failed. import os os.environ['TF_ENABLE_ONEDNN_OPTS'] = '2' # {0,1,2,3,4} os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' from keras.models import load_model from keras.keras.preprocessing import image as kerasImage model_dir = settings.BASE_DIR / "/static/model.h5" model = load_model(model_dir) model.make_predict_function() # actual class labels class_labels = ["kencur", “temulawak”, “ginger”, “turmeric”, “galangal”] # Proccesing image by keras i = kerasImage.load_img(img_path, target_size=(224, 224)) i = kerasImage.i(i) / 255.0 shape = i.reshape(1, 224, 224, 3) p = model.predict(shape) when running a django app to load_model using a trained model stored in the root static directory. I use python version 7.3 and tensorflow / hardware version 2.11.0 on my cpanel how do I resolve this? -
Profile is not registered with auto created User via signals
I have a django application where the following model named Employee plays the role of the user Profile that is in relation with the User from the auth module: class Employee(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True) phone = models.IntegerField(blank=True) is_chef_de_project = models.BooleanField( default=False ) is_chef_de_produit = models.BooleanField( default=False ) is_ghr = models.BooleanField( default=False ) account = models.OneToOneField( User, on_delete=models.CASCADE, null=True ) i want to automatically to create a User during registration of an Employee so i created the following signals.py file: from django.db.models.signals import post_save from django.contrib.auth.models import User from django.contrib.auth import hashers from django.dispatch import receiver from .models import Employee def generate_password(): import secrets import string alphabet = string.ascii_letters + string.digits return ''.join(secrets.choice(alphabet) for i in range(10)) @receiver(post_save, sender=Employee) def create_user(sender, instance, created, **kwargs): breakpoint() if created: uname = instance.first_name[0].lower() + instance.last_name.lower() passd = generate_password() User.objects.create(employee=instance, username=uname, password=passd) print("generated credentials:" + uname + ":" + passd) @receiver(post_save, sender=Employee) def save_user(sender, instance, **kwargs): breakpoint() instance.account.save() but after registration i find the account attribute in the created Employee instance null: null account any hints what's going on ? i was expecting the User instance created to be referenced by the registered Employee -
inconsistent django session key
I am implementing a cart function which gets session key since it doesnt have user login. But every time I add something to the cart, it gets different session key. When I check the django admin panel, it adds data to the cart but I get an empty array whenever I call my Get Cart api. @api_view(['POST']) def add_to_cart(request): try: session_key = request.session.session_key if not session_key: request.session.create() session_key = request.session.session_key product_id = request.data.get('product') quantity = request.data.get('quantity') size_id = request.data.get('size') if not all([product_id, quantity, size_id]): return Response({'error': 'Missing required fields'}, status=status.HTTP_400_BAD_REQUEST) cart_item = Cart.objects.create( product_id=product_id, quantity=quantity, size_id=size_id, session_key=session_key ) serializer = CartSerializer(cart_item) return Response(serializer.data, status=status.HTTP_201_CREATED) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) @api_view(['GET']) def get_cart_items(request): session_key = request.session.session_key cart_items = Cart.objects.filter(session_key=session_key) serializer = CartSerializer(cart_items, many=True) return Response(serializer.data) -
Huey Connection Refused
I keep getting "connection failed: connection to the server at "127.0.0.1", port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections" when running my task in production?" This does not happen in local development. @db_periodic_task(crontab(minute='*/1'), queue='application_expiration') def parcel_expiration_task(): # current date and time current_timestamp = timezone.localtime(timezone.now()) # get all event get_events = Event.objects.order_by('-creation_time').filter( time_ends__lt=current_timestamp ) if get_events.exists(): .... I have tried to add a db. connection in the supervisor: [program: application] command='...' user='...' autostart=true autorestart=true redirect_stderr = true stdout_logfile = '....' environment=DATABASE_URL="postgresql://username: password@localhost:5432/db_name" I have also edited the pg_hba.conf file and added the following entry at the end of the file: host all all 0.0.0.0/0 md5 host all all ::/0 md5 -
Will a dynamic list of choices in a Django model evaluate when the model is migrated or when a user tries to select a choice for a model?
Code Let's say I have the following model: class Course(models.Model): title = models.CharField(max_length=48) YEAR_CHOICES = [(r, r) for r in range( datetime.date.today().year-1, datetime.date.today().year+2 ) ] year = models.IntegerField(_('year'), choices=YEAR_CHOICES) Question Will the datetime.date.today() statements be evaluated right when the model is migrated, or will they be evaluated whenever the user accesses a form to set the year value for the Course model? In other words, is my YEAR_CHOICES code above frozen to when I migrated my model or will it dynamically update as the years go by? -
django generic UpdateView with some custom fields
My question is quite close to this one UpdateView with additionnals fields, so I used the info, but I still lack some details to complete the process So, I have a simple toy model : class TxtPlus(models.Model): txt = models.CharField(max_length=140) def __str__(self): return f'TxtPlus<{self.id},{self.txt}>' def get_absolute_url(self): return reverse("tplus_detail", kwargs={"pk": self.pk}) When editing an instance, I want to add a field, and thus according to the answer above, I define a custom Model class TxtPlusForm(ModelForm): info = CharField(widget=Textarea(attrs={"rows":"2"})) class Meta: model = TxtPlus fields = ["txt", ] the using the UpdateView is easy class TxtPlusUpdateView(UpdateView): model = TxtPlus template_name = "adding_to_model_forms/tplus_update.html" form_class = TxtPlusForm But, what I wish to do is roughly: def infos_associated_to_object(object): return f'there is more about object:{object.pk}' def test_edit(request,pk): object = TxtPlus.objects.get(id=pk) info = infos_associated_to_object(object) if request.method == 'GET': form = TxtPlusForm(instance=object,initial={'info': info}) up_log = None if request.method == 'POST': form = TxtPlusForm(request.POST,instance=object) up_log = f"change '{info}' to '{form.data['info']}'" form.save() #... add here form.data['info'] saving return render( request, "adding_to_model_forms/tplus_edit.html", { "object" : object, "form" : form, "info" : info, "up_log" : up_log } ) (of course, infos_associated_to_object, is here a toy version..) In particular, my problem with UpdateView, is on : first the part initial={'info': info} (where info … -
Images not showing, using Django admin, cloudinary and deploying to Heroku
I'm trying to add images to my project (in the albums) using django admin, cloudinary and then it is being deployed to Heroku. I can't seem to make it work, sat with a tutor for 2 hours yesterday and we made it work and now it's just gone again. Header image is just black and the image for the album is coming back as a 404 even if I checked that the image is where it should be. When I upload on Django admin the image file does not go to the workspace and stays in cloudinary so I think it is because of that. Anyone who has any other ideas? enter image description here Where it's black shoul be a static image and further down where the image icon is should be an image loaded from Django admin panel. -
getting an error saying assessment must be an instance
in my assessment section model i have defined an foreign key like this: assessment_id = models.ForeignKey(to=Assessment, on_delete=models.CASCADE, related_name='section_assessment_mapping', null=False, blank=False, help_text="The assessment associated with this section.") this points to assessment model's id whichis primary key. in assessment section serializer i have defined the assessment id like this: assessment_id = serializers.UUIDField(required=True) this is the create method of the serializer: def create(self, validated_data): print('validdata',validated_data) print(validated_data.get('assessment_id')) section_obj = AssessmentSection.objects.create_with_defaults(**validated_data) return section_obj and this is the create api for assessment section: def create(self, request, *args, **kwargs): try: serializer = AssessmentSectionSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(data=serializer.data, status=status.HTTP_201_CREATED) except ValidationError as e: service_logger.error(str(e)) return Response({'error': True, 'message': e.args[0]}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: service_logger.error(str(e)) raise StandardizedException(error_status=True, error_obj=e, status_code=status.HTTP_400_BAD_REQUEST) now when i hit the API with payload containing assessment_id having some valid assessment id which is present in the DB it gives this error: Cannot assign \"UUID('7025deca-afb8-4ad3-93b8-6035599bcf6e')\": \"AssessmentSection.assessment_id\" must be a \"Assessment\" instance." } I have tried several approaches but they are not working. I just need to store the assessment id in the table with section info. Thank you in advance. tried using source=assesment.id in the serializer field but didnt work. -
Pure SQL from postgres to django
We have a pure SQL in postgres that groups the instance visits registered in that table grouped by country, what I need is to pass this pure query to django queryset to get the same result Here is the pure SQL query: SELECT country, SUM(difference) AS total_difference FROM ( SELECT id, entry_or_exit_datetime AS entry_time, LEAD(entry_or_exit_datetime) OVER (ORDER BY entry_or_exit_datetime) AS exit_time, EXTRACT(EPOCH FROM (LEAD(entry_or_exit_datetime) OVER (ORDER BY entry_or_exit_datetime) - entry_or_exit_datetime)) AS difference, country FROM ( SELECT id, entry_or_exit_datetime, country, LAG(is_joining) OVER (ORDER BY entry_or_exit_datetime) AS prev_is_joining FROM public.access_sectionslog WHERE date(entry_or_exit_datetime) >= '2024-05-17' AND date(entry_or_exit_datetime) <= '2024-05-23' AND section_name = 'landing-page' AND country IN ('VE', 'CO') ) AS subquery ) AS subquery_with_difference GROUP BY country; This is the model in django: class SectionsLog(BaseModel): class SectionNameChoice(models.TextChoices): GROUPS = "section-groups", _("Groups") FEED = "section-feed", _("Feed") NEWS = "section-news", _("News") LANDING_PAGE = "landing-page", _("Landing Page") EXTERNALS_SHARING = "external-sharing", _("External Sharing") LIVESCORE = "section-livescore", _("Livescore") SALES_PAGE = "sales-page", _("Sales page") ON_BOARDING = "onboarding", _("On boarding") user = models.ForeignKey( User, on_delete=models.CASCADE, blank=True, null=True, related_name="sections_log", ) section_name = models.CharField( max_length=20, choices=SectionNameChoice.choices, null=True, blank=True, ) is_joining = models.BooleanField( blank=True, null=True, help_text="Enter the Section(True)/Leave the Section(False)", ) is_anonymous = models.BooleanField( default=False, blank=True, null=True, help_text="Is True to anybody who enter … -
Django migration keeps generating old model attributes (is it cached somewhere?)
I am new to Django but have some experience with MVC web development. I am encountered with a weird problem, hopefully, it is only weird to me, not all folks. After doing some changes (changing attribute's names) in models project_name/models.py. I ran: python manage.py makemigrations to migrate the DB with new changes. But it showed that "No changes." So I decided to do a fresh re-migrate DB :( Delete DB and recreate empty DB Delete migrations/ folder and recreate folder with __init__.py Re-run makemigrations OK. Now the weird thing happens. No matter how I change in models.py, the migrations/0001_initial.py file always keep generate old attribute. # models.py class Task(models.Model): STATUS_CHOICES = [ ('PENDING', 'Pending'), ('PROCESSING', 'Processing'), ('COMPLETED', 'Completed'), ('FAILED', 'Failed'), ] pdf_file = models.FileField(upload_to='pdfs/') status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='PENDING') #Previously `preview_url` preview_img = models.ImageField(blank=True, null=True, upload_to='previews/') #Previously `thumbnail_url` thumbnail_img = models.ImageField(blank=True, null=True, upload_to='thumbnails/') error_message = models.TextField(blank=True, null=True) uploaded_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f"Task: {self.id} - {self.status}: {self.pdf_file.name}" # migrations/0001_initial.py ... operations = [ migrations.CreateModel( name='Task', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('pdf_file', models.FileField(upload_to='uploads/')), ('status', models.CharField(choices=[('PENDING', 'Pending'), ('PROCESSING', 'Processing'), ('COMPLETED', 'Completed'), ('FAILED', 'Failed')], default='PENDING', max_length=10)), ('preview_url', models.URLField(blank=True, null=True)), # WEIRD ('thumbnail_url', models.URLField(blank=True, null=True)), # WEIRD ('error_message', models.TextField(blank=True, …