Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can we make copy of a static file in Django?
My requirement is to write into a sample excel (static) file, and download the copied static file in the device. The copy is required cause the sample file contains some formatting, which I need in the downloaded file as well. Directory Structure : Django Project - project - app - static - files -> sample.xlsx - css - js - manage.py Now, I need to create a copy of sample.xlsx file, write some details in it and download it. I've tried below code, in which I am creating a new file and copying the content from sample.xlsx to new_file.xlsx . But it does not copy the formatting from sample.xlsx def exportXLS(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="new_file.xlsx"' sample = load_workbook(sample_file_path) #opening sample.xlsx active_sheet = sample.worksheets[0] new_workbook = Workbook() #creating new excel file worksheet = wb.active worksheet.title = "Sheet Name" mr = active_sheet.max_row mc = active_sheet.max_column #copying values from sample.xlsx to new_file.xlsx for i in range (1, mr + 1): for j in range (1, mc + 1): c = active_sheet.cell(row = i, column = j) worksheet.cell(row = i, column = j).value = c.value new_workbook.save(response) return response ==> I would like to make a COPY of sample.xlsx first then write … -
Using Arrays vs Temp Tables for a user session
I am prototyping an event system app for a local organization. They are logging into the site and then API calls use their entered login info to retrieve information from other apps. The goal is to not store any long term "user data" since that is stored in the other apps. (by user data, I mean stuff for logins/settings/etc since its stored in those other apps). The info retrieved from the API calls is displayed to the user but is only needed for the length of the registration process. Once the user registers for the event, the data gotten from the API calls and such should be deleted and the only data saved long term is the data that makes its way to the separate event registration table. Is it better to do a temp table or to store the temporary information in a session variable/array? We are only anticipating maybe 500 concurrent users. -
GeoDjango endpoint is extremely slow
I'm trying to work with a list of 1.100 rows loaded in a PostgreSQL with PostGIS extension. Each row has the following fields: code (integer) name (char) mpoly (multipolygon) The idea is to have an endpoint that will be called from a VueJS app to print each geo data in a Leaflet managed map. The query is extremely slow when serializing it. How can I optimize it? I thought about having a geojson file, but each row has a manytomany table associated that indicate some groups that it belongs to. -
Problem RSA cryptographie in python [django]
I've following code in python, django, to share symetric cryptographie for encrypt/decrypt files, using RSA cryptographie, i can allready create RSA keys and store them in the member model, also I'm able to create the securit_key_relations, but then the private_key_relation in member model is empty, I tried everything and don't know why. models.py class Member(models.Model): private_key=models.TextField(blank=True, null=True) public_key=models.TextField(blank=True, null=True) private_key_relation=models.TextField(blank=True, null=True) dc_verification=models.CharField(max_length=50, blank=True, null=True) id=models.AutoField(primary_key=True) permission=models.TextField(default="") mma_classification=models.IntegerField(default=1) firstname=models.CharField(max_length=30, null=True) lastname=models.CharField(max_length=30, null=True) username=models.CharField(max_length=30, null=True, unique=True) password=models.CharField(max_length=1000, null=True) agentnr=models.CharField(max_length=11, null=True, unique=True) bezlogged=models.CharField(max_length=20, null=True) frei=models.BooleanField(default='FALSE') email=models.EmailField(max_length=50) code=models.CharField(max_length=50, null=True, unique=True) verify=models.BooleanField(default=False) ort=models.CharField(max_length=50, null=True) bereitschaftsort=models.CharField(max_length=50, null=True) land=models.CharField(max_length=4, default='ENG') phonenumber=models.CharField(max_length=20, default='0000000000') kategorie=models.CharField(max_length=9, default='agent') benachrichtigt=models.BooleanField(default='FALSE') abteilung=models.CharField(max_length=30, null=True) einsatztag=models.CharField(max_length=30, default='agent') status=models.CharField(max_length=1, default='5') api_user=models.BooleanField(default='False') dc_tag=models.CharField(max_length=100, null=True) support=models.CharField(max_length=100, default="no_support") prioritaet=models.CharField(max_length=1, default="1") pefw=models.BooleanField(default=False) device_code=models.TextField(default="X", max_length=1000) device_id=models.CharField(max_length=100, default='X') def __str__(self): return self.firstname + " " + self.lastname class security_key_rel(models.Model): id=models.AutoField(primary_key=True) gmid=models.TextField(blank=True, null=True) key=models.TextField(blank=True, null=True) purpose=models.TextField(blank=True, null=True) ` views.py `def byte_to_string(byte_obj): return byte_obj.decode('utf-8') def string_to_byte(string_obj): return string_obj.encode() def encrypt_file(filename, key): key = string_to_byte(key) f = Fernet(key) with open(filename, 'rb') as file: file_data = file.read() encrypted_data = f.encrypt(file_data) os.remove(filename) with open(filename, 'wb') as file: file.write(encrypted_data) def decrypt_file(filename, key): key = string_to_byte(key) f = Fernet(key) with open(filename, 'rb') as file: encrypted_data = file.read() decrypted_data = f.decrypt(encrypted_data) os.remove(filename) with open(filename, 'wb') as file: file.write(decrypted_data) def generate_RSA_key(): … -
Why is Heroku returning a 500 server error when Django DEBUG is set to False?
Working locally, I'm able to visit mysite.com. Hosted on Heroku, I'm only able to access mysite.com if I have DJANGO_DEBUG set to True in my config vars. The following is my settings.py file: from pathlib import Path import os from dotenv import load_dotenv import dj_database_url import django_heroku load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False' ALLOWED_HOSTS = ['myprojectwebsite.herokuapp.com', 'www.mysite.com', 'mysite.com', 'localhost', '127.0.0.1'] INSTALLED_APPS = [ 'myprojectwebsite', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_google_fonts', 'django.contrib.sitemaps', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myproject.urls' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'detailed': { 'format': '{levelname} {asctime} {module} {message} {pathname}:{lineno}', 'style': '{', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'detailed', }, }, 'loggers': { 'script_logger': { 'handlers': ['console'], 'level': 'DEBUG', }, }, } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], # Global templates folder 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', 'myprojectwebsite.context_processors.resorts_by_location', ], }, }, ] WSGI_APPLICATION = 'myproject.wsgi.application' if DEBUG: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', … -
Unable to split text received as POST request in django
i am facing a weird error. I am trying to split text sent via form in django. Here is my code in django from transformers import AutoTokenizer from langchain.text_splitter import CharacterTextSplitter tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased-finetuned-sst-2-english" ) text_splitter = CharacterTextSplitter.from_huggingface_tokenizer( tokenizer, chunk_size=256, chunk_overlap=0 ) def home(request): if request.method == 'POST': input_text = request.POST['input'] # Get input text from the POST request print("input_text",type(input_text)) splitted_text = text_splitter.split_text(str(input_text)) print("splitted_text_length_outside",len(splitted_text)) The length is always 1, which mean text is not split. I have checked that i am receiving text from html form and the type of text is str. But when i use the same code outside of django such as in jupyter notebook, it work well and split the text. In django I tried input_text.split() and that worked. But i am clueless why the langchain text splitter is not working. def home(input_text): splitted_text = text_splitter.split_text(input_text) print("splitted_text_length_outside",len(splitted_text)) Here is my html form <form action="{% url 'home' %}" method="post" id="myForm"> {% csrf_token %} <textarea name="input" id="input" rows="4" cols="50"></textarea> <br> <button type="submit">Submit</button> </form> Here is my ajax code $("#myForm").submit(function(event) { event.preventDefault(); let formData = $(this).serialize(); $.ajax({ "url": "/", "type": "POST", "data": formData, "success": function(response) { console.log("success"); }, "error": function(error) { console.log("error",error); } }); }); -
How to solve Model class django.contrib.contenttypes.models.ContentType
RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. And LookupError: No installed app with label 'admin'. Are the Errors i am facing so please help me to solve both. Error is Traceback (most recent call last): File "A:\Projects\ePlant\eplant_dj\manage.py", line 22, in <module> main() File "A:\Projects\ePlant\eplant_dj\manage.py", line 18, in main execute_from_command_line(sys.argv) File "A:\Projects\ePlant\venv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "A:\Projects\ePlant\venv\Lib\site-packages\django\core\management\__init__.py", line 382, in execute settings.INSTALLED_APPS File "A:\Projects\ePlant\venv\Lib\site-packages\django\conf\__init__.py", line 89, in __getattr__ self._setup(name) File "A:\Projects\ePlant\venv\Lib\site-packages\django\conf\__init__.py", line 76, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "A:\Projects\ePlant\venv\Lib\site-packages\django\conf\__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ateyu\AppData\Local\Programs\Python\Python312\Lib\importlib\__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 995, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "A:\Projects\ePlant\eplant_dj\eplant_dj\settings.py", line 11, in <module> from account.authentication import CustomJWTAuthentication File "A:\Projects\ePlant\eplant_dj\account\authentication.py", line 1, in <module> from rest_framework_simplejwt.authentication import JWTAuthentication File "A:\Projects\ePlant\venv\Lib\site-packages\rest_framework_simplejwt\authentication.py", line 4, in <module> from django.contrib.auth.models import AbstractBaseUser File "A:\Projects\ePlant\venv\Lib\site-packages\django\contrib\auth\models.py", line 5, in <module> from django.contrib.contenttypes.models import ContentType File "A:\Projects\ePlant\venv\Lib\site-packages\django\contrib\contenttypes\models.py", line 139, in <module> class ContentType(models.Model): … -
Save the current user when saving a model in Django admin backend
I'd like to store the user that saved a model for the first time in one of the fields of that model. This is what I have. models.py: from django.conf import settings class Project(models.Model): [...] added_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.PROTECT) def save_model(self, request, obj, form, change): if not obj.pk: obj.added_by = request.user super().save_model(request, obj, form, change) settings.py: AUTH_USER_MODEL = 'auth.User' The request.user appear to be always empty (I'm logged in as root to the /admin). What am I missing? -
Django+Nginx having issue with SSE
I made an API on django rest framework, I have SSE via django-eventstream Deployed everything on the server (django in docker), wrote a config for nginx But for some reason the SSE query does not work, everything else works I even added print to the function from the module to check if the request reaches the api, everything is ok But in the postman there is an endless sending of the request, although I checked locally - everything worked Nginx conf location /events/orders/ { proxy_pass http://172.23.0.3:8005/events/orders/; proxy_set_header Host $host; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_buffering off; proxy_set_header Content-Type text/event-stream; proxy_cache off; proxy_buffers 8 32k; proxy_buffer_size 64k; } ASGI os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sushi_api.settings') application = get_asgi_application() -
Where the actual db fetch is done in drf list()
As you may know the querysets do the actual fetch data only when you evaluate them for ex iterating over them. I want to put that actual fetch inside celery so I need to catch the method in which that actual fetch data from db happens during drf lifecycle. what is it? I'm diving in drf source code but since I have not much time any help is appreciated. -
Social Authentication (dj_rest_auth) with multiple role user
#user_model: class User(AbstractUser, PermissionsMixin): class Role(models.TextChoices): SELLER = "seller" BUYER = "buyer" SUPER = "super" name = models.CharField(max_length=100) phone = models.CharField(max_length=15) email = models.EmailField() created_at = models.DateTimeField(default=timezone.now) shipping_address = models.CharField(max_length=100, blank=True, null=True) role = models.CharField( max_length=100, default=Role.SELLER.value, choices=Role.choices ) updated_at = models.DateTimeField(default=timezone.now, null=True) first_name = None last_name = None profile_picture = models.ImageField( default="profile 1.jpg", upload_to="profile_images" ) is_staff = models.BooleanField(default=False) is_blocked = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) username = models.CharField(max_length=30, unique=True) USERNAME_FIELD = "username" REQUIRED_FIELDS = ["email", "name", "role"] objects = myUserManager() class Meta: unique_together = [("email", "role"), ("phone", "role")] ordering = ["id"] db_table = "users" I've implemented dj_rest_auth with Google Authentication, and it functions as intended. However, a limitation arises wherein it only supports users with a single role. For instance, if we create a user with the role of seller, it successfully creates an account and logs in the user. However, if we attempt to log in with a user role such as buyer, it erroneously returns the seller user and logs them in instead. #CustomSocialLoginSerializer: import requests from allauth.socialaccount.models import SocialAccount from dj_rest_auth.registration.serializers import SocialLoginSerializer from django.contrib.auth import get_user_model from django.core.files.base import ContentFile from rest_framework import serializers from rest_framework.response import Response User = get_user_model() class CustomSocialSerializer(SocialLoginSerializer): … -
Django The custom permissions granted in the admin site do not work
I created permissions for the drop-down list, gave the user permissions for the drop-down list on the administration page, so that after logging in he could see only item 1 and item 2. After logging in, the list is empty, no item is displayed. models.py from django.db import models class Main(models.Model): positions = [ ('1', 'Position 1'), ('2', 'Position 2'), ('3', 'Position 3'), ] drop_down = models.CharField(max_length=1, choices=positions) text = models.CharField(max_length=255, blank=True, null=True) forms.py from django import forms from .models import Main class main_input(forms.ModelForm): class Meta: model = Main fields = ['drop_down', 'text'] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(main_input, self).__init__(*args, **kwargs) self.fields['drop_down'].choices = [] if self.user and self.user.has_perm('portal.can_see_position_1'): self.fields['drop_down'].choices.append(('1', 'Position 1')) if self.user and self.user.has_perm('portal.can_see_position_2'): self.fields['drop_down'].choices.append(('2', 'Position 2')) if self.user and self.user.has_perm('portal.can_see_position_3'): self.fields['drop_down'].choices.append(('3', 'Position 3')) class LoginForm(forms.Form): username = forms.CharField(max_length=50) password = forms.CharField(widget=forms.PasswordInput) views.py ct = ContentType.objects.get_for_model(Main) for position in Main.positions: codename = f'can_see_{position[1].replace(" ", "_").lower()}' name = f'Can see {position[1]}' if not Permission.objects.filter(codename=codename, content_type=ct).exists(): permission = Permission.objects.create(codename=codename, name=name, content_type=ct) @login_required(login_url='login') def view_input(request): if request.method == 'POST': form = main_input(request.POST or None, user=request.user) if form.is_valid(): symbol = form.cleaned_data['text'] if form.cleaned_data['drop_down'] == '1': return employee() return employee_csv(symbol) else: form = main_input(user=request.user) return render(request, 'index.html', {'form': form}) I've run … -
expected output is not coming in django
I am trying to scrap the mega menu from the website using python beautiful soup frame work ! for i in menu_items('https://natureshair.com.au/'): print(json.dumps(i, indent=6)) The output is fine! I can able to different level of menus ! Now i want to see the result in browser so i have used Django framework to display this out put in browser this is my views.py code def say_hello(request): for i in menu_items('https://natureshair.com.au/'): return HttpResponse(json.dumps(i, indent=6)) But i am getting only first level of menu list in browser ! dont know where i have missed something Please let me know what i am missing here ? -
creating stripe connect account for seller(creating stripe account)
I am working on a project where i have 2 user type one is buyer and another is seller, Now i am trying the create stripe connect account for that seller so that he/she will be able to receive money view.py def encrypt_data(data): encrypted_data = cipher_suite.encrypt(data.encode()) return encrypted_data.decode() def decrypt_data(encrypted_data): print("Encrypted data:", encrypted_data) if encrypted_data is None: return None decrypted_data = cipher_suite.decrypt(encrypted_data.encode()) return decrypted_data.decode() def bank_details(request): login_user = request.user try: bank_details_obj = BankDetails.objects.get(user=login_user) except BankDetails.DoesNotExist: bank_details_obj = None if request.method == 'POST': bank_name = request.POST.get("bank_name") account_number = request.POST.get("account_number") name = request.POST.get('User_name') routing_number = request.POST.get('routing_number') encrypted_account_number = encrypt_data(account_number) encrypted_name = encrypt_data(name) encrypted_routing_number = encrypt_data(routing_number) if bank_details_obj: bank_details_obj.bank_name = bank_name bank_details_obj.account_number = encrypted_account_number bank_details_obj.username = encrypted_name bank_details_obj.routing_number = encrypted_routing_number bank_details_obj.save() messages.success(request, "Bank Details updated successfully") else: bank_details_obj = BankDetails.objects.create( bank_name=bank_name, account_number=encrypted_account_number, username=encrypted_name, routing_number=encrypted_routing_number, user=login_user, ) messages.success(request, "Bank Details added successfully") try: stripe.api_key = "test key here" user_address = Address.objects.filter(user=login_user).first() stripe_account = stripe.Account.create( type="express", country="US", individual={ "email": login_user.email, "first_name": login_user.first_name, "last_name": login_user.last_name, "dob": login_user.birth_date.strftime("%Y-%m-%d"), "address": { "line1": user_address.line1, "line2": user_address.line2, "city": user_address.city, "state": user_address.state, "postal_code": user_address.postal_code, "country": user_address.country, }, "phone": "+12013514000", }, business_type='individual', external_account={ "object": "bank_account", "country": "US", "currency": "usd", "routing_number": routing_number, "account_number": account_number, }, capabilities={ "card_payments": {"requested": True}, "transfers": {"requested": True}, "legacy_payments": … -
Executing Selenium, Tesseract, and Pandas in a Web App Without Python/Chrome Installed?"
I have a business that downloads and extracts federal tax liens from hundreds of clerk and recorder sites everyday for the last few years I’ve been just running the individual .py scripts from task scheduler. I want to create a product that I can sell as a SASS. I don’t really know what my options are . To be honest my business partner is the code guy I’m the sales guy but I need to understand the process to sell him on this. What are my options, from reading online articles this is what I believe is possible : Create a Python GUI (use figma for look and feel) integrate the figma design with the python code. last create a exe file I can offer to customers 1A. I understand I would have to have the customer install at least chromedriver as the py to exe packs in the needed libraries with the exe. Create a web based dashboard in Django with authentication and isql database. Would this dashboard be able to have features like a button user could click to execute certain python scripts that would complete the python selenium task, export the data to excel and then have … -
Site not available with gunicorn --bind 0.0.0.0:8000 myproject.wsgi
I'm new to deployment, when i do python manage.py runserver 0.0.0.0:8000 i am able to access it on domain and ip with http but when i do gunicorn --bind 0.0.0.0:8000 core.wsgi i tried testing it by running wget http:server_ip:8000 or 127.0.0.1:8000 its just stuck on it Connecting to 127.0.0.1:8000... connected. HTTP request sent, awaiting response... result from sudo ufw status To Action From Nginx Full ALLOW Anywhere 22/tcp ALLOW Anywhere 8000 ALLOW Anywhere Nginx Full (v6) ALLOW Anywhere (v6) 22/tcp (v6) ALLOW Anywhere (v6) 8000 (v6) ALLOW Anywhere (v6) -
Wagtail: How to set InlinePanel Child Label based on model fields?
How can I set the label on the InlinePanel child ("Field 1") to a value based on fields of a model being added? My models: class FormField(AbstractFormField): label = models.CharField( blank=True, verbose_name=_("label"), max_length=255, help_text=_("The label of the form field"), ) field_type = models.CharField( verbose_name="field type", max_length=16, choices=(("section", "Section"),) + FORM_FIELD_CHOICES, ) page = ParentalKey( 'ContactPageBase', on_delete=models.CASCADE, related_name='form_fields', ) And contact form page: class ContactPageBase(WagtailCaptchaEmailForm, BasePage): ... content_panels = AbstractEmailForm.content_panels + [ FieldPanel('contact_intro'), InlinePanel('form_fields', heading=_('Form fields'), label=_("Field")), FieldPanel('thank_you_text') ] I understand the label can be edited like above but that is for the whole set of children in the InlinePanel but I would like to show something like "{FormField.field_type} - {FormField.label}" in the label so it's clear in the overview on the right. How can this be achieved? -
Django - Get a list of the items for which values exist
I have a project in Django. I have 2 modules, QlikApp and QlikAppUserAccess that are related to a ForeignKey. I want to get all the apps that have related 'Qlik AppUser Access' data. How can i do that? class QlikApp(models.Model): id = models.CharField( verbose_name="App ID", primary_key=True, max_length=100, null=False, blank=False, ) application_name = models.CharField( verbose_name="Qlik app name", max_length=100, blank=False, null=False, ) def __str__(self): return f"{self.application_name}" class QlikAppUserAccess(models.Model): app = models.ForeignKey( QlikApp, related_name="qlik_app_user", on_delete=models.PROTECT, null=True, blank=True, ) employee = models.ForeignKey( Employee, related_name="employee_app_access", on_delete=models.PROTECT, null=True, blank=True, ) access_type_dropdown = ( ("ADMIN", "ADMIN"), ("USER", "USER"), ) access_type = models.CharField( verbose_name="Access Type", max_length=30, blank=True, null=True, choices=access_type_dropdown, ) def __str__(self): return f"{self.app.application_name} - {self.employee.employee_user_name} - {self.access_type}" For example: I have 10 apps but only 2 of them have related data and I wanna show inly them. For example: I have 3 apps: app1 app2 app3 I have 2 values in QlikAppUserAccess model. Roni -> related to app1 Avi -> related to app2 So i need to see only app1 and app2. Thanks a lot. -
How to retrieve a constraint name in an existing database
In a migration, I want to remove an index from a table (before adding a new one). I can do that with a RunSQL and a DROP CONSTRAINT constraint_name, but it turns out that the name of the constraint (for the primary key) is not always the same, because it used to be named differently in the past. So I'm looking for a way to retrieve this constraint name, be it with the DJANGO ORM, or with a SQL request, so I can then remove it. -
I made a color model in django by installing and importing colorfield and it is working but when I am clicking in save button the color is not saving
In admin pannel color field screenshot------>color field screenshot when I am clicking save button(image---->save button ) it is not saving the color in the products(model) In my models.py:(app name:"core") from django.db import models from shortuuid.django_fields import ShortUUIDField from django.utils.html import mark_safe from userauths.models import CustomUser from colorfield.fields import ColorField class Color(models.Model): color = ColorField(default='#FF0000') class Meta: verbose_name_plural="colors" user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True,related_name="category") vendor=models.ForeignKey(Vendor, on_delete=models.SET_NULL,null=True) color = ColorField(image_field="image",default=None) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=models.TextField(null=True, blank=True,default="This is a product") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) specifications=models.TextField(null=True, blank=True) # tags=models.ForeignKey(Tags, on_delete=models.SET_NULL ,null=True) product_status=models.CharField(choices=STATUS, max_length=10,default="In_review") status=models.BooleanField(default=True) in_stock=models.BooleanField(default=True) featured=models.BooleanField(default=False) digital=models.BooleanField(default=False) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef") date=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(null=True,blank=True) class Meta: verbose_name_plural="Products" def product_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title def get_percentage(self): new_price=((self.old_price-self.price)/self.old_price)*100 return new_price In admin.py: from django.contrib import admin from core.models import * class ProductAdmin(admin.ModelAdmin): inlines=[ProductImagesAdmin] list_display=['user','title','product_image','price','featured','product_status','color'] class ColorAdmin(admin.ModelAdmin): list_display=['color'] admin.site.register(Product,ProductAdmin) admin.site.register(Color,ColorAdmin) In my code when I am clicking on save button my colors are not saving in the admin pannel other this are working perfectly. I am posting also my problem in a video. I am giving you the link YouTube (my Problem link): https://youtu.be/7CTPBAvJEDY -
Filter dropdown choices based on another fields value: [Django, django-smart-selects]
I want to show only relevant option in first_model_field dropdown based on values of product and product_state. When admin changes values of one of these fields in SecondModel, it should get only first_model_field choices that have same state and product. How can I get filtered FirstModel based on these two values without writing async JavaScript ? It should also change when one of these values changes in dropdown. class FirstModel(models.Model): product = models.ForeignKey("Product", on_delete=models.CASCADE) product_state = models.CharField(default=PRODUCT_STATE_START, choices=PRODUCT_CHOICES) class SecondModel(models.Model): product = models.ForeignKey("Product", on_delete=models.CASCADE) product_state = models.CharField(default=PRODUCT_STATE_START, choices=PRODUCT_CHOICES) first_model_field = ChainedForeignKey( FirstModel, on_delete=models.CASCADE, chained_field="product", chained_model_field="product", ) ps: Currently it only filters based on product field -
im getting an error on post and get method. im using django framework
[26/Feb/2024 13:03:35] "GET /registration/ HTTP/1.1" 200 6389 Method Not Allowed (POST): /registration/ Method Not Allowed: /registration/ [26/Feb/2024 13:03:44] "POST /registration/ HTTP/1.1" 405 0 try to get the user username and password on the database.but it showign error e.g method not allowed -
my serilazer not working , show "'Tag' object is not iterable" , could you help me
i am building my personal blogpost and i am using django rest framework to build my api i have problem with my tag Post_TagSerializer when i access to tag like python it show me error that i motion it the image above this is my code this is my serializer class Post_TagSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True) # Show names of associated tags postlist = PostSerializer(many=True, read_only=True) class Meta: model = Post_Tag fields="__all__" and this is my model from django.db import models # Create your models here. class Tag(models.Model): tName = models.CharField(max_length=100) _created = models.DateField() def __str__(self): return self.tName class Category(models.Model): cName = models.CharField(max_length=50) cDescription = models.CharField(max_length=250) def __str__(self): return self.cName class Post(models.Model): postName = models.CharField(max_length=200) postDescription = models.CharField(max_length=250) category_id = models.ForeignKey(Category, on_delete=models.CASCADE , related_name="postlist") release_date = models.DateField(auto_now_add=True) #tags = models.ManyToManyField(Tag) def __str__(self): return self.postName class Post_Tag(models.Model): postId = models.ForeignKey(Post , on_delete=models.CASCADE ,related_name="postlist") tags = models.ForeignKey(Tag, on_delete=models.CASCADE , related_name='tags') def __str__(self): return str(self.postId) and this is my view class TagPostAV(APIView): def get(self, request, tags): try: # Filter Post_Tag objects based on tags__tName tagpost = Post_Tag.objects.filter(tags__tName=tags) # Check if any results were found if not tagpost.exists(): return Response({'error': 'tag not found'}, status=status.HTTP_404_NOT_FOUND) # Create a serializer instance with many=True for multiple objects serializer … -
MetaApi profile issue
I am using MetaApi service to integrate MT5 account. Currently working with MT5 groups. Here is the API **https://mt-manager-api-v1.new-york.agiliumtrade.ai/users/current/mt5/provisioning-profiles/{profile_id}/groups ** When i use Manger API id it gives timeout error and when i use ProvisioningProfile id it give 403 error. Can any one help? I have given all the information correct like auth-token and profile id still not getting the required output. Any help would be appreciated. Thanks. -
Page not found (404) No Category matches the given query
When I click the add movie button its showing "Page not found (404) No Category matches the given query." error. it was working till I added a dropdown option to the website where movies are show with respect to the category selected. urls.py