Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I get String in Django model field and make sure if it is unique
This question already has answers here: How to create a GUID/UUID in Python (8 answers) Your post has been associated with a similar question. If this question doesn’t resolve your question, ask a new one. Closed 8 mins ago. (Private feedback for you) I am generating a string using below technique but one thing I just want be sure of is that uniqueness of the string. will be a great help if anybody evaluate and suggest if there is a better way of getting a unique string. models.py import random import string def random_string_generator(size=10, chars=string.digits): return ''.join(random.choice(chars) for _ in range(13)) class Orders(models.Model): id= models.AutoField(primary_key=True) token = models.CharField(max_length=13, default=random_string_generator, editable=False, unique=True) identifier = models.CharField(max_length=13, default=random_string_generator, editable=False, unique=True) -
How to check and keep checkboxes checked when others are unchecked
I have check boxes that when I check 3of them for example and then I uncheck 1, an attribute works in the opposiste. With this I mean that Because I have a default hidden button that appears when I check a checkbox, when I hav e 3 of the checkboxes checked and I uncheck 1, the button is hidden where as 2 checkboxes are still checked meaning that the button should be unhidden. How would I correct this???? <script> $(document).ready(function() { $('#select-all').click(function() { var checked = this.checked; $('input[type="checkbox"]').each(function() { this.checked = checked; }); }) }); //Add a JQuery click event handler onto our checkbox. $('input[type="checkbox"]').click(function(){ //If the checkbox is checked. if($(this).is(':checked')){ //Enable the submit button. $('#delete_all').attr("hidden", false); } else{ //If it is not checked, hide the button. $('#delete_all').attr("hidden", true); } }); </script> <form method="post" action="{% url 'delete_students' %}"> {% csrf_token %} <table class="layout container"> <thead> <th><input type="checkbox" id="select-all"></th> </thead> <tr> <td> <input type="checkbox" name="marked_delete" value="{{ student.pk }}"> </td> </table> <button class="btn btn-dark" id="delete_all" hidden="hidden">Delete Selected</button> </form> -
How to check type is timestamp in dictionary?
{ "request_emp": { "id": 2 }, "overtime_date": "2021-05-26", "mail_body": "werr", "mail_status": 0, "mail_subject": "er", "request_start_datetime": "2021-05-26T00:00:00Z", "request_end_datetime": "2021-05-26T00:00:00Z", "request_total_datetime": null, "actual_start_datetime": null, "actual_end_datetime": null, "actual_total_datetime": null, "del_flag": 0 } how to check attribute which has datetime type value in above dict? -
How to show map in website GIS shape file map data in to my website?
Here, I'm trying to show GIS map on my website. I'm using GIS dataset from https://opendatanepal.com/dataset/nepal-municipalities-wise-geographic-data-shp-geojson-topojson-kml and I have the following files in zipped dataset: local_unit.dbf local_unit.xml local_unit.shx local_unit.prj local_unit.sbn local_unit.sbx local_unit.shp I have problem of using this file in my Django/Python website. I'm trying to use jquery library with ArcGIS from this: https://developers.arcgis.com/javascript/3/jssamples/framework_jquery.html. I don't know this is the way or not to embed map in website. Please suggest how can I use GIS map in website. -
How to display django forms in a table format?
I have the following in my Models.py class Accounts(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) .... is_assigned = False class Section(models.Model): name = models.CharField(max_length=150) .... is_assigned = False is_teacher = False class Assignment(models.Model): teacher = models.ForeignKey( Accounts, on_delete=models.CASCADE, limit_choices_to={'is_teacher': True, 'is_assigned': False} ) section = models.ForeignKey( section, on_delete=models.CASCADE, limit_choices_to={'is_assigned': False} ) Now I'm trying to assign a teacher to a section and I'm using BSModalModelForm in my forms.py but as I'm writing my code I'm starting to get lost. How can I display my form in this format? Note: All teachers that are not assigned are displayed in the table. Thank you for answering! -
How can I check the file names through python a script in python?
I am using python scripts to save web scraped data to CSV files. The name of CSV files is dynamic, like fl_todays_date.csv where today's date is the date derived from the web scraped site. After saving the data in a CSV file, I then import the CSV data into my Django models, all through the script. But the problem I'm facing is, How can I check whether the data from yesterday's file is already present in the database before importing today's data. My file structure is as follows: csv_files fl_some_pervious.csv fl_yesterday.csv fl_today.csv script scrape.py db_upload.py -
Getting KeyError: 'first name' in django serializers.py
I am stuck for a long time here. I am getting a KeyError for first name, but if I remove it then the code works. I am also using React for my front-end and its just getting messier. serializers.py from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth import authenticate # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first name', 'last name', 'username', 'email') # Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first name', 'last name', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['first name'], validated_data['last name'], validated_data['username'], validated_data['email'], validated_data['password']) # user.save() return user # Login Serializer class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Incorrect Credentials") Logs: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 26, 2021 - 08:36:27 Django version 3.1.7, using settings 'leadmanager.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [26/May/2021 08:36:33] "GET / HTTP/1.1" 200 1009 [26/May/2021 08:36:33] "GET /static/frontend/main.js HTTP/1.1" 200 231194 Unauthorized: /api/auth/user [26/May/2021 08:36:33] "GET /api/auth/user HTTP/1.1" 401 58 Not Found: … -
Getting 'GET /static/css/base.css HTTP/1.1" 404 1795' error for static files
I have no idea what I'm doing wrong. I have STATIC_URL = '/static/' STATICFILES_DIR = [str(BASE_DIR.joinpath('static'))] under my settings.py. Here is an image to my current file structure https://pasteboard.co/K3uhtSN.png I linked with <link rel="stylesheet" href="{% static 'css/base.css' %}"> in base.html and loaded at the very top using {% load static %} Thank you -
How to Generate a Unique String in Django?
I am generating a string using below technique but one thing I just want be sure of is that uniqueness of the string. will be a great help if anybody evaluate and suggest if there is a better way of getting a unique string. models.py import random import string def random_string_generator(size=10, chars=string.digits): return ''.join(random.choice(chars) for _ in range(13)) class Orders(models.Model): id= models.AutoField(primary_key=True) token = models.CharField(max_length=13, default=random_string_generator, editable=False, unique=True) identifier = models.CharField(max_length=13, default=random_string_generator, editable=False, unique=True) -
OuterRef is compatible with UUID Django
I have the following query where the primary key of the products model is a UUID and when I use OuterRef in the query it throws me the following message: ValidationError at /api/v1/productstodist/ ["'0' it is not a valid UUID."] OuterRef does not support uuid? the following is the query that I am trying to perform between two models: queryset = queryset.filter(~Q(provider = provider)).annotate( sellproductprices=Subquery( prefetch_qr.filter(product=OuterRef('pk')) .values('id_sell_price') .annotate(count=Count('pk')) .values('count') ) ).filter( sellproductprices__gt=0 ).prefetch_related( prefetch ) -
Incorrect padding error in putting SECRET_KEY in .env file
When I'm using SECRET_KEY value in settings.py, the Django application is working fine but as soon as I put the value in .env file and stating SECRET_KEY = config('SECRET_KEY') in settings.py, it is giving padding error. Case in which I put SECRET_KEY value directly in settings.py is working fine.settings.py Using .env file giving padding error. Error Screenshot:-Padding Error Please help me out. -
In a Django template, can I use a button to update the data in an HTML table generated with a for loop?
Let's say I've used the following syntax to create tables in a Django template: {% for data in list_of_data_dicts %} <tr> <td> data.col_one_val </td> <td> data.col_two_val </td> <td> data.col_three_val </td> </tr> {% endfor %} I also have several such 'list_of_data_dicts' representing datasets of the same form. I would like to be able to update which dataset is used to populate the table with a button click. How can I accomplish this? -
How to fix Jenkins error. no such table: users_user
Not sure where to start. I just want Jenkins to run tests via python manage.py test In my build step I am run migrtaions after installing necessary packages. Output: [...] Applying auth.0012_alter_user_first_name_max_length... OK Applying users.0001_initial... OK Applying admin.0001_initial... OK [...] Part of Traceback (starting @ test command): + python manage.py test /var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/environ/environ.py:628: UserWarning: /var/lib/jenkins/workspace/New_Performance_Realm/speedrealm/.env doesn't exist - if you're not configuring your environment separately, create one. warnings.warn( Creating test database for alias 'default'... Traceback (most recent call last): File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 421, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: no such table: users_user The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/core/management/commands/test.py", line 55, in handle failures = test_runner.run_tests(test_labels) File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/test/runner.py", line 725, in run_tests old_config = self.setup_databases(aliases=databases) File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/test/runner.py", line 643, in setup_databases return _setup_databases( File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/test/utils.py", line 179, in … -
What else can I try to debug a "ModuleNotFoundError" in Django?
I’m having problems with one module in my Visual Studio Core project. It is not being found. It generates this error: File "C:\Users\danj\source\repos\project_django\comstockapt\comstockapt\urls.py", line 28, in from comstockapt.email_accounts import views as email_views ModuleNotFoundError: No module named 'comstockapt.email_accounts' I’ve gone through many, many similar questions, but I can’t get it to work. I’m using the virtual environment. When I execute “python” in the terminal and then run ‘help(“modules email_accounts”)’ it shows the module with all of its files. When I run help(“modules”), I see all of my modules listed in the response. Here is my urls.py file within module comstockapt.comstockapt. Here is my installed_apps: I've checked environment variables, the virtual environment, the directory structure. What can I try next? -
Partial updating a ManyToMany field, but keeping its get representation
I've been scratching my head about this problem for a couple of hours now. Basically, I have two models: User and Project: class User(AbstractUser): username = None email = models.EmailField("Email Address", unique=True) avatar = models.ImageField(upload_to="avatars", default="avatars/no_avatar.png") first_name = models.CharField("First name", max_length=50) last_name = models.CharField("Last name", max_length=50) objects = UserManager() USERNAME_FIELD = "email" class Project(models.Model): name = models.CharField("Name", max_length=8, unique=True) status = models.CharField( "Status", max_length=1, choices=[("O", "Open"), ("C", "Closed")], default="O", ) description = models.CharField("Description", max_length=3000, default="") owner = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name="project_owner" ) participants = models.ManyToManyField(User, related_name="project_participants", blank=True) created_at = models.DateTimeField(auto_now_add=True) I use standard ModelViewSets for both of them, nothing changed. Then there's my Project serializer: class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = "__all__" status = serializers.CharField(source="get_status_display", required=False) owner = UserSerializer() participants = UserSerializer(many=True) I use UserSerializers here, because having them achieved first of my two goals: I wanted to get the user data when getting the project from the API -> owner is a serialized User with all the fields, same for participants, but it's a list of users I want to be able to partially update the Project, for example add a participant So I searched through the docs and SO and I always found answers … -
Filter in Django array
How do I filter an array with a property from a model? class InvestorCountry(SimpleListFilter): """ This filter is being used in django admin panel in Investor model. """ title = 'Country' parameter_name = 'profile__country' def lookups(self, request, model_admin): return ( ('US', 'US'), ('non_US', 'non-US') ) def queryset(self, request, queryset): print("First::", queryset[0].investor_country()) print("Second::", queryset.filter(profile__country__exact='US')) print("Third::", queryset.filter(profile__country=['US'])) if self.value() == 'US': return queryset.filter(profile__country=['US']) The print shows this: First :: US Second :: <QuerySet [<Investment: Prosy Arceno>, <Investment: Prosy Arceno>, <Investment: Prosy Arceno>]> Third :: <QuerySet []> these are the data: I think this is the closest I've ever gone since I asked this question, but I still can't figure out how to filter based on a property. Can anyone help? -
Checking if user exists and using its data if it does
I have a view in which the user has to fill either the email or phone fields and then choose a pizza from an items list. The thing is, if the user enters an email or a phone then I need to check if the email or phone match an existing user (if it does, then the order uses that one, if not then no user is used). But if the user enters both fields and the user exists then I use that one and, if not, I create it. Since I'm doing all of this through a view that connects to the order serializer that is connected to the order model, I am not sure how I can implement this, since the user's data is connected to its own serializer and model. I am new to this type of thing so any advice on how to tackle this would be very appreciated. I wrote something in my view that does not work but should illustrate what I mean... maybe there's a way to do it like that but make it work? These are the models: class Client(models.Model): email = models.EmailField(max_length=200) phone = models.IntegerField() def __str__(self): return self.email class Order(models.Model): … -
Django, template. Can't pass variable inside if statement
I am using django all auth to sign in with my Google accounts. I'm able to get {userName} to display on the template. I also created a table and pass {userName} as a hidden field. When I try to match {userName} to match the table's userName in my if statement to only display certain rows of data, nothing shows up. I can't get {userName} directly in my view and pass it on to my template because django all auth uses different views. -
Passing authenticated_user kwargs to Django Form with Class-based View
I have a Django application to track referrals (referred by a user). I want to pass the id of the authenticated user to the ModelForm 'referrer' field (and since it's from the current logged in user the field shouldn't be editable). class Referral(models.Model): name = models.CharField(max_length=100) referrer = models.ForeignKey('users.User', on_delete=models.SET_NULL, related_name='referrals', null=True, blank=True) View: class ReferralFormView(FormView): form_class = ReferralForm template_name = "refer.html" success_url = reverse_lazy('thanks') def get(self, request): if request.user.is_authenticated(): return super(ReferralFormView, self).get(request) else: return redirect('login') def get_form_kwargs(self): user = self.request.user form_kwargs = super(ReferralFormView, self).get_form_kwargs() form_kwargs['referrer'] = user.id return form_kwargs def form_valid(self,form): ... form.save() return super(ReferralFormView, self).form_valid(form) I override get_form_kwargs in the view, then modify form init class ReferralForm(forms.ModelForm): class Meta: model = Referral def __init__(self, *args, **kwargs): referrer = kwargs.pop('referrer', None) super(ReferralForm, self).__init__(*args, **kwargs) self.fields['referrer'].disabled = True self.fields['referrer'].queryset = User.objects.filter(id=referrer) However all I see is a blank referrer field, what am I missing to pass the user id to that field? thanks -
Parse Nested Url Encoded Data from POST Request
I am creating a callback URL in Django for a webhook in Mailchimp. Mailchimp sends a POST request to the URL whenever certain actions are performed on users in Mailchimp. These POST requests contain data in the body in the form application/x-www-form-urlencoded. Mailchimp does not provide an option to choose the format of the data returned, so we must use the URL-encoded data. Now, the issue is that the data returned contains nested data. That is, lists and dictionaries (or JSON, since it is an HTTP request), are in the url-encoded data. For example, one POST request from Mailchimp, which is sent when a user changes their name, would look like: type=profile&fired_at=2021-05-25+18%3A03%3A23&data%5Bid%5D=abcd1234&data%5Bemail%5D=test%40domain.com&data%5Bemail_type%5D=html&data%5Bip_opt%5D=0.0.0.0&data%5Bweb_id%5D=1234&data%5Bmerges%5D%5BEMAIL%5D=test%40domain.com&data%5Bmerges%5D%5BFNAME%5D=first_name&data%5Bmerges%5D%5BLNAME%5D=last_name&data%5Blist_id%5D=5678 Using Django's request.POST, the data is decoded into: type=profile&fired_at=2021-05-25 18:03:23&data[id]=abcd1234&data[email]=test@domain.com&data[email_type]=html&data[ip_opt]=0.0.0.0&data[web_id]=1234&data[merges][EMAIL]=test@domain.com&data[merges][FNAME]=first_name&data[merges][LNAME]=last_name&data[list_id]=5678 This is less than optimal, since to access the first name of the user from this data we would have to write request.POST.get("data['merges']['FNAME']", None) when the data is intended to be accessed more like data = request.POST.get('data', None) try: first_name = data['merges']['FNAME'] except KeyError: first_name = '' I have looked for a Django/Python specific way to decode this nested URL-encoded data into more appropriate formats to work with it in Python, but have been unable to find anything. … -
Logstash Error: "too many arguments" when attempting to start/run logstash
Was attempting to run logstash on my python/django project with the following command on windows (using git bash): ./logstash -f path/to/logstash.conf I was getting this error /c/Program Files/logstash-7.13.0/bin/logstash: line 40: cd: too many arguments /c/Program Files/logstash-7.13.0/bin/logstash: line 40: /c/Users/Stephanie/Documents/Projects/BidRL/bidrl-reporting/bin/logstash.lib.sh: No such file or directory /c/Program Files/logstash-7.13.0/bin/logstash: line 41: setup: command not found /c/Program Files/logstash-7.13.0/bin/logstash: line 59: setup_classpath: command not found /c/Program Files/logstash-7.13.0/bin/logstash: line 60: exec: : not found I created a notion with every step I took to try to resolve the error. Eventually I decided to try moving logstash from c/program files to c. This solved the issue. I cd into the logstash directory: cd "/c/logstash-7.13.0/bin/" And then run logstash ./logstash -f path/to/logstash.conf This is the output Using bundled JDK: /c/logstash-7.13.0/jdk OpenJDK 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and will likely be removed in a future release. WARNING: Could not find logstash.yml which is typically located in $LS_HOME/config or /etc/logstash. You can specify the path using --path.settings. Continuing using the defaults Could not find log4j2 configuration at path /C:/Program Files/logstash-7.13.0/config/log4j2.properties. Using default config which logs errors to the console [INFO ] 2021-05-25 14:34:41.276 [main] runner - Starting Logstash {"logstash.version"=>"7.13.0", "jruby.version"=>"jruby 9.2.16.0 (2.5.7) 2021-03-03 f82228dc32 … -
ImproperlyConfigured: Error finding Upload-Folder. Maybe it does not exist?
I found a Django project and failed to upload files to it. git clone git clone https://github.com/NAL-i5K/django-blast.git $ cat requirements.txt in this files the below dependencies had to be updated: psycopg2==2.8.6 I have the following Dockerfile: FROM python:2 ENV PYTHONUNBUFFERED=1 RUN apt-get update && apt-get install -y postgresql-client WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ RUN mkdir -p /var/log/django RUN mkdir -p /var/log/i5k For docker-compose.yml I use: version: "3" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data - ./scripts/install-extensions.sql:/docker-entrypoint-initdb.d/install-extensions.sql environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db links: - db $ cat scripts/install-extensions.sql CREATE EXTENSION hstore; I had to change: $ vim i5k/settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } #https://github.com/NAL-i5K/django-blast/blob/master/i5k/settings.py#L223 ... FILEBROWSER_SUIT_TEMPLATE = True FILEBROWSER_DIRECTORY = '' FILEBROWSER_VERSIONS_BASEDIR = '_versions/' FILEBROWSER_MAX_UPLOAD_SIZE = 10737418240 # 10GB FILEBROWSER_EXTENSIONS = { 'Folder': [''], #'Image': ['.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff'], 'Document': ['.pdf', '.doc', '.rtf', '.txt', '.xls', '.csv', '.docx'], #'Video': ['.mov', '.wmv', '.mpeg', '.mpg', '.avi', '.rm'], #'Audio': ['.mp3', '.mp4', '.wav', '.aiff', '.midi', '.m4p'], 'FASTA': ['.fa', '.faa', '.fna', '.fasta', '.cds', '.pep'], … -
ModuleNotFoundError: No module named 'psycopg2' error: python3, django, settings.py?
First of all, I've read I think all the most recent (2019 onwards) posts here about this problem to no avail :( I've got an up&running default webapp with python3 and django already working with default db.sqlite2. I now neeed to change all that db backend to psql. So, from these sources: https://pypi.org/project/psycopg2/ https://www.psycopg.org/docs/install.html I've installed psycopg2-binary, OK. From this source: https://www.enterprisedb.com/postgres-tutorials/how-use-postgresql-django I've modified settings.py, DATABASES section, to use psql instead of sqlite. I've tried: 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'ENGINE': 'django.db.backends.postgresql', And both gives me the error: (env) PS D:\Users\llagos.NB-KEYONE15\Visual Studio projects\ecommerce-psql> python manage.py makemigrations Traceback (most recent call last): File "D:\Users\llagos.NB-KEYONE15\Visual Studio projects\ecommerce-psql\env\lib\site-packages\django\db\backends\postgresql\base.py", line 25, in <module> import psycopg2 as Database ModuleNotFoundError: No module named 'psycopg2' ... django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' So, what's wrong with this settings.py file? is this correct? I've tried to google for information but again, no luck. Documentation for psycopg2 doesn't say what to change on settings.py. It just say "install and code", but when using django, there are previous steps, like this settings.py file. Thanks a lot for any hint! Regards, -
Django changing model value based on relationship with other model
I'm working on a project that has three models, one of which has a value that is dependent on if the other two are linked to it by a foreign key. the value can also switch if the links change. I was wondering how I would go about that. For example: general/models.py class Person(models.Model): DEFAULT = 'D' A = 'A' B = 'B' BOTH = 'AB' TYPES = [ (DEFAULT,'Default'), (A,'Type A'), (B,'Type B'), (BOTH,'Type A & B') ] # type is default if Person is not linked to A or B # A if Person is linked to A # B if Person is linked to B # BOTH if Person is linked to both type = models.CharField(max_length=2, choices=TYPES, default=DEFAULT) A/models.py class A(models.Model): person = models.ForeignKey('general.Person',on_delete=models.CASCADE) B/models.py class B(models.Model): person = models.ForeignKey('general.Person',on_delete=models.CASCADE) -
GLTF file is loading but it displaying black in browser three.js
I am working on my project in Django where I am using three.js to load my model and animate it I was able to load my .gltf file but it getting displayed black on my browser my website background color is white even though it's showing the black screen.I am totally new to the Three.js pls guide me here is my code <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'mysite/style.css' %}" type="text/css"> <script src="https://ajax.googleapis.com/ajax/libs/threejs/r76/three.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/92/three.min.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r92/examples/js/loaders/GLTFLoader.js"></script> <script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script> <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/100/three.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/100/three.min.js"></script>--> <title>Finance Assistant</title> </head> <body> <canvas class="webgl"></canvas> <script type="text/javascript"> // Debug //const gui = new dat.GUI() const gltfloader = new THREE.GLTFLoader(); // Canvas const canvas = document.querySelector('canvas.webgl') // Scene const scene = new THREE.Scene() //Hand gltfloader.load("{% static 'mysite/HomeHand.gltf' %}", function(gltf) { scene.add(gltf.scene); }); /* Objects const geometry = new THREE.TorusGeometry( .7, .2, 16, 100 ); // Materials const material = new THREE.MeshBasicMaterial() material.color = new THREE.Color(0xff0000) // Mesh const sphere = new THREE.Mesh(geometry,material) scene.add(sphere) */ // Lights const pointLight = new THREE.PointLight(0xffffff, 0.1) pointLight.position.x = 2 pointLight.position.y = 3 pointLight.position.z = 4 scene.add(pointLight) /** * Sizes */ const sizes = { width: window.innerWidth, height: window.innerHeight } window.addEventListener('resize', …