Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How pass data from template to Updateview
I'm very new to programming. I would like to pass data from html input to update view and then save it to my database. Tried to search for it but with no luck. Here is my html code: <form action="{% url 'darbai:taskasupdate' pk=taskas.pk %}" method="POST"> {% csrf_token %} <input type="text" name="pavad"> <input type="text" name="atsak"> <button type="submit"/>Update</button> </form> Here is my model: class Taskas(models.Model): pavadinimas = models.CharField(max_length=30, null=True, blank=True) atsakingas = models.CharField(max_length=30, null=True, blank=True) Here is my urls: urlpatterns = [ path('', CreateList.as_view(), name='CreateList'), path('delete/<int:pk>', TaskasDeleteView.as_view(), name='taskasdelete'), path('update/<int:pk>', TaskasUpdateView.as_view(), name='taskasupdate'), ] Here is my view: class TaskasUpdateView(UpdateView): model = Taskas form_class = TaskasForm success_url = reverse_lazy('darbai:CreateList') def post(self, request, **kwargs): self.object = self.get_object() request.POST['pavad'] = self.object.pavadinimas request.POST['atsak'] = self.object.atsakingas -
How to pull variables of the main class from a subclass in django
I have a filter code for the site: def buy_files(request): bdfiles = FeedFile.objects.all() # bdfiles = UploadFile.objects.all() form = FileFilterForm(request.GET) if form.is_valid(): if form.cleaned_data["number_course"]: bdfiles = bdfiles.filter(number_course = form.cleaned_data["number_course"]) if form.cleaned_data["number_semestr"]: bdfiles = bdfiles.filter(number_semestr = form.cleaned_data["number_semestr"]) if form.cleaned_data["subjectt"]: bdfiles = bdfiles.filter(subjectt = form.cleaned_data["subjectt"]) if form.cleaned_data["type_materials"]: bdfiles = bdfiles.filter(type_materials = form.cleaned_data["type_materials"]) if form.cleaned_data["institute"]: bdfiles = bdfiles.filter(institute = form.cleaned_data["institute"]) return render(request, 'chat/files/buyfile.html', {'bdfiles': bdfiles, 'form':form}) And models.py: class UploadFile(models.Model): user = models.ForeignKey(User,on_delete = models.CASCADE,related_name='file_created' ,verbose_name='Автор') title = models.CharField(max_length=200, verbose_name='Заголовок') # uploadedfile = models.FileField(upload_to='files/',null=True, verbose_name='Файл') description = models.TextField(blank=True, verbose_name='Описание') createdtime = models.DateField(auto_now_add=True, db_index=True, verbose_name='Дата создания') price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='Цена') number_course = models.IntegerField(null=True, blank=True, verbose_name='Курс') number_semestr = models.IntegerField(null=True, blank=True, verbose_name='Семестр') subjectt = models.CharField(max_length=200, null=True,verbose_name='Предмет') type_materials = models.CharField(max_length=200,null=True, verbose_name='Тип работы') institute = models.CharField(max_length=200, null=True, verbose_name='Институт') def __str__(self): return self.title class Meta: verbose_name = 'Загрузка файла' verbose_name_plural = 'Загрузка файлов' class FeedFile(models.Model): file = models.FileField(upload_to="files/") feed = models.ForeignKey(UploadFile, on_delete=models.CASCADE) When I start entering data in the filter on the html page, an error occurs that there are no fields number_semestr, number_course and so on, but there are only fields feed, feed_id, file, id. HTML code of the page: <form action="" method="get" style="width:90%"> {% csrf_token %} <!-- {{form|crispy}}--> <p><label class="form-label" for="{{ form.number_course.id_for_label }}">Курс: </label> … -
DRF Authentication is not working in frontend
So, I created registration app. I added registration API, Login API and User profile API. I tested three API's in Postman it is giving results. In my project I used djangorestframework-simplejwt authentication. When I test with browser it is not working what I have to do please anyone can help me out to achieve this. In settings.py # JWT Configuration REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } # JWT Settings SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=20), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', } INSTALLED_APPS = [ ......... 'rest_framework_simplejwt', ......... ] In Views.py class UserLoginView(APIView): def post(self, request, format=None): q = QueryDict(request.body) query_dict = q.dict() json_object = json.dumps(query_dict, indent=4) reqBody = json.loads(json_object) email = reqBody['email'] password = reqBody['password'] user = authenticate(email=email, password=password) print('user') print(user) if user is not None: token = get_tokens_for_user(user) Account = customer.objects.get(email=email) request.session['email'] = Account.email request.session['id'] = Account.id request.session['name'] = Account.firstname request.session['cust_status'] = Account.cust_status request.session['os_name'] = Account.os_name request.session['user_type'] = Account.flag request.session['username'] = str(Account.firstname) + str(Account.lastname) return Response({'token': token, 'msg': 'Login Success'}, status=status.HTTP_200_OK) else: return Response({'errors': {'non_field_errors': ['Email or Password is … -
How to Join Subqueries in Django ORM
I'm a beginner Django and I have been stuck on the following problem for a while. The basic thing I would like to achieve is that when client makes a GET list api request with a time period parameter (say 3 months) then the server would return an aggregation of the current 3 months data and also show an extra field comparing the difference with previous 3 months. I have models as: class NTA(models.Model): nta_code = models.CharField(max_length=30, unique=True) ... class NoiseComplaints(models.Model): complaint_id = models.IntegerField(unique=True) created_date = models.DateTimeField() nta = models.ForeignKey( NTA, on_delete=models.CASCADE, to_field='nta_code') ... The sample output I would like to get is something like: [ { "id": 1, "nta_code": "New York", "noise_count_current": 30, # this would be current 3m count of NoiseData "noise_count_prev": 20, # this would be prev 3m count of NoiseData "noise_count_diff": 10, # this would be prev 3m count of NoiseData } ... The raw SQL query (in Postgres) is quite simple as below but I'm really struggling on how to make this work in Django. WITH curr AS ( SELECT "places_nta"."id", "places_nta"."nta_code", COUNT("places_noisecomplaints"."id") AS "noise_count_curr" FROM "places_nta" INNER JOIN "places_noisecomplaints" ON ("places_nta"."nta_code" = "places_noisecomplaints"."nta_id") WHERE "places_noisecomplaints"."created_date" BETWEEN '2022-03-31 00:00:00+00:00' AND '2022-06-30 00:00:00+00:00' GROUP BY "places_nta"."id" … -
Multiple container app: execute container from another container
I have a multi container Django app. One Container is the database, another one the main webapp with Django installed for handling the front- and backend. I want to add a third container which provides the main functionality/tool we want to offer via the webapp. It has some complex dependencies, which is why I would like to have it as a seperate container as well. It's functionality is wrapped as a CLI tool and currently we build the image and run it as needed passing the arguments for the CLI tool. Currently, this is the docker-compose.yml file: version: '3' services: db: image: mysql:8.0.30 environment: - MYSQL_DATABASE=${MYSQL_DATABASE} - MYSQL_USER=${MYSQL_USER} - MYSQL_PASSWORD=${MYSQL_PASSWORD} - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD} - TZ=${TZ} volumes: - db:/var/lib/mysql - db-logs:/var/log/mysql networks: - net restart: unless-stopped command: --default-authentication-plugin=mysql_native_password app: build: context: . dockerfile: ./Dockerfile.webapp environment: - MYSQL_NAME=${MYSQL_DATABASE} - MYSQL_USER=${MYSQL_USER} - MYSQL_PASSWORD=${MYSQL_PASSWORD} ports: - "8000:8000" networks: - net volumes: - ./app/webapp:/app - data:/data depends_on: - db restart: unless-stopped command: > sh -c "python manage.py runserver 0.0.0.0:8000" tool: build: context: . dockerfile: ./Dockerfile.tool volumes: - data:/data networks: net: driver: bridge volumes: db: db-logs: data: In the end, the user should be able to set the parameters via the Web-UI and run the tool container. … -
Django LDAP search problems
Server Error AUTH_LDAP_USER_SEARCH must be an LDAPSearch instance. Trying to setup Netbox here. Seems like a really cool tool, if I could ever get it working properly due to operator error. I am able to get a login portal when I host the server insecurely -- I have it set to where you must sign in before seeing anything. When I enter a username and password for the super user, or any text, here is what I get. <class 'django.core.exceptions.ImproperlyConfigured'> AUTH_LDAP_USER_SEARCH must be an LDAPSearch instance. Python version: 3.10.4 NetBox version: 3.2.8 Here is two parts of my config file, note that name, user and passwords have been changed. DATABASE = { 'NAME': 'myName', # Database name 'USER': 'myUsername', # PostgreSQL username 'PASSWORD': 'myPass', # PostgreSQL password 'HOST': 'localhost', # Database server 'PORT': '', # Database port (leave blank for default) 'CONN_MAX_AGE': 300, # Max database connection age # Remote authentication support REMOTE_AUTH_ENABLED = True REMOTE_AUTH_BACKEND = 'netbox.authentication.LDAPBackend' REMOTE_AUTH_HEADER = 'HTTP_REMOTE_USER' REMOTE_AUTH_AUTO_CREATE_USER = True REMOTE_AUTH_DEFAULT_GROUPS = [] REMOTE_AUTH_DEFAULT_PERMISSIONS = {} I would appreciate any help/advice you all have to offer. Thanks. -
visual studio code debug configuration for django doesnt recognize test files
I have a standard project setup where my test.py inside of the app folders. When I manually run py manage.py test it recognizes my test files. When using this debug config, it wont run the tests. Found 0 test(s). System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK How can I set them up correctly? launch.json: { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}\\django_project\\manage.py", "args": [ "test" ], "django": true, "justMyCode": true }, -
Trying to add items in list of lists of tuples
I am making a game picking app and I am stuck on trying to get a summary of points for users. The list is consisting of 18 lists (weeks) with all users and their respective points, sorted alphabetically. I don't know how to create a list with user---> all points combined. Here is an example with only 2 users [[('user1', 25), ('user2 ', 18)], [('user1', 18), ('user2 ', 25)], [('user1', 18), ('user2 ', 25)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)]] -
how to display all the post if url has this id in django templates
<div class="wilipedia-overview__list"> {% for lexicon_item_obj in lexicon_item_obj.all %} <div id="wilipedia-item-{{ lexicon_item_obj.id }}" class="wilipedia-item js-wilipedia-item{% if forloop.counter > 8 %} hidden {% endif %}" data-filter="{% for lexicon_key in lexicon_item_obj.lexicon_key_set.all %}{{ lexicon_key.title }}{% endfor %}"> <div class="wilipedia-item__title"> <h5>{{ lexicon_item_obj.title }}</h5> </div> <div class="wilipedia-item__desc"> {{ lexicon_item_obj.description }} </div> <a href="#" class="js-load-more" style="display: none" data-load-more="Load more" data-load-less="Load less">Load more</a> </div> {% endfor %} </div> {% if lexicon_item_obj.count > 8 %} <a href="#" class="wilipedia-overview__show-all btn --btn-black js-show-all">Show more</a> {% endif %} </div> enter image description here I am implementing the search functionality and search items on base of id and here I want to check url if url has id 12 or more I want to disable the button and dispaly all the items. Anyone has an idea how to do that? -
Permission Denied Error on linux server only, same code works well on windows?
In my project, I have used google drive API. Using google API, I want to create folders and upload some files to a particular folder. When a new company is added to the database, I want to create folders related to that company. The whole code is working on windows perfectly. But in Linux, while creating a folder on the drive it shows permission denied [Error 13]. The actual error comes in the following place: if not os.path.exists(os.path.join(working_dir, token_dir)): os.mkdir(os.path.join(working_dir, token_dir)) Traceback (most recent call last): File "/home/admin/webkorradmin/envwebkorradmin/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/admin/webkorradmin/envwebkorradmin/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/admin/webkorradmin/webkorradmin/invoice_generator/views.py", line 497, in add_company service = init_drive_service() File "/home/admin/webkorradmin/webkorradmin/invoice_generator/google_drive/drive.py", line 14, in init_drive_service service = create_service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES) File "/home/admin/webkorradmin/webkorradmin/invoice_generator/google_drive/Google.py", line 24, in create_service os.mkdir(os.path.join(working_dir, token_dir)) Exception Type: PermissionError at /invoice/add-company/ Exception Value: [Errno 13] Permission denied: '/token files' -
How to get data between two dates by getting from inputs?
I'm trying to filter my table with the user inputs. I create a filter that allows the users to choose 2 dates (YYYY-MM-DD). I can reach the input data like: 2022-08-19 2022-08-31 and I have a Case model. I want to get the cases created between these two dates. views.py year_one = self.request.GET.get('year_one') year_two = self.request.GET.get('year_two') cases = Case.objects.filter(date_created=.....).values(fieldname).order_by(fieldname).annotate(the_count=Count(fieldname)) -
How to get access to field using many to many and 'through' in Django?
I need to get the name from ProjectProgramGroup model starting from Project model. I tried to do somenting like this: @property def project_groups(self): return self.project.project_groups but it returns: projects.ProjectProgramGroup.None My models: class Project: short_name = models.CharField(verbose_name='short name', max_length=255) project_groups = models.ManyToManyField('ProjectProgramGroup', through='ProjectGroupRelation') class ProjectGroupRelation: project = models.ForeignKey(Project, on_delete=models.CASCADE) group = models.ForeignKey(ProjectProgramGroup, on_delete=models.CASCADE, verbose_name='group') class ProjectProgramGroup(): name = models.CharField('name', max_length=255) -
How can I get user question from a view that already has a slug
I'm trying to get a user question from public_profile view that uses slug to get user profile information, and now I wanted to get user question in the public_profile view that uses slug, but it gives me Page not found (404) error. I want a users to be able to see other user question in their profile page. How can I solve this problem to get users question when someone visited their profile page? Question model: class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, null=False) body = RichTextField(blank=False, null=False) category = models.ForeignKey(Category, on_delete=models.CASCADE) slug = models.SlugField(unique=True, max_length=200) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Question, self).save(*args, **kwargs) def __str__(self): return str(self.title) The view: @login_required(login_url='login') def public_profile(request, slug): profile = get_object_or_404(Profile, slug=slug) questions = get_object_or_404(Question, slug=slug) number_of_likes = Like.objects.filter(post__user=request.user).count() try: number_of_likes = Like.objects.filter(post__user=profile.user).count() except ObjectDoesNotExist: number_of_likes = None context = { 'profile':profile, 'number_of_likes':number_of_likes, 'questions':questions } return render(request, 'public_profile.html', context) my template: <div class="container"> <div class="row justify-content-center"> <div class="col"> <ul class="list-group"> <li class="list-group-item">{{question.title}}</li> </ul> </div> </div> </div> urls: path('userProfile/<slug:slug>/', views.public_profile, name='Public_Profile'), -
Verifying AzureAD access token with Django-REST-framework
Before anything I would like to warn you about my extremely limited knowledge on the subject. Now that you've been warned, what I need to ask is how can I verify and azureAD access token with Django/django-rest-framework. I have a app that I need to sing in to with azureAD, which means I need to get an access token from azureAD, and thankfully this is will be done on the frontend side with Angular what I need to do is verify that token on the backend side with django/django-rest-framework and I have no idea where to start from, can anyone suggest a way to do this or send me in the right direction ? Thank you very much. -
Django/Flask : Rewritting an Flask Azure B2C authentication in Django, issue with the scope
I want to use and Azure B2C authentication in Django, however there is no tutorial in Django for it but in Flask. However I never coded in Flask. I used the documentation/tutorial of microsoft that share a github with the flask code to do it : https://docs.microsoft.com/en-us/azure/active-directory-b2c/configure-authentication-sample-python-web-app?tabs=windows I try to convert it in Django but I have two issues. One is one line in Flask that I am not sure to understand well its role and how to rewrite it in Django. The second one is the scope of the input variables that do not work. Here is the code how I converted : views.py from django.shortcuts import render, redirect import msal import os from dotenv import load_dotenv load_dotenv() def index(request) : if not request.session.get("user"): return redirect("login") return render('index.html', user=request.session["user"] ) def login(request): print(os.getenv("SCOPE")) # Technically we could use empty list [] as scopes to do just sign in, # here we choose to also collect end user consent upfront request.session["flow"] = _build_auth_code_flow(scopes=os.getenv("SCOPE")) return render("login.html", auth_url=request.session["flow"]["auth_uri"], ) def authorized(request): try: cache = _load_cache(request=request) result = _build_msal_app(cache=cache).acquire_token_by_auth_code_flow( request.session.get("flow", {}), request.args) if "error" in result: return render("auth_error.html", result=result) request.session["user"] = result.get("id_token_claims") _save_cache(cache=cache, request=request) except ValueError: # Usually caused by CSRF pass # … -
How to run single Django project on multiple static IP address in docker
Here, this project works fine. This project is opening only on single static IP address. The problem is I want to open this project on multiple static IP address in docker. Can anyone tell me how to do this? This help will be good for me. Please help. docker-compose.yml: version: '3.9' services: app: build: context: . args: - DEV=true ports: - '8000:8000' volumes: - ./app:/app - dev-static-data:/vol/web command: > sh -c 'python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000' environment: - DB_HOST=db - DB_NAME=devdb - DB_USER=postgres - DB_PASS=m@noj5078 - DEBUG=1 depends_on: - db db: image: postgres:13-alpine volumes: - dev-db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=devdb - POSTGRES_USER=postgres - POSTGRES_PASSWORD=m@noj5078 volumes: dev-db-data: dev-static-data: proxy/default.conf.tpl server { listen ${LISTEN_PORT}; location /static { alias /vol/static; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } -
user is anonymous despite the user is logged in
I hope you are fine. I have a project using vue and django rest and I have done the authentication by djoser. When a user logs in, a token would be set and the user can login to the website correctly but in views.py when I use self.request.user in get_queryset(self) function it says that the user is anonymous. I will thank if anyone give me a piece of advice. Thanks. -
Why homebrew installs everything in /opt/homebrew/Cellar, while my python project looks for everything in /usr/local
I'm new to macos using Monterey on an M2 macbook Air, and having a hard time satisfying dependencies for a django project. To make it clean and simple, I've build python 3.8 from source, --with-openssl=/also/built/from/source, created a bin/python -m venv django, went source ./django/bin/activate, and installed the project requirements.txt. After running a project, i keep encountering missing library errors, like '/usr/local/lib/libssl.1.1.dylib' (no such file) '/usr/local/lib/libcairo.2.dylib' (no such file) '/usr/local/lib/libffi.8.dylib' (no such file) etc. Even though in the case of libssl for example, i would have expected python to know the location of the custom built openssl, i've went ahead and installed these system dependencies with brew install openssl@1.1 cairo libffi etc. but the errors persisted until i linked (ln -s) each library from /opt/homebrew/Cellar/libffi/3.4.2/lib/libffi.8.dylib to /usr/local/lib/libffi.8.dylib. Why is all this happening? Why is homebrew not populating a static library path? -
execute for loop for a dictionary key
This kind of data i have sent to my template x = [{'id': 668, 'title': 'ME2: Pressurisation Unit Maintenance Record', 'valuess': ['person', 'address', 'asset']} return render(request, 'xyz.html', {'data': x}) want to run a for loop for a key named 'values' in my data set x "x" is a key but it contains list of values as well. So want to run a for loop on a key "values" How to do this. anyone please help....I just started my programming career...i am stucked plz help me -
Run Django's model makemigration from package
I have different package's structure and i want to run makemigration and then migrate but it doesn't work. i have app user_app and models package where is my custom user model's file. when i run makemigration i have this - > No changes detected in app 'user_app' what i can do? it's my project structure user.py from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.core.exceptions import ValidationError from user_app.const import STATUS_CHOICES def validate_length(value): if len(str(value)) != 11: raise ValidationError(('Passport must be 11 digit!')) class MyUserManager(BaseUserManager): def create_user(self, email, last_name, first_name, passport_id, password=None): if not email: raise ValueError('Email is required') elif not last_name: raise ValueError('Last name is required') elif not first_name: raise ValueError('First name is required') elif not passport_id: raise ValueError('Passport is required') user = self.model( email=self.normalize_email(email), last_name=last_name, first_name=first_name, passport_id=passport_id ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractUser): email = models.EmailField(unique=True, verbose_name='Email', error_messages={'unique': 'This email already exists'}) first_name = models.CharField(max_length=20, verbose_name='First name') last_name = models.CharField(max_length=25, verbose_name='Last name') passport_id = models.BigIntegerField(validators=[validate_length], verbose_name='Passport') status = models.CharField(max_length=20, choices=STATUS_CHOICES) object … -
how to use arithmetics in djangos save method?
What is the best appraoch for overriding a save method, which calculates modelfield a trough self.modelfielda= self.modelfieldb / 4 + self.modelfieldc / 2 Currently I get Expected type 'int', got 'DecimalField' instead -
Django ORM query optimisation with multiple joins
In my app, I can describe an Entity using different Protocols, with each Protocol being a collection of various Traits, and each Trait allows two or more Classes. So, a Description is a collection of Expressions. E.g., I want to describe an entity "John" with the Protocol "X" that comprises the following two Traits and Classes: Protocol ABC Trait 1: Height Available Classes: a. Short b. Medium c. Tall Trait 2: Weight Available Classes: a. Light b. Medium c. Heavy John's Description: Expression 1: c. Tall, Expression 2: b. Medium My model specification (barebone essentials for simplicity): class Protocol(models.Model): name = models.CharField() class Trait(models.Model): """ Stores the Traits. Each Trait can have multiple Classes """ name = models.CharField() protocol = models.ForeignKey( Protocol, help_text="The reference protocol of the trait", ) class Class(models.Model): """ Stores the different Classes related to a Trait. """ name = models.CharField() trait = models.ForeignKey(Trait) class Description(models.Model): """ Stores the Descriptions. A description is a collection of Expressions. """ name = models.CharField() protocol = models.ForeignKey( Protocol, help_text="reference to the protocol used to make the description;\ this will define which Traits will be available", ) entity = models.ForeignKey( Entity, help_text="the Entity to which the description refers to", ) class … -
Is there a method to pass a folder path into a File Upload form in Django?
System at present uses no models. Takes user selected multi file input, parses information and generates an output. Currently user needs to navigate to correct share drive location before selecting file(s). Is it possible to pass a folder path (and ideally search string for filename) on windows explorer open using Django form? -
How do I import a Json file into a django database whilst maintaining object references
I have a C# desktop app and a django webapp that share a set of common class/model types. The C# app is exporting json files containing instances of these models, and I am trying to import these into the django database. The complication is that the parent model contained within the json file has properties that may reference the same sub-model in multiple places. For example, the json file looks something like this: { "$id": "1", "SubModels": { "$id": "2", "$values": [ { "$id": "3", "name": "Dave", "value": "123" }, { "$id": "4", "name": "John", "value": "42" } ] }, "PreferredSubModel: { "$ref": "4" } } Which was created using the using System.Text.Json.Serialization C# library with the ReferenceHandler = ReferenceHandler.Preserve serialisation option. In django, I've converted the json file into a dictionary using model_dictionary = JSONParser().parse(json_file). Are there any existing functions (in the django Python environment) that can handle this $id/$ref system to maintain class instances, or do I need to code my own deserializer? If the latter, does anyone have any suggestions for the best way to handle it? I'm new to django and json files, so hopefully I've just been googling the wrong terms and something exists... -
Django auto reloading of code changes not working in Docker on MacM1
Django auto reloading of code changes deployed in docker containers doesn't work on mac m1.