Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a subdomain to a django URL?
I just have a simple question: How can I add a subdomain to my django url, like: forums.websitename.com or account.websitename.com? Since my URLS were starting to get messy, I would like to add subdomains to my website that is still in development. Thank you for all possible help. -
Error when trying to use 'platform login' command in Platform.sh
I'm trying to use platform.sh in my python virtual environment, but when I try to run 'platform login' in a command prompt to login, it will not work. The login browser page does open and says I logged in successfully, but the command prompt says '[RequestException] cURL error 60: SSL certificate problem: unable to get local issuer certificate'. Here is the full output of the command prompt (ll_env) C:\Users\david\PycharmProjects\pythonProject2\learning_log>platform login Opened URL: http://127.0.0.1:5000 Please use the browser to log in. Help: Leave this command running during login. If you need to quit, use Ctrl+C. Login information received. Verifying... [RequestException] cURL error 60: SSL certificate problem: unable to get local issuer certificate I tried quite a few things. I downloaded cacert.pem and set it up, and I also asked ChatGPT, who had no clue on what was going on. It kept presenting 'solutions' that would do nothing to help. -
Why does request.COOKIES periodically return an empty dict?
I set a cookie in my view like so: response.set_cookie( 'cookie_name', 'true', max_age=100000 ) The cookie sets ok, and is viewable in dev tools. I have a tag which checks for a specific cookie on every page load: @register.simple_tag(takes_context=True) def get_cookie_status(context): request = context['request'] print(request.COOKIES) Around 40% of the time, this prints an empty dictionary and I have absolutely no idea why. As I said above, Django picks up no cookies at all, but the loaded page has all of the expected cookies present. Is there any common reason why this would occur? -
Error while migrating. I am deploying my django app+telegram bot to heroku
I am deploying my django app+telegram bot to heroku. While migrating data to heroku, i am getting an error: C:\Users\Acer\brand_online\brand_online>heroku run python manage.py migrate --app brand-telegram Running python manage.py migrate on ⬢ brand-telegram... up, run.7513 (Basic) python: can't open file '/app/manage.py': [Errno 2] No such file or directory everything seems simple, but i am not writing /app/ before manage.py. I dont know where did it come from. Procfile: web: gunicorn brand_online.wsgi worker: python main.py How to fix? heroku run python C:\Users\Acer\brand_online\brand_online\manage.py migrate i tried to use detailed link to manage.py -
Date pickers should start on Monday instead of Sunday
I have a custom widget for date input: class JQueryUIDatepickerWidget(DateInput): def __init__(self, **kwargs): super().__init__( attrs={ "size": 10, "class": "datepicker", "autocomplete": "off", "placeholder": "Select date", }, **kwargs, ) but when I open date picker, it starts from Sunday, like: Su, Mo, Tu, We, Th, Fr, Sa. Can I update it to start on Monday? Might it be solved adding some JS or JQuery code to my base.html -
Django: Vendor Profile Not Detected Despite Being Created
I am working on a Django project where each user can have an associated vendor profile. I've created a vendor profile for a user, but when I try to access the vendor's shop, it always renders the no_vendor.html page, indicating that the vendor profile does not exist. View Function: Here is the view function where I attempt to retrieve the vendor profile: @login_required def vendor_shop(request): try: vendor = Vendor.objects.get(user=request.user) except Vendor.DoesNotExist: # Handle the case where the vendor does not exist return render(request, 'vendorpannel/no_vendor.html') # Redirect to a page or show a message all_products = Product.objects.filter(vendor=vendor) all_categories = Category.objects.all() context = { "all_products": all_products, "all_categories": all_categories, } return render(request, 'vendorpannel/shop.html', context) Models: Here are the relevant models: class Vendor(models.Model): vid=ShortUUIDField(length=10,max_length=100,prefix="ven",alphabet="abcdef") title=models.CharField(max_length=100,default="Nest") image=models.ImageField(upload_to=user_directory_path,default="vendor.jpg") cover_image=models.ImageField(upload_to=user_directory_path,default="vendor.jpg") description=RichTextUploadingField(null=True, blank=True,default="Normal Vendorco") address=models.CharField(max_length=100, default="6,Dum Dum Road") contact=models.CharField(max_length=100, default="+91") chat_resp_time=models.CharField(max_length=100,default="100") shipping_on_time=models.CharField(max_length=100,default="100") authenticate_rating=models.CharField(max_length=100,default="100") days_return=models.CharField(max_length=100,default="100") warranty_period=models.CharField(max_length=100,default="100") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) class Meta: verbose_name_plural="Vendors" def Vendor_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title class Product(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") 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,related_name="product") color=models.ManyToManyField(Color,blank=True) size=models.ManyToManyField(Size,blank=True) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=RichTextUploadingField(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=RichTextUploadingField(null=True, blank=True) tags=TaggableManager(blank=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 … -
ImproperlyConfigured` Error When Deploying Django to Vercel with Supabase PostgreSQL
I'm currently trying to deploy my Django project to Vercel, using Supabase as the PostgreSQL database provider. I have separated my settings into base.py, development.py, and production.py to manage environment-specific configurations. Problem: When attempting to migrate the database using python manage.py migrate, I encounter the following error: ```bash django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. ``` Setup Details: Database Configuration (production.py): from decouple import config import dj_database_url from urllib.parse import urlparse # Production-specific settings DEBUG = True # Parse the DATABASE_URL to extract components url = urlparse(config('DATABASE_URL')) # Configure your production database (example using PostgreSQL) DATABASES = { 'default': dj_database_url.config( default=config('DATABASE_URL') ) } # configure the database ENGINE to use the Postgres database DATABASES['default']['ENGINE'] = 'django.db.backends.postgresql' # Optional: Additional database settings DATABASES['default']['ATOMIC_REQUESTS'] = True # Cache configuration CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': config('UPSTASH_REDIS_REST_URL'), 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } # Static and media files settings for production STATIC_URL = '/static/' MEDIA_URL = '/media/' # Use proper email backend for production (e.g., SMTP) EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = config('EMAIL_HOST') EMAIL_PORT = config('EMAIL_PORT', default=587) EMAIL_HOST_USER = config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') # Cloudinary storage for production DEFAULT_FILE_STORAGE … -
Iterate through all the days in a month in DJANGO template
enter image description here I have a model table like above which contains two columns on which dates on which an item is being sold in a month. I want to show the entire month table in Django template instead of showing only the dates of sale, and on each day showing "yes" if the sale is there and keeping blank if no sale is there on that day. I.e How to iterate in Template through all the days in a month. How the code should be in Django "views.py" and in Template models.py class SaleDates(models.Model): date_of_sale = models.DateTimeField(blank=True, null=True) sold_choices = ( ('yes', 'yes'), ('no', 'no'), ) sold_status = models.CharField(max_length=9, choices=sold_choices,) template.html {% for item in list %} {% if forloop.first %} <table class="table table-hover table-bordered"> <tr> <th>Sl.NO</th> <th>date</th> <th>details</th> </tr> {% endif %} <tr> <td> {{ forloop.counter }} <br/> </td> <td> {{ item.date_of_sale }}</td> <td> {{ item.sold_status }} </td> </tr> {% if forloop.last %} </table> {% endif %} {% empty %} {% endfor %} -
Where to write queries in rest api, and how to secure it
I will make an application with Flutter. With Django, I will make a rest api to send data from mysql. I have never made an api before. In the tutorials I found, when I go to the api url, the whole database appears directly. My goal is to display the data in that url only in requests made via flutter. How do I make it hidden? In my second question, should I make the queries on flutter, or should I create a new url for each filtered query I will make in django. For example, if I have 200 queries, should I have 200 different url structures. I have not written any code yet, I am researching. -
Hello everyone! Does anyone know how I can georeference a png image with Gdal using Django?
I am trying to georeference a .png image with some control points, which would be the corner coordinates. I have achieved this using Gdal only with: from osgeo import gdal ds = gdal.Open(f'{filename}.png') gdal.Translate(filename + '.tif', ds, outputBounds=bounds) but when I try to put this in my DJANGO API I can't because Django GDAL doesn't have the gdal.translate method. Does anyone know what the equivalent of this function is in Django gdal or how can I georeference a png image with boundaries using django? -
CSV file not found error in html file in pyscript tag . Running this html file in python Django web framework
I am learning python django web framework . Reading csv file content and showing in pandas dataframe but getting error file not found. Tried all possible options using latest , alpha pyscript release . Tried absolute path as well as relative path . When running index.html it gives csv file not found error . CSV file is alreday there in the directory where index.html is located . <py-env> -numpy - pandas - paths: - ./customer.csv </py-env> import pandas as pd import numpy as np df = pd.read_csv("./customer.csv") print(df.head()) -
Only first placeholder displayed in Django's UserCreationForm
I'm trying to make a sign-up page with a customized user creation form - add placeholders to the fields. I'm trying to do it this way: forms.py class SignUpForm(UserCreationForm): email = EmailField(max_length=200) class Meta: model = User fields = UserCreationForm.Meta.fields + ("password1", "password2", "email") widgets = { 'username': TextInput(attrs={'placeholder': 'Username'}), 'email': EmailInput(attrs={'placeholder': 'Email'}), 'password1': PasswordInput(attrs={'placeholder': 'Password'}), 'password2': PasswordInput(attrs={'placeholder': 'Repeat password'}), } However, it only affects the username's placeholders - the other ones are unaffected. What I've tried doing was to add the placeholder to the declaration of the email variable, which works. However, there has to be a simpler way to do it, and - even if I'd do that the passwords would still not have placeholders. I have also tried to make the fields variables, like email = CharField(TextInput(attrs{'placeholder': 'Email'}), but that didn't help too. Tried doing it as in the "Adding placeholder to UserCreationForm in Django" thread, but that didn't change anything. Other threads too, that's probably due to Django's version. Each time before trying it out I delete the site's browsing data to make sure it's not a client-side problem. -
When deploying Django to prod, Gunicorn lives in the virtual environment, but we deactivate the virtual environment when we go live with Nginx
I've been following a few tutorials online on how to setup Django, Postgres, Gunicorn and Nginx in production. I noticed that it is always recommended to install all Python dependencies inside the virtual environment. This includes Gunicorn. For example, we fire up our virtual environment initially, then execute the 'manage.py runserver 0.0.0.0:8000' command, we then test if Gunicorn binds to it. Once we see that Gunicorn works we then deactivate our virtual environment to start configuring Nginx. It is never mentioned to enable our virtual environment again. How is Gunicorn able to process requests when it lives inside the virtual environment, which had been deactivated? I assume there is a mechanism somewhere wherein the virtual environment is enabled again automatically. But where and when is the virtual environment enabled? I mean, how is it enabled? I've tried looking for answers online and in tutorials, but I still can't find anything that explains it fully. -
User is not created in django when making a request
I try to make some requests to django, all is working fine, but a user is not created. import json import requests url = 'http://127.0.0.1:8000/register/' for i in range(10): s = requests.Session() r1 = s.get(url) csrf = r1.cookies['csrftoken'] data = { 'csrfmiddlewaretoken': csrf, 'username-input': f'111111111{i}', 'email-input': f'111{i}1@gmail.com', 'password-input': '1111', 'password-input-verify': '1111' } r2 = s.post(url, data=data) print(r2.status_code) please help !!!!!!!!!!!! -
Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>: In my React Native, Django-restframework
I have setup my RTK Query in React Native (expo-router)/File based here files rtk/api.ts: import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"; export const api = createApi({ baseQuery: fetchBaseQuery({ baseUrl: "http://127.0.0.1:8000/" }), endpoints: (builder) => ({ signUp: builder.mutation({ query: (userData) => ({ url: "accounts/signup/", method: "POST", body: userData, }), }), login: builder.mutation({ query: (credentials) => ({ url: "accounts/login/", method: "POST", body: credentials, }), }), logout: builder.mutation({ query: () => ({ url: "accounts/logout/", method: "POST", }), }), passwordReset: builder.mutation({ query: (data) => ({ url: "accounts/password_reset/", method: "POST", body: data, }), }), passwordResetConfirm: builder.mutation({ query: (data) => ({ url: `accounts/password_reset_confirm/${data.uidb64}/${data.token}/`, method: "POST", body: data, }), }), changePassword: builder.mutation({ query: (data) => ({ url: "accounts/change_password/", method: "POST", body: data, }), }), userVerification: builder.mutation({ query: (data) => ({ url: "accounts/user_verification/", method: "POST", body: data, }), }), userVerificationConfirm: builder.mutation({ query: (data) => ({ url: `accounts/user_verification_confirm/${data.idb64}/${data.token}/`, method: "POST", body: data, }), }), addPhone: builder.mutation({ query: (data) => ({ url: "accounts/phone/add/", method: "POST", body: data, }), }), addEmail: builder.mutation({ query: (data) => ({ url: "accounts/email/add/", method: "POST", body: data, }), }), }), }); export const { useSignUpMutation, useLoginMutation, useLogoutMutation, usePasswordResetMutation, usePasswordResetConfirmMutation, useChangePasswordMutation, useUserVerificationMutation, useUserVerificationConfirmMutation, useAddPhoneMutation, useAddEmailMutation, } = api; rtk/store.ts import { configureStore } from "@reduxjs/toolkit"; import { … -
How to aggregate nested manytomany relationships in django orm
Given the pseudo definitions: class User: name: string class Account: owner: foreignkey(User, related_name="accounts") class Transactions: type: Enum(1,2,3) account: foreignkey(Account, related_name="transactions" value: Int How do I write this query using django ORM? SELECT user.id, type, AVG(value) as type_average FROM user JOIN account ON account.owner = user.id JOIN transactions ON transactions.account = account.id GROUP BY user.id, type -
How to use postgres' ARRAY in django orm
In postgresql, I am able to combine two columns into one into an array like so SELECT id, ARRAY[address,zip] as address_array FROM user Is there a way to do this using django's orm? Why? I want to be able to transform it into a dict mapping like users = dict(User.objects.values("id", "address").all()) Gives me a mapping of: { 1: "Address 1", 2: "Address 2", ... ... } And ultimately I want: { 1: ["Address 1", "Zip 1"], 2: ["Address 2", "Zip 2"], } I am looking for a solution using django's orm, not python. I know I can do this by using python code after looping through the queryset. -
Is there a way to get a user instance in template with async view?
I need to get user instance in my templates using async view {{ request.user }} or {{ request.auser }}/ Of course i can user something like this: async def view(request): user = await request.auser() return render(request, 'template.html', {'user': user} but is there a other way to get it? -
Managing SSO for Multi-Domain and Local Deployments in a Django Application?
I am developing a Django application that will be offered in a marketplace. Each customer will have a unique domain, differentiated at least by prefixes. I have integrated Single Sign-On (SSO) for authentication. I have two specific questions regarding SSO management in this multi-domain setup: Domain Registration with SSO Providers: For each new customer, do I need to manually register each new domain with the SSO provider, or is there a method within Django or the SSO provider's services that can automate this process? Local Deployment SSO Configuration: I plan to allow customers to optionally run the application locally. I've noticed that SSO providers differ in their local testing configurations, with Google using 127.0.0.1 and Microsoft using localhost. How can I accommodate these differences in a seamless manner? Thanks in advance👍 For now I don't have any extra domains, so it is working properly...so just wanted to know about this when I try out. -
Django NoReverseMatch error: Reverse for 'vendor_pannel1' with arguments '('prdbececfaabd',)' not found
I'm getting a NoReverseMatch error in my Django project, and I'm not sure how to fix it. Here's the error message: NoReverseMatch at /vendorpannel/edit_product/prdbececfaabd Reverse for 'vendor_pannel1' with arguments '('prdbececfaabd',)' not found. 1 pattern(s) tried: ['vendorpannel/vendor_pannel1/\\Z'] Here's my code: views.py: @login_required def edit_product(request, pid): product = get_object_or_404(Product, pid=pid) if request.method == "POST": form = AddProductForm(request.POST, request.FILES, instance=product) if form.is_valid(): new_form = form.save(commit=False) new_form.user = request.user # assuming there is a user field in the Product model new_form.save() form.save_m2m() # Save many-to-many relationships return redirect("vendorpannel:vendor_pannel1",product.pid) else: # Print form errors for debugging print(form.errors) else: form = AddProductForm(instance=product) context = { "form": form, "product": product, } return render(request, "vendorpannel/edit-product.html", context) urls.py: from django.urls import path from vendorpannel import views app_name = 'vendorpannel' urlpatterns = [ path('vendor_pannel1/', views.vendor_pannel1, name='vendor_pannel1'), path('vendor_signup/', views.vendor_signup, name='vendor_signup'), path('login_view/', views.login_view, name='login_view'), path('vendor_shop/', views.vendor_shop, name='vendor_shop'), path('vendor_tickets/', views.vendor_tickets, name='vendor_tickets'), path('vendor_user/', views.vendor_user, name='vendor_user'), path('vendor_settings/', views.vendor_settings, name='vendor_settings'), path('add_product/', views.add_product, name='add_product'), path('edit_product/<str:pid>', views.edit_product, name='edit_product'), ] in html template: <form method="POST" enctype="multipart/form-data" action="{% url 'vendorpannel:edit_product' product.pid %}"> Additional context: 1.I'm using Django 3.2.5 2.I've checked my URL patterns and views, and they seem to be correct 3.I've tried reversing the URL with and without the vendorpannel: namespace prefix Any help would be appreciated! -
How to pull out the most similar words in DRF and Postgres?
My backend server consists of drf and postgres. What I want to do is, if any keyword comes from the client, the result is the B field value in the A table that is most similar to it. Therefore I wanted to use trigram_similar and it worked, but I can't use pg_trgm anymore because the service has to support Korean. How do I resolve this? -
How to run Django test names verbosely without displaying too much logging
I would like to run the tests in my Django project, displaying the test names, but without displaying the logging output of the database migrations. If I do not pass the -v 2 flag, then I don't get to see the test names, which I want to see: $ python manage.py run test Found 1 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). . ---------------------------------------------------------------------- Ran 1 test in 0.053s OK Destroying test database for alias 'default'... However, if I pass the flag -v 2 to increase the verbosity level, then I see both the test names and the logging information from the database migrations: $ python manage.py test -v 2 Found 1 test(s). Creating test database for alias 'default' ('test_projectname')... Operations to perform: Synchronize unmigrated apps: allauth, django_browser_reload, django_extensions, forms, google, hijack, hijack_admin, messages, runserver_nostatic, simple_deploy, staticfiles Apply all migrations: account, admin, auth, contenttypes, sessions, sites, socialaccount Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK # ... cut for brevity System check identified no issues (0 silenced). test_hello (projectname.test_login.LoginTest.test_hello) ... ok ---------------------------------------------------------------------- … -
django.db.utils.DatabaseError: DPY-4027: no configuration directory to search for tnsnames.ora in my dockerized django application
I am trying to connect my django application with an oracle database in vain. I added the TNS_ADMIN environment variable but the problem persists. Here is the content of my tnsnames.ora file: # tnsnames.ora Network Configuration File: C:\app\HP\product\21c\homes\OraDB21Home1\NETWORK\ADMIN\tnsnames.ora # Generated by Oracle configuration tools. XE = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = xxx)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = XE) ) ) LISTENER_XE = (ADDRESS = (PROTOCOL = TCP)(HOST = xxx)(PORT = 1521)) ORACLR_CONNECTION_DATA = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521)) ) (CONNECT_DATA = (SID = CLRExtProc) (PRESENTATION = RO) ) ) It should be noted that I use SQL developer. My database configuration in django: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': os.environ.get("DB_NAME"), 'USER': os.environ.get("DB_USER"), 'HOST': os.environ.get("DB_HOST"), 'POSRT': os.environ.get("DB_PORT"), 'PASSWORD': os.environ.get("DB_PASS") } } docker-compose.yml file: version: '3' services: backend: container_name: bdr-backend build: context: . command: > sh -c "python manage.py makemigrations --noinput && python manage.py migrate --noinput && python manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 volumes: - ./backend:/backend env_file: - .env environment: - DEBUG=1 - DB_HOST=${DB_HOST} - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} depends_on: - redis redis: image: redis:7.0.5-alpine container_name: redis2 expose: - 6379 I use docker docker desktop … -
django {% url "home" %} name conflict, why? It shouldn't
In a new django project I came a cross a conflict of names in the url when intheory shouldn't be. the path of the two urls are different, but the name the same. It is easy to fix, changing the name, but I would like to understand why there is conflict when to me it shouldn't. The problme is in the {% url 'home' %}. <a class="navbar-brand" href="{% url "home" %}">CRM</a> urls.py of the project: urlpatterns = [ path('admin/', admin.site.urls), path('',views.home, name='home'), <---------'localhost:8000/' path('CRMapp/', include('CRMapp.urls')), ] urls.py of app: urlpatterns = [ path('', views.home, name='home'), <---------'localhost:8000/CRMapp/' path('hello/', views.hello, name='hello') ] views.py of app: (in theory triger when localhost:8000/CRMapp/ def home(request: HttpRequest): return render(request,'home.html',{}) views.py of project deliver when localhost:8000/: def home(request: HttpRequest): # return HttpResponse('home') return render(request,'home.html',{}) html of the nav: Both {% url "home" %} deliver localhost:8000/CRMapp/, when they should deliver localhost:8000/ <a class="navbar-brand" href="{% url "home" %}">CRM</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{% url "home" %}">Home</a> here the order list of routes that django-extentions show: / djangoCRM.views.home home /CRMapp/ CRMapp.views.home home /CRMapp/hello/ CRMapp.views.hello hello /admin/ django.contrib.admin.sites.index … -
How can i "add" additional Data (Classification-Codes) to an existing Field
I have build a model which should representate our Products at work. Our products are different sorts of luminaires. Some of these with different variations like different colour-temperature, different housing-colour, different power, sensors or dimmable. at the moment my model looks (a little shortend) like this class ProductID(models.Model): product_id = models.CharField(max_length=100, unique=True) base_model = models.BooleanField(default=True) active = models.BooleanField(default=True, choices=CHOICES) possible_as_option = models.BooleanField(default=False, choices=CHOICES) product_variant_data = models.ForeignKey('ProductVariantData', on_delete=models.PROTECT) ... class ProductVariantData(models.Model): short_text = models.CharField(max_length=300, null=True, blank=True) packaging_unit = models.IntegerField(validators=[MinValueValidator(1)]) guarantee = models.IntegerField() product = models.ForeignKey('Product', null=True, on_delete=models.PROTECT) ... class Product(models.Model): enec = models.BooleanField(default=False) ce = models.BooleanField(default=True) min_ambient_temperature = models.IntegerField() max_ambient_temperature = models.IntegerField() ip_code = models.ForeignKey(IPCode, on_delete=models.PROTECT) ik_code = models.ForeignKey(IKCode, on_delete=models.PROTECT) dimensions = models.ForeignKey(Dimensions) cutout_dimensions = models.ForeignKey(CutoutDimensions, null=True) product_type = models.ForeignKey(ProductType, on_delete=models.PROTECT) .... class LEDData(models.Model): led_changeable = models.BooleanField(default=True) average_lifespan = models.IntegerField(null=True, blank=True) dimmable = models.BooleanField(default=False) voltage = models.DecimalField(max_digits=5, decimal_places=2, null=False) flicker_metric = models.DecimalField(max_digits=2, decimal_places=1, null=True) stroboscopic_effect_metric = models.DecimalField(max_digits=2, decimal_places=1, null=True) class LEDData(models.Model): average_lifespan = models.IntegerField() dimmable = models.BooleanField(default=True) voltage = models.DecimalField(max_digits=5, decimal_places=2, null=False) flicker_metric = models.DecimalField(max_digits=2, decimal_places=1, null=True) stroboscopic_effect_metric = models.DecimalField(max_digits=2, decimal_places=1, null=True) class Luminaire(models.Model): product = models.OneToOneField(Product, primary_key=True) control_gear_included = models.BooleanField(default=True) external_control_gear = models.BooleanField(default=True) control_gear_changeable = models.BooleanField(default=True) control_gears = models.ManyToManyField('ControlGear', through='LuminaireControlGearDetails') led_data = models.ForeignKey(LEDData) lighting_technology = models.CharField(max_length=15, choices=LightingTechnology, default=LightingTechnology.LED) ... class …