Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to create multisite django with one database?
I want to create some websites on a server with one database. my structure is: main_domain.com/ main_domain.com/website1 main_domain.com/website2 . . main_domain.com/website_n Some contents are common between websites. I use Django 3 What is best practice for doing this. -
Django Strawberry writing a mutation that includes a foreign key that creates multiple objects
I am trying to have a graphql mutation create the inputs for two django models at once using strawberry. I check the docs here and there were no examples of how to do this. I have the following django model: class Address(models.Model): name = models.CharField() class Person(models.Model): name = models.CharField() address = models.ForeignKey('Address', on_delete=models.CASCADE, blank=False, null=False) With they type.py @strawberry.django.type(models.Address) class Address: id: auto name:auto @strawberry.django.input(models.Address) class AddressInput: id: auto name:auto @strawberry.django.type(models.Person) class Person: id: auto name: auto address:'Address' @strawberry.django.input(models.Person) class Person: id: auto name: auto address:'AddressInput' For the schema.py I have: @strawberry.type class Mutation: createAddress: Address = mutations.create(AddressInput) createPerson: Person =mutations.create(PersonInput) schema = strawberry.Schema(mutation=Mutation) I tried the Mutation but got an error: mutation newPerson ($name: String!, $addressname:String!){ createPerson(data: {name: $name, address: {name: $addressname}}) { id name address { id name } } } #Query Variables { "name": "Min", "addressname": "jkkihh", } Error message: "message": "Field 'id' expected a number but got PersonInput(id=<strawberry.unset._Unset object at 0x00000194FB945C90>, addressname='jkkihh', description=<strawberry.unset._Unset object at 0x00000194FB945C90>, notes=<strawberry.unset._Unset object at 0x00000194FB945C90>)." This is similar the this question I previously asked using graphene. Where it was resolved by making an new object type to store and wrote a mutate function inside a class for mutation. I also … -
HTML min max step validation doesn't work when using javascript to submit
I did use standard html validation for number input (min, max and step). User couldn't write the number exceeding this limit and couldn't use arrows to exceed it either. I had to prevent double clicking Submit button- users sometimes clicked this button very fast and it did add double the objects it supposed to add. So I used some js and jQuery: <script> $(document).ready(function() { $("#addButton").on("click", function() { var $this = $(this); $this.attr('disabled', true); $("#addForm").submit(); }); }); </script> With this way of submiting the form the validation is gone. I still can't use arrows to exceed the limit but user can just type any value. Is there any other way to approach this? I could validate in Javascript but there's a lot of different objects with different validation limits. Or should I ask- is there any other way to prevent double clicking submit button? I use Django and I tried to prevent this action in backend using django-ratelimit but it didn't work like it should @ratelimit(key='ip', rate='2/s') def my_view(request): -
Import "django.db.models" could not be resolved from source / py manage.py makemigrations No changes detected
I am working on a project using django and I am using Visual Studio Code software. In my 'store' directory i have a python package called 'tiendaonline' and the app called "gestionpedidos" where I am trying to create a a Table (DDBB) The problem i am getting is that I cannot create table because when I try to run "py manage.py makemigrations" I can see the msg "No changes detected". Also I can see in the window called problems this msg: " Import "django.db.models" could not be resolved from source " My setting.py is like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'gestionpedidos', ] and my model is this: from django.db import models # Create your models here. class Pedidos(models.Model): numero = models.IntegerField(max_length=100 ) fecha = models.DateField(max_length=300 ) entregado = models.BooleanField() class Clientes(models.Model): name = models.CharField(max_length=30 ) direc = models.CharField(max_length=50 ) Email = models.EmailField() Tel = models.EmailField() class Articulos(models.Model): name = models.CharField(max_length=100 ) seccion = models.CharField(max_length=300 ) price = models.IntegerField() I don't know what is happening. It could give me an adress of migration like "0001_init" but is not running. Thank you -
Set Session Variable in Django Rest Framework
How can i set session variable in DRF view(APIView) and get it in other views of my API. when I set session in any views like request.session['name'] = 'SRJ' I can access this in same view but I cant get it in other views files of API. i know request of django and DRF are different but is there a way to do it ? Thanks for any help -
How to store multiple values inside a foreign key field?
I need to add multiple categories to a brand field. Here is the code class Brand_Category(models.Model): """ this model is use to store the data of products category """ name = models.CharField(max_length=50, unique=True, verbose_name="Brand Category Name") slug = models.SlugField(max_length=140, unique=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) class Brand(models.Model): """ This model is use to store the data of products sub category """ user = models.ForeignKey(User, related_name='brand_user', on_delete=models.CASCADE,null=True,blank=True, default=None) name = models.CharField(max_length=50, unique=True, verbose_name="Brand Name") brand_img = models.FileField(verbose_name='Upload Image') category = models.ForeignKey(Brand_Category, related_name='brand_category', on_delete=models.PROTECT, null=True) slug = models.SlugField(max_length=140, unique=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) I have a brand form where I am adding multiple categories. This categories are stored in the brand_category model, and i would like to save the id of multiple categories into one brand field. how can i add that? i have found about onetomany field in django but it seems to have deprecated, and the other soultions are not similar to my problem. However, a cateogry is not strictly related to any brand -
How to validate the password at DB level in django
I'm trying to register a user with a phone and password, I want to find if the user exists and if the password is the same as we have already on our DB then I want the user to get a login instead of giving an error to that the user with same creds already exists. Now the problem I cant validate the password. I'm trying : registered_user = CustomUser.objects.get(phone_number=data['phone_number']) if make_password(data['password']) == registered_user.passwrod: serializer = UserSerializerWithToken(registered_user, many=False) return Response(serializer.data) But I get registered_user has no attribute password How we can fix this? -
ile "manage.py", line 9, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django'
#!/usr/bin/env python import os import sys if name == "main": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) ~ anyone can explane this code. while ı have trying to run this code with "python manage.py makemigrations" its gives an error: enter image description here but all modules in requrement.txt succsessfully loaded before. -
Administration of different databases of an application with django
I understand how to handle several databases through routers, however, how would it be handled when I have two databases with the same structure but it is required to save the information according to the database chosen by the user when starting a session . I have a session login with its corresponding username and password, in addition to that it is mandatory that the user choose a database through a selector to start the session to the application correctly, this information on the name of the selected database is moves through a session cookie for the entire session (forgive the redundancy), all the operations of the application must be done on the database that was initially selected in the access login, how to correctly route the databases for this case? DATABASES = { 'default' : { 'ENGINE': 'django.db.backends.mysql', 'NAME': env.str('NAME_DB_ZF'), 'USER': env.str('USER_DB'), 'PASSWORD': env.str('PASS_DB'), 'HOST': 'localhost', 'PORT': '3306', }, 'SBOJOZF': { 'ENGINE': 'django.db.backends.mysql', 'NAME': env.str('NAME_DB_ZF'), 'USER': env.str('USER_DB'), 'PASSWORD': env.str('PASS_DB'), 'HOST': 'localhost', 'PORT': '3306', }, 'SBOJOCOL': { 'ENGINE': 'django.db.backends.mysql', 'NAME': env.str('NAME_DB_COL'), 'USER': env.str('USER_DB'), 'PASSWORD': env.str('PASS_DB'), 'HOST': 'localhost', 'PORT': '3306', } } -
What is the fastest way to make plain html/css/javascript website work in Django?
I created a game with HTML/CSS/JavaScript (vanilla) and it really works. Now I want to have users of the same game, so when logged in, they can submit the results and see their place on the list. What are the fastest steps I need to do in order to accomplish that? As my first step, I just want this game to work in Django. -
Django throwing UNIQUE Constraint failed even after adding unique = False
I am developing a custom usermodel for my application in django, by using AbstractUser. But I am getting a UNIQUE constraint failed error while using add user + from django admin. I have also tried to add unique = False in the EmailField class User(AbstractUser): id = models.BigAutoField(primary_key=True) rollno = models.CharField(null=True,unique=True,max_length=15) email = models.EmailField(blank=True,null=True,unique=False) Error : .... return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: Accounts_user.email [28/Jun/2022 05:54:58] "POST /admin/Accounts/user/add/ HTTP/1.1" 500 233697 The add form does not have a email field, submits a blank email. (PS : I can add user by signup form of my application, change user of django admin is also working.)\ -
Show fields for adding password to custom user model - Django
I have a custom user model. I want the admin to create new accounts from the admin panel. Registering a class doesn't help. admin.site.register(CustomUser) *This has the effect of avoiding the possibility of double-entering the password So I try this solution: from django.contrib.auth.admin import UserAdmin admin.site.register(CustomUser, UserAdmin) *In the above option, I have the option to enter the password twice (whean i create user), but the other fields from my custom user model are disappearing. class CustomUser(AbstractUser): name = models.CharField(max_length=50, blank=True, null=True) surname = models.CharField(max_length=50, blank=True, null=True) account_type = models.ForeignKey(Locationd, on_delete=models.CASCADE, blank=True, null=True How to add the ability to create accounts in the admin panel, giving a password that can be sent to the new user and editing all fields from the custome user class. ) -
I made a form and doesn't save to my database in django
Hey I just started learning django , and i had a problem in registration form , it doesn't save to my database , i've tried a lot of things and none if works for me i don't know where the problem is , and when i try to add it from python shell it worked but not from html i would love to if someone figure it out : models.py: class Register(models.Model): Username = models.CharField(max_length=255) email = models.EmailField(max_length=255) password = models.CharField(max_length=255) con_password = models.CharField(max_length=255) def __str__(self): return ( f"{self.Username}" f"{self.email}" ) views.py : def register(request): if request.method == "POST": form = Register(request.POST) if form.is_valid(): form.save(commit=False) form.save() return redirect('/') #redirect after saving form = Register() return render(request, "register.html", {'form': form}) register.html : {% block content %} <section id="hero" class="login"> <div class="container"> <div class="row justify-content-center"> <div class="col-xl-4 col-lg-5 col-md-6 col-sm-8"> <div id="login"> <div class="text-center"><img src="{% static 'touriste/img/logo_sticky.png' %}" alt="Image" data-retina="true"></div> <form method="post"> {% csrf_token %} {{ form.as_p }} <div class="form-group"> <label for="Username">Username</label> <input type="text" name="Username" class=" form-control" required placeholder="Username"> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" name="email" class=" form-control" required placeholder="Email"> </div> <div class="form-group"> <label>Password</label> <input type="password" name="password" class=" form-control" required id="password" placeholder="Password"> </div> <div class="form-group"> <label>Confirm password</label> <input type="password" name="con_password" class=" … -
Django + Apache2 behind NGINX reverse proxy - redirections going wrong
I have a Django project running on Apache2 with mod_wsgi in a VM - https://systems3.slt.local/ Accessing the VM directly, via https://systems3.slt.local/ works perfectly. However, I need it to work behind an NGINX reverse proxy, and I'm having problems with login redirection. My proxy is configured like this: location /systems3 { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_redirect off; proxy_pass https://systems3.slt.local/; } When I try to access the project through the proxy, https://example.org/systems3 , Django checks that there is no user logged in, and then redirects to https://example.org/**accounts/login**. The correct would be to redirect to https://example.org/**systems3/accounts/login**. Even if I try to directly access this address, I am redirected to https://example.org/accounts/login. It seems that some configuration is missing so that the address https://example.org/systems3 is the root of the project, it shouldn't be redirecting me outside of systems3. It's also giving problem with my static folder, it also looks for the folder at https://example.org/static, ignoring that it was supposed to look inside systems3. -
Convert a basic sql query to django query
I want to display the course name along with the question count in a table. Need help to convert below query to a django query: SELECT DISTINCT exam_course.course_name, COUNT(exam_question.question) FROM exam_course INNER JOIN exam_question ON exam_question.course_id = exam_course.id GROUP BY exam_question.course_id -
How to Properly Display RenderedMarkdownField() on Template when "safe" Isn't "Working"?
On my django website, I'm using a RenderedMarkdownField() to make some fancy looking description text on my posts. My model looks like this: # Portfolio project overview model class Work(models.Model): title = models.CharField(max_length=100) # description = models.TextField() description = MarkdownField(rendered_field='description_rendered', validator=VALIDATOR_STANDARD) description_rendered = RenderedMarkdownField() image = models.ImageField(upload_to="work_app/media/images/", null=True, blank=True) video = models.FileField(upload_to="work_app/media/videos/", null=True, blank=True) pdf = models.FileField(upload_to="work_app/media/documents/", null=True, blank=True) # To show the title in the Admin page def __str__(self): return self.title Then my work_index.html page looks like this when rendering each project from my database (personally identifying/crucial info scratched out): As you can see, the Markdown characters in the description text (the *'s) are visible in this description. To fix this, we use Django's safe tag and render the work.description_rendered field instead, so my code when iterating through each post looks like this: <div class="row"> {% for work in works %} <div class="col-md-4"> <div class="card mb-2"> <a href="{% url 'work_detail' work.pk %}"> <img class="card-img-top" src="{{ work.image.url }}"> </a> <div class="card-body"> <a href="{% url 'work_detail' work.pk %}"> <h5 class="card-title project-title-link">{{ work.title }}</h5> </a> <p class="card-text">{{ work.description_rendered | safe | truncatechars:200 }}</p> <a href="{% url 'work_detail' work.pk %}" class="btn btn-primary"> Read More </a> </div> </div> </div> {% endfor %} </div> ...HOWEVER, … -
Django: Accessing reusable app in settings.py
I have a reusable django app installed in my project, and the desired outcome is to import it into the main project's settings.py. The project runs well with the reusable app installed and added into INSTALLED APPS in settings.py. However, when I try to import it in settings.py, django throws an error. django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I think it has something to do with Django not loading the reusable app in time before the imports, but I'm not sure how to solve this. Any suggestions are much appreciated! -
part a custom user model into two apps, but custom user model app override the 2nd app
I have searched a lot to any related to my problem but never found what i need I am trying to create a simple Django blog that has a custom user model inherit the core authentication AbstractUser class in app named user user.models.py class User(AbstractUser): email = models.EmailField('email_address', unique=True) USERNAME_FIELD = 'email' and another account app that has been parted the login and profiles of authenticated users account.models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile_user', on_delete=models.CASCADE) the settings.AUTH_USER_MODEL above is the same User that already been imported from user app user.models import User and already been identified in settings.py When i started to makemigrations and migrate i found no problems, but when i went to my PostgreSQL pgAdmin to see database tables i fount all tables except the account_profile table although there are another class in account i found it's table but no Profile as it never been created Also when i tried to create superuser, i got the same notation that : psycopg2.errors.UndefinedTable: relation "account_profile" does not exist LINE 1: INSERT INTO "account_profile" ("user_id", "city_id", "phone... should i have to put the Profile class in account.models.py in user.models.py together or what exactly should i do, please help and sorry for … -
Django - ModelForm - Filter by user
I need to filter in EmployeeForm just to show me options of Companies related to user is logged in. I'm using ModelForm and CreateViews This is my code: models.py class Company(models.Model): reg_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=255) cuit = models.CharField(max_length=20) class Employee(models.Model): company = models.ForeignKey(Empresa, on_delete=models.CASCADE) name = models.CharField(max_length=255) cuil = models.CharField(max_length=20) forms.py class EmployeeForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ... self.fields['name'].widget.attrs['autofocus'] = True What is the code I need to write in the ellipses? It's currently showing me all companies even ones not owned by the user. Thanks in advance. -
How do I copy to the clipboard in JavaScript? tell me
i used this code const copyBtns = [...document.getElementsByClassName('copy')] copyBtns.forEach(btn=> btn.addEventListener('click', ()=>{ content = btn.getAttribute('data-content') navigator.clipboard.writeText(content) btn.textContent = "تم النسخ" })) copy not working on click in mobile, and it's working with any computer. what is the solution? -
HTML template for displaying forms only if form.DELETE doesn’t exist
I want to achieve something like this, actually "DELETE" shouldn’t exist in form itself, or if it does it should be switched off or not checked. {% if not form.DELETE %} <div class="input-form"> <div class="col-md-12 mb-4 mt-4"> {{ form }} </div> </div -
get all many to many field values + the rest of the model fields in a general query to db
I am studing django and I want to do an API endpoint that brings all the employees in the database with all the fields, including the languages field which has a manyToMany relationship to Languages Model. class Employee(models.Model): name = models.CharField(max_length=50) lastname = models.CharField(max_length=50) salary = models.PositiveBigIntegerField() position = models.ForeignKey(Position, on_delete=models.CASCADE, related_name='employees') languages = models.ManyToManyField(Languages, related_name='employees') def __str__(self): return f'{self.name} {self.lastname}' class Languages(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name I managed to do this but with a query that gets only one employee try: emp = Employee.objects.get(id=id) data = { 'name': emp.name, 'lastname': emp.lastname, 'salary': emp.salary, 'position': emp.position.name, 'languages': [x['name'] for x in emp.languages.all().values()] } except ObjectDoesNotExist: return JsonResponse({"message": "No company found"}) except Exception as ex: return JsonResponse({"message": "Something went wrong."}) return JsonResponse({"message": "success", "data": data}) But now I can't do the same with a query such as Employee.objects.all() or Employee.objects.values(). This is what I would need but with all the employees at once: { "message": "success", "data": { "name": "Fred", "lastname": "Wilson", "salary": 28000, "position": "CTO", "languages": [ "JavaScript", "PHP" ] } } I've tried a lot of things including prefetch but I couldn't get it to work. -
How to pass variable from view.py to javascript without using render() in django
return render(request, 'index.html', {"flag": flag, "form": form}) I want to pass flag value which should be read by javascript to change style of an element in template, but since rendering it again the flag value is lost and set back to "none" ,is there any way to not use render and pass the variable to a url where the page is already rendered -
Django app return error when connecting to Postgres Database django.db.utils.OperationalError
I have a Django web app that connects to a postgres database in Azure, some days ago this was working fine, but now i receive the following error when I run the server: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 244, in ensure_connection self.connect() File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 225, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\postgresql\base.py", line 203, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server at "exampleyv.postgres.database.azure.com" (52.182.136.38), port 5432 failed: FATAL: no pg_hba.conf entry for host "186.31.127.234", user "exampleyv", database "exampleyv", SSL on The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run self.check_migrations() File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 576, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\loader.py", line 58, in __init__ self.build_graph() File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File … -
Django-native/ORM based approach to self join
Trying to set up a Django-native query that grabs all rows/relationships when it shows up on the other side of many-to-many relationship. I can explain with an example: # Django models class Ingredient: id = ... name = ... ... class Dish: id = ... name = ... ... class IngredientToDish # this is a many to many relationship ingredient_id = models.ForeignKey("Ingredient", ...) dish_id = models.ForeignKey("Dish", ...) ... I'd like a Django-native way of: "For each dish that uses tomato, find all the ingredients that it uses". Looking for a list of rows that looks like: (cheese_id, pizza_id) (sausage_id, pizza_id) (tomato_id, pizza_id) (cucumber_id, salad_id) (tomato_id, salad_id) I'd like to keep it in one DB query, for optimization. In SQL this would be a simple JOIN with itself (IngredientToDish table), but couldn't find what the conventional approach with Django would be... Likely uses some form of select_related but haven't been able to make it work; I think part of the reason is that I haven't been able to succinctly express the problem in words to come across the right documentation during research. Any help would be appreciated... thank you!!