Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to add django-database-size to django project view?
I am trying to use django-database-size to display mysql table sizes to django admin page. The project has very limited docs to how to add the view. Here is the repo: https://github.com/chrisspen/django-database-size All it mentions about adding the view: Install the appropriate view in /sql (currently only PostgreSQL and MySQL supported). -
Does foreign key have to be primary key in Django?
Can we use any other unique column as foreign key in django model? -
Integrity Error NOT NULL constraint failed even though I have set blank=True, null=True in my model
Im getting a NOT NULL constraint error in my code when trying to save my model form, even though the fields I have left empty are optional (have set blank=True, null=True) in models.py Im very confused, what am I doing wrong? The error is popping up when I leave the first optional field blank (description). Filling any of them manually before work.save() pushes the issue to the next field, and passes when all fields are filled. EDIT: this also happens when trying to create a work instance from the admin dashboard. models.py class Work(models.Model): ## core fields creator = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, default=None) created = models.DateTimeField() modified = models.DateTimeField() work_slug = models.SlugField(max_length=50) # slug -> TBD: find way to assign default value to slug = archival number. archive = models.ForeignKey(Archive, on_delete=models.CASCADE) # superfolder -> replaces category, series etc with dynamic hierarchical database folder = models.ForeignKey(Folder, on_delete=models.CASCADE) # basic metadata fields name = models.CharField(max_length=50) year = models.CharField(max_length=50) medium = models.CharField(max_length=50) description = models.CharField(max_length=1200, blank=True, null=True) # optional metadata authors = models.CharField(max_length=50, blank=True, null=True) classification = models.CharField(max_length=50, blank=True, null=True) location = models.CharField(max_length=50, blank=True, null=True) link = models.URLField(max_length=50, blank=True, null=True) record_creator = models.CharField(max_length=50, blank=True, null=True) # revisit -> # custom descriptors cd1_name … -
Connecting a Django App Deployed to IIS to a Sql Server Database
I'm currently having difficulties connecting my Django app to a SQL Server Database after I've deployed it to IIS. My current setting for the database is: DATABASES = { 'default': { "ENGINE": 'mssql', "NAME": 'databasename', "USER": 'myusername', "PASSWORD": 'mypassword', "HOST": 'host', "PORT": '', "OPTIONS": {"driver": "ODBC Driver 17 for SQL Server", "Trusted_Connection":'yes'}, }, } and with this setting, I keep getting the error message: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'myusername'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0); I've also tried using sql_server.pyodbc as the engine but also got the same error message. I was just wondering if there's anything else I would need to do for me to be able to connect my app to the database or if there's anything I would need to change in my current setting? -
Why django template not render tag after include tag
i consider that why template not render tag after {% include %}. when i put some tag like something in front of include tag, it work. But it not work if i try to put behind the include tag. :( in index.html <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'styles/main.css' %}" /> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"> </script> </head> <body> <div class="d-flex"> {% include 'navbar.html' %} <div class="content"> <div class="header"> {% include 'header.html' %} </div> <div> {% block subHeader %} {% endblock %} </div> <div> {% block list %} {% endblock %} </div> </div> </div> </body> </html> in list.html <table class="table"> <thead> <tr> <th scope="col">Cardinal Number</th> <th scope="col">ID</th> <th scope="col">Name</th> <th scope="col">Category</th> <th scope="col">Cost</th> <th scope="col">Note</th> <th scope="col">Image</th> <th scope="col">Action</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <th scope="row">2</th> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <th scope="row">3</th> <td colspan="2">Larry the Bird</td> <td>@twitter</td> </tr> </tbody> </table> in products.html {% extends 'index.html' %} {% block subHeader %} {% include 'components/subHeader.html' with url="api/add-product" name="product" selectName="product-category" %} {% endblock subHeader%} {% block list %} {% include 'components/list.html' %} {% endblock content%} although i put whatever after include … -
I need help adding word counter on the input text on a flask paraphraser app
I've gotten hold of an open source paraphraser project written in python and flask and need help in adding some functionality to it. I am totally new to the field so please overlook if i say something stupid, i was downvoted on the same question before. I've tried to look for a solution elsewhere on the web but couldn't find anything that helped. When i test the app on the local server, it shows a simple paraphrasing app with input and output boxes. It paraphrases the text but doesn't highlight the specific words and sentences that it rephrases in the output box. I wanna know adding what piece of code in the app file would achieve that. Additionally, i also want to add a word counter on the input text. The corresponding code for the template file would be a bonus, thanks! -
Django taggit query error: must be "model_name" instance
I have a very simple Photo class which uses django_taggit class Photo(models.Model): ... some other fields tags = TaggableManager(blank=True) Oddly enough, even simple query like this: blue_tag = Tag.objects.get(name='blue') q1 = Photo.objects.filter(tags=blue_tag) some_tags = Tag.objects.filter(name__icontains='b') q1 = Photo.objects.filter(tags__in=some_tags) will result in the following error.... Cannot query "blue": Must be "Photo" instance. Which is odd...given the fact that I'm passing Tag objects... -
Understanding Ubuntu storage
I have host with Ubunbu instance and in it I have docker containers with django project, postgres, cronjob and nginx. I'm checking the host disk with df -h and the output is this: Filesystem Size Used Avail Use% Mounted on udev 3.8G 0 3.8G 0% /dev tmpfs 777M 1.5M 776M 1% /run /dev/sda1 150G 42G 102G 30% / tmpfs 3.8G 0 3.8G 0% /dev/shm tmpfs 5.0M 0 5.0M 0% /run/lock tmpfs 3.8G 0 3.8G 0% /sys/fs/cgroup /dev/sda15 253M 1.1M 252M 1% /boot/efi overlay 150G 42G 102G 30% /var/lib/docker/overlay2/b4e1380fce967b0a51e9264582b5aca1ef489e7df77e15e7d44527d20c639e48/merged overlay 150G 42G 102G 30% /var/lib/docker/overlay2/108849a926d5a23bea24c0e9192d92e80db4257733948c4378546e9a466c1416/merged overlay 150G 42G 102G 30% /var/lib/docker/overlay2/e1840145e9fc846d78a661ea87044c4e5f30c12eadd0bf9a3eb6c7645f93f0ad/merged overlay 150G 42G 102G 30% /var/lib/docker/overlay2/aa03a83c65275cfc7b8909246937930046f6b8c7b8b20868f996804fcd282611/merged overlay 150G 42G 102G 30% /var/lib/docker/overlay2/e9fae8ab52b956cda4b9c5e14a21ee1976e9f684ead3134dae20d6c7b1df4f39/merged tmpfs 777M 0 777M 0% /run/user/0 When I export my data into csv, the csv file is not larger than 300MB. Can someone explain why I have 42G and what are those /var/lib/docker/overlay2/* files? -
Python Django {% if usuario.username == user %} not work :(
I need some help. I want to list all user avoid the login user. if I print user= juan if I print usuario.username=juan There have the same string {% if usuario.username == user %} Nothing {% else %} <tr><td> {{usuario.username}} <img src="{% static 'assets/img/icono_writeMSJ.png' %}" height="30px"> </td> </tr> {% endif %} if i change for example {% if usuario.username == 'juan' %} Nothing {% else %} <tr><td> {{usuario.username}} <img src="{% static 'assets/img/icono_writeMSJ.png' %}" height="30px"> </td> </tr> {% endif %} this work fine, why?? :( -
Selfjoin in Django to get list of combinations and their number
unfortunately I am missing the right idea right now, so I am trying my first post here: My model: class MyModel(models.Model): interesting_value = PositiveIntegerField() other_value2 = PositiveIntegerField() other_value3 = PositiveIntegerField() ... Now I want to do something like this in django: with query as (select interesting_value, other_value2, other_value3 from mymodel) select q1.interesting_value, q2.interesting_value, count(*) AS cnt from query q1 inner join query q2 on q1.other_value2 = q2.other_value2 and q1.other_value3 = q2.other_value3 and q1.interesting_value <> q2.interesting_value and q1.interesting_value < q2.interesting_value group by q1.interesting_value, q2.interesting_value; To get such an result which finds the number of pairs under the given conditions: q1.interesting_value, q2.interesting_value, cnt 1,4,2 1,9,3 1,38,1 1,100,1 How could I realize this selfjoin in Django without using pure SQL in my app? To get a idea of the question I want to answer, this example: How often is the combination of two of exams (=interesting_value) taken by one student (=other_value2) in one semester (=other_value3)? I would be really thankful for a little hint to the solution! Jan -
Combine Comodo SSL certificate
I have a Django website running Nginx on DigitalOcean. Now I have a certificate from Comodo. I have 4 files. AAACertificateServices.crt SectigoRSADomainValidationSecureServerCA.crt USERTrustRSAAAACA.crt mydomain.crt How do I combine these files and what do I need to do next? Because I get the error message: [emerg] 113128#113128: SSL_CTX_use_PrivateKey("/var/www/ssl/mydomain.key") failed (SSL: error:05800074:x509 certificate routines::key values mismatch) -
Function mixing up values of different model (within similar named fields)
Here is my search function def search(request): query = request.GET['query'] allPoststit = List.objects.filter(title__icontains=query) allPostscont = List.objects.filter(content__icontains=query) allPostsl = allPoststit.union(allPostscont) allPoststitm = MusicList.objects.filter(title__icontains=query) allPostscontm = MusicList.objects.filter(content__icontains=query) allPostsm = allPoststitm.union(allPostscontm) allPoststitb = BookList.objects.filter(title__icontains=query) allPostscontb = BookList.objects.filter(content__icontains=query) allPostsb = allPoststitb.union(allPostscontb) allPosts2 = allPostsl.union(allPostsm) allPosts = allPosts2.union(allPostsb) params = {'allPosts' : allPosts, 'query':query} return render(request, 'app/search.html', params) when from template im calling {% for tag in i.genre.all %} <div class="Genre"> <small>{{ tag }}</small> </div> {% empty %} No tags! {% endfor %} Its mixing up values within different models or returning empty. Any idea why is this happening? -
Trying to get API working on Django app I'm making whilst following a tutorial
Errors Recieved Hi, thanks for reading. So I'm following a tutorial from codewithmosh and I'm currently building the django app. Everything was going smooth until trying to get the API to work on it. The first thing I had to change was the 'from django.middleware.csrf import _sanitize_token' in the authentication file. After getting rid of that error I started getting the errors as shown in the attached picture. I am absolutely stumped. Any light that can be shone on my issue would be much appreciated. -
python test coverage cannot omit env/venv folder and throwing ERROR collecting env/Lib error
I have faced this issue when I am trying to test in a Django project from docker. Based on the instructions in the tutorial, I have implemented successfully black test and isort test successfully. However, when it comes t0 Pytest I am facing the aforementioned issue despite the fact that I have specified the exclusion of env files in my setup.cfg file using omit command of pytest-cov tool. Here are is my setup for setup.cfg file: [flake8] max-line-length = 119 exclude = .git,*/migrations/*,*env*,*venv*,__pycache__,*/staticfiles/*,*/mediafiles/* [coverage:run] source = . omit= *apps.py, *settings.py, *urls.py, *wsgi.py, *asgi.py, manage.py, conftest.py, *base.py, *development.py, *production.py, *__init__.py, */migrations/*, *tests/*, */venv/*, [coverage:report] show_missing = True The only variation between the youtube tutorial and my setup is that the Tutor create his virtual env using venv however I used env name. I have tested this but to no avail. Furthermore, pytest.ini file was set up like this: [pytest] DJANGO_SETTINGS_MODULE = real_estate.settings.development python_files = tests.py test_*.py *_tests.py Also, project.toml is set up like this: [tool.black] extend-exclude = ''' /( | env )/ ''' However when I run the test using the command: docker compose exec api pytest -p no:warnings --cov=. I am facing the following errors: ERROR collecting env/Lib/site-packages/social_core/tests/backends/test_twitch.py _ ERROR … -
Field is only visible when on "Writing" mode
I have the following field in my Django Admin app: class ContractForm(forms.ModelForm): ativo = forms.CharField( initial="this is a test" ) The field value is visible when the logged user has all permissions (can add, change and view) on Admin's default auth console: But when a user has only view permissions, the value is not shown: Any thoughts? -
Creating an objects to database: FOREIGN KEY constraint failed
When I try create an objects to my database it give me this error FOREIGN KEY constraint failed Which I dont understand why. Anyone have an idea? models.py from django.contrib.auth.models import User from django.db import models class Account(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) accountid = models.CharField(max_length=100) mt5password = models.CharField(max_length=100, default="default") mt5server = models.CharField(max_length=100, default="default") telegramchannel = models.CharField(max_length=100, default="default") riskpertrade = models.FloatField(max_length=100, default="1.0") balance = models.FloatField(default=2000) winrate = models.CharField(max_length=100) riskreward = models.CharField(max_length=100) result = models.CharField(max_length=100, default="Not Passed") def __str__(self): return self.accountid class AccountHistory(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE) tradeid = models.CharField(max_length=100) opendate = models.CharField(max_length=100) type = models.CharField(max_length=100) volume = models.CharField(max_length=100) symbol = models.CharField(max_length=100) openprice = models.CharField(max_length=100) closedate = models.CharField(max_length=100) closeprice = models.CharField(max_length=100) profit = models.FloatField() def __str__(self): return self.tradeid Here is my function to create the database objects views.py def testfunc(): AccountHistory.objects.create(tradeid=30688, account_id=98765, opendate="8 mars", type="buy", volume=1.25, symbol="EURUSD", openprice=1.234, closedate="9 mars", closeprice=1.250, profit=9349.23) -
Why my navbar not displaying properly? displaying like text
My Navbar is coming like this: Image of my navbar Why not like this : Image of desired navbar PLEAES ASSIST! (I AM NEW PROGRMMER CURRENTLY LEARNIG WEB DEV.) -
How to best handle the access with Django to a database that has some DateTime fields stored in local timezone while others are stored in UTC?
What would be the best approach to handle the following case with Django? Django needs access to a database (in MariaDB) in which datetime values are stored in UTC timezone, except for one table that has all values for all of its datetime columns stored in local timezone (obviously different that UTC). This particular table is being populated by a different system, not Django, and for some reasons we cannot have the option to convert the timestamps in that table to UTC or change that system to start storing the values in UTC. I am asking your opinion for an approach to the above case that would be as seamless as it can be, preferably without doing conversions here and there in various parts of the codebase while accessing and filtering on the datetime fields of this "problematic" table / model. I think an approach at the model layer, which will let Django ORM work as if the values for that table were stored in UTC timezone, would be preferable. Perhaps a solution based on a custom model field that does the conversions from and back to the database "transparently". Am I thinking right? Or perhaps there is a better … -
android and "server" outh keys gcloud
I have android and ios OAuth2.0 Credentials for authenticating with outh2.0, I do get my access and refreshtokens. I store the refreshToken . Then in a django server I try to get a new access_token with above refresh token by posting to https://accounts.google.com/o/oauth2/token using new Auth2.0 Credentials for a web app. params = { "grant_type": "refresh_token", "refresh_token": user_refresh_token, "token_uri": authorization_url, "access_type": "offline", "client_id": client_id, "redirect_uri": "https://www.googleapis.com/oauth2/v4/token", "client_secret": client_secret, } errorThe credentials do not contain the necessary fields need to refresh the access token. You must specify refresh_token, token_uri, client_id, and client_secret The access token is then used to get creds and access user calendar. creds = google.oauth2.credentials.Credentials(access_token) service = build('calendar', 'v3', credentials=creds) Note the keys are for the same project. Is there a way to use a service account to get a refresh token ? Can I use different oAuth credentials for the same project? Can I "merge"/"mix" the clients? What can I do to get a refresh token with the web App Credentials? -
Find MS SQL Server column information for Django models
I have done this before but can't remember how, so forgive me if this has already been answered. I want to create a model in Django from an MS SQL Server table. How would I find the relevant information for the columns? I used the command line to retrieve this information. An example of what I am looking for: region = models.CharField(db_column='Region', max_length=255, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) # Field name made lowercase. -
Django data entry with relationships, what is the standard or most effecient way?
With a model without a relationship the, the most efficient way for data entry would be to use a django.forms.ModelForm. Take the following example: class Customer(models.Model): first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) def __str__(self): return f"{self.first_name} {self.last_name}" class CustomerModelForm(forms.ModelForm): class Meta: fields = ("first_name", "last_name") model = Customer form = CustomerModelForm(data={"first_name": "Jon", "last_name": "Doe"}) if form.is_valid(): form.save() But when you add in relationships, what is the most efficient or best standard to follow, let's update the model to: class Customer(models.Model): first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) address = models.ForeignKey( "Address", on_delete=models.PROTECT ) def __str__(self): return f"{self.first_name} {self.last_name}" class Address(models.Model): street = models.CharField(max_length=120) city = models.CharField(max_length=120) state = models.CharField(max_length=2) zip_code = models.CharField(max_length=5) def __str__(self): return f"{self.street}, {self.city}, {self.state} {self.zip_code}" One solution might be: class CustomerModelForm(forms.ModelForm): class Meta: fields = ("first_name", "last_name", "address") model = Customer class AddressModelForm(forms.ModelForm): class Meta: fields = ( "street", "city", "state", "zip_code" ) model = Address class Customer(forms.Form): first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) street = models.CharField(max_length=120) city = models.CharField(max_length=120) state = models.CharField(max_length=2) zip_code = models.CharField(max_length=5) def save(self): address_form = AddressModelForm( data={ "street": "123 Sycamore St", "city": "Eagles Harbor", "state": "AD", "zip_code": "12345" } ) if address_form.is_valid(): address = address_form.save() customer_form = CustomerModelForm( data={"first_name": "Jon", "last_name": "Doe"} … -
on_save() is not triggered when model is created
I got the two following models: class Stuff(models.Model): ... def custom_function(self): ... class MyModel(models.Model): name = models.CharField(max_length=200) many_stuff = models.ManyToManyField(Stuff, related_name="many_stuff+") many_other_stuff = models.ManyToManyField(Stuff, related_name="many_other_stuff+") def __init__(self, *args, **kwargs): super(MyModel, self).__init__(*args, **kwargs) for stuff in self.many_stuff.all(): many_stuff.custom_function() def on_save(self, *args, **kwargs): for stuff in self.many_stuff.all(): many_stuff.custom_function() super(MyModel, self).save(*args, **kwargs) When I create a new instance of MyModel through the Django Admin, I want to execute for each Stuff object, a function. It works on_save but I cannot make it work on __init__ for some reason. If I create the new instance, the functions don't get executed. If I save the newly created instance, the functions do get executed. To be more specific, when I use this __init__ method, the model breaks on instance creation with the error: MyModel needs to have a value for field "id" before this many-to-many relationship can be used. I also attempted doing the same thing with the post_save signal, instead of using __init__ and on_save but I had the same problem. On object creation, the function custom_function did not get executed, but it did when I saved the object after it has been created by clicking on the save button. Any ideas? -
Django logs user in by default
I have a Django account, where there is only one user for the entire app. I also have not setup admin for this app. The problem is, when I first start my docker container for the Django app and type in my domain, I am already logged in. Even if I open this in a private window or another browser (Firefox; I normally use Chrome), the issue still remains. This is the script to create the user: from django.contrib.auth.models import User import os # Create user and save to the database if User.objects.exists(): print("user already exists") else: username = os.environ.get("USER_USERNAME") email = os.environ.get("USER_EMAIL") password = os.environ.get("USER_PASSWORD") if not username or not email or not password: print("user information not supplied. please check your .env that USER_USERNAME, USER_EMAIL, USER_PASSWORD are all set.") User.objects.create_user(username, email, password) print("created user") This is called from docker-compose.yml like this: services: web: build: . command: > bash -c "mkdir -p static && python manage.py collectstatic --no-input && python manage.py migrate && python manage.py shell < init/create_user.py && $$RUN_SERVER_COMMAND" Why does this happen? Is there a setting to turn off "logged in by default"? -
Django MultiSelect Dropdown Checkbox to update Models
How can I create a multiselect dropdown checkbox (checked=True, unchecked=False) to update my models? Below is my current code: ###### models.py ####### class TestProfile(models.Model): revenue = models.BooleanField(default=False) costOfRevenue = models.BooleanField(default=False) ###### forms.py ####### class CreateTestProfile(forms.ModelForm): class Meta: model = TestProfile fields = '__all__' ###### views.py ###### def test(request): profile_form = CreateTestProfile() if request.method == 'POST': profile_form = CreateTestProfile(request.POST) if profile_form.is_valid(): profile_form.save() return redirect('/dashboard') else: profile_form = CreateTestProfile() return redirect('/dashboard') dict = {'profile_form': profile_form} return render(request, 'demo/test.html', dict) ###### test.html template ######## <div class="w-1/2"> <form method="POST"> {% csrf_token %} {{profile_form|crispy}} <input type="submit" value="Submit"> </form> </div> If the dropdown is checked for revenue, then I would like to update the TestProfile model's revenue value to be True. Any help would be much appreciated! -
Password field is visible and not encrypted in Django admin site
So to use email as username I override the build-in User model like this (inspired by Django source code) models.py class User(AbstractUser): username = None email = models.EmailField(unique=True) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = [] def __str__(self): return self.email admin.py @admin.register(User) class UserAdmin(admin.ModelAdmin): fieldsets = ( (None, {"fields": ("email", "password")}), (("Personal info"), {"fields": ("first_name", "last_name")}), ( ("Permissions"), { "fields": ( "is_active", "is_staff", "is_superuser", "groups", "user_permissions", ), }, ), (("Important dates"), {"fields": ("last_login", "date_joined")}), ) add_fieldsets = ( ( None, { "classes": ("wide",), "fields": ("email", "password1", "password2"), }, ), ) list_display = ("email", "is_active", "is_staff", "is_superuser") list_filter = ("is_active", "is_staff", "is_superuser") search_fields = ("email",) ordering = ("email",) filter_horizontal = ("groups", "user_permissions",) But this is how it looks like when I go to Admin site to change a user: Password is visible and not hashed and no link to change password form. Comparing to what it looks like on a default Django project: Password is not visible and there's a link to change password form So clearly I'm missing something but I can't figure out what it is.