Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error in uploading image from a react form into django model using django rest framework
I am building a website using Django and React I want to create a form that enters data into a model containing image field. I have followed many tutorials to make this but I have failed to upload image into the Image field models.py: class entry(models.Model): title = models.CharField(max_length=600) body = models.TextField() entryCover = models.ImageField(upload_to='entrycover', blank=True, null=True) def __str__ (self): return self.title serializers.py: class EntryFormSerializer(serializers.ModelSerializer): entryCover = serializers.ImageField(required=False) class Meta: model = entry fields = ['title', 'body', 'entryCover'] views.py: class EntryFormViewSet(viewsets.ModelViewSet): queryset = entry.objects.all() serializer_class = EntryFormSerializer parser_classes = (MultiPartParser, FormParser) def post(self, serializer): serializer.save(creator=self.request.user) urls.py: urlpatterns = [ path('entryForm/', views.EntryFormViewSet) ] in Form.js: import React from "react"; import Select from 'react-select' import axios from 'axios'; import { AxiosInstance } from "axios"; export default function Form(){ const [inputs, setInputs] = React.useState({}); const handleImageChange = (e) => { console.log(e.target.files[0]) let image = e.target.files[0] setInputs(values => ({...values,'entryCover' : image})) }; const handleChange = (event) => { const name = event.target.name; const value = event.target.value; setInputs(values => ({...values, [name]: value})) } const handleSubmit = (event) => { event.preventDefault() let form_data = new FormData(); form_data.append('entryCover', inputs.entryCover, inputs.entryCover.name); form_data.append('title', inputs.title); form_data.append('body', inputs.body); axios.post('/entryForm/', form_data, { headers: { 'Content-Type': 'multipart/form-data' } }).then(res => { console.log(res); }).catch(err … -
Prevent the user from going to the URL manually
I am writing a website on the Django framework I have a user application in which authorization, registration, password change, user password reset are configured I have a url: auth/password_change/ that processes a view of the PasswordChangeView class embedded in Django with a form for changing the user's password and, if successful, redirects to the url: auth/password_change_done/ auth/password_change_done/ handles the representation of the PasswordChangeDoneView class built into Django, which handles a template that says: you have successfully changed your password But any authorized user, even without changing the password, can manually go to the URL auth/password_change_done/ and get the page to which the redirect should go only if the password is successfully changed Tell me how to make it so that no one can manually get to the URL auth/password_change_done/, but only if the password has been successfully changed I tried to use re_path, but it has nothing to do with it at all I need some other way I will be grateful to everyone -
Django admin page formatting is messed up
Picture of formatting I made some updates to my django backend that is running on an azure app service and suddenly the formatting is all broken, see above. I tested it on a local server and the formatting is perfectly normal so I'm very confused, has anybody experienced a similar issue before or have any ideas on what could cause this? EDIT: Wanted to add that I checked the web browsers inspector logs and found errors saying that "the resource from [url] was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff)." I assume thats the issue but I'm unsure how to fix that through azure -
Django App not able not able to run on Heroku Container
I am trying to build and deploy a Django app using docker images with heroku.yml, but I am having issues running the app. All I get is application error, which might be related to the configuration I have. Attached below is the Dockerfile and the heroku.yml: Dockerfile FROM python:2.7.17 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -U pip RUN pip install -r requirements.txt COPY . /code/ EXPOSE $PORT CMD ["uwsgi", "--ini", "uwsgi/production/uwsgi.ini"] heroku.yml build: docker: web: Dockerfile run: web: command: - uwsgi - --ini - uwsgi/production/uwsgi.ini image: web -
KeyError: 'ATOMIC_REQUESTS' when running DRF tests with mysqlclient installed
I have a functioning test suite for DRF. It uses @pytest.mark.django_db() to access an SQL Server DB. I now have the need to access an ancillary MySQL DB, so I installed mysqlclient. Without changing any of my source code or django settings, intalling this package alone breaks my test suite. Note, that the actual mysqlclient seems to work fine and allows me to access the ancillary MySQL DB. This is the error django/core/handlers/base.py(348)make_view_atomic() def make_view_atomic(self, view): non_atomic_requests = getattr(view, "_non_atomic_requests", set()) for alias, settings_dict in connections.settings.items(): > if settings_dict["ATOMIC_REQUESTS"] and alias not in non_atomic_requests: E KeyError: 'ATOMIC_REQUESTS' I have tried using this: @pytest.mark.django_db(databases=["default"]) to isolate things to the SQL Server DB. It doesn't help. I have tried setting ATOMIC_REQUESTS in settings and it doesn't stick. DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': os.environ['DATABASE'], 'USER': os.environ['USERNAME'], 'PASSWORD': os.environ['PASSWORD'], 'HOST': os.environ['SERVER_URL'], "ATOMIC_REQUESTS": True, 'OPTIONS': { 'driver': 'ODBC Driver 18 for SQL Server', 'extra_params': "Encrypt=no" }} In the debugger, it doesn't show 'ATOMIC_REQUESTS' in the settings. ipdb> settings_dict {'ENGINE': 'mssql', 'HOST': 'localhost', 'NAME': 'dev'} -
Testing 500 error code in django rest API unit test
I am working on unit tests for my API endpoints which I have built using Django rest_framework. I was able to test most of the error codes related to my endpoint except the 500 error code. Is there are way to mock the client function to return 500 error response or any cleaner way in unit test framework? class UserApiTests(TestCase): def setUp(self): self.client = APIClient() ... def test_retrieve_user(self): """Test server failure while retrieving profile for user.""" res = self.client.get(USER_URL) # Below should return server error self.assertEqual(res.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR) -
Django using database without migration
I have a Django application running using MySQL database, and everything works fine. For another part of the same application, I want to create a new Django application, implement database sharding, and have a separate database to store the tracking data and use the existing database (used by previous Django application) for authentication and other stuff. But since I need to get data from the existing database using Django ORM, I created models with the required-only fields in the new application as well. # authentication.models.User class User(AbstractUser): email = models.EmailField('email address', blank=True, unique=True) is_shared = models.BooleanField(verbose_name='Is Shared User', default=False) class Meta: app_label = 'authentication' managed = False I want to use this model for authentication in the admin panel as well (the same is used in the existing application). But I do not want this new application to migrate changes to the master database, so added managed=False in the Meta class. The settings.py file is AUTH_USER_MODEL = 'authentication.User' DATABASE_ROUTERS = [ 'app.database_routers.tracking.TrackingRouter' ] DATABASES = { 'default': eval(os.environ.get('DATABASE_MASTER')), 'database_tracking': eval(os.environ.get('DATABASE_TRACKING')) } where the default database has to be used for authentication and access to the admin panel. Migration should not write to this database as the migration should only be … -
Uncaught TypeError: Cannot read properties of null (reading 'classList') Django extends
I know this is bit common to ask but I'm still confused why it didn't read the classlist it says error in the console. I just want to pops the toaster when button was click I've tried putting js scripts in different places because The JS script tag should run after the HTML elements have been declared. The DOM element exists before accessing, still don't have any idea why it doesn't work what I did. <script src="{% static 'assets/vendor/libs/toastr/toastr.js' %}"></script> <script src="{% static 'assets/js/ui-toasts.js' %}"></script> transaction.html <button type="button" class="btn btn-label-primary add-data">Click button</button> {% block footer_scripts %} <script> $(document).ready(function(){ $('.add-data').click(function (event) { const toastAnimationExample = document.querySelector('.toast-ex'); let selectedType, selectedAnimation, selectedPlacement, toast, toastAnimation, toastPlacement; if (toastAnimation) { toastDispose(toastAnimation); } toastAnimationExample.classList.add('animate__fadeInRight'); toastAnimationExample.querySelector('.ti').classList.add('text-success'); toastAnimation = new bootstrap.Toast(toastAnimationExample); toastAnimation.show(); // Dispose toast when open another function toastDispose(toast) { if (toast && toast._element !== null) { if (toastPlacementExample) { toastPlacementExample.classList.remove(selectedType); toastPlacementExample.querySelector('.ti').classList.remove(selectedType); DOMTokenList.prototype.remove.apply(toastPlacementExample.classList, selectedPlacement); } if (toastAnimationExample) { toastAnimationExample.classList.remove(selectedType, selectedAnimation); toastAnimationExample.querySelector('.ti').classList.remove(selectedType); } toast.dispose(); } } }); }); </script> {% endblock footer_scripts %} -
Django Rest Framework Mock Test
I have a requirement where I need to execute testcases of a view that uploads data to cloud when the create method is called. I want to mock this view to verify create functionality without the file upload happening. Can you please tell me Which DRF library I need to use? thank you. -
How to specify 2 différents source for a same package when in prod or in dev when using poetry?
I am using Python / Poetry to manage my virtual environment. I would like to install django-listing from pypi when in production but use a local version of django-listing when developping, so I wrote this pyproject.toml file : [tool.poetry] ... [tool.poetry.dependencies] python = "^3.11" Django = "^4.1.7" ... [tool.poetry.group.prod] optional = true [tool.poetry.group.prod.dependencies] django-listing = "^0.0.15" [tool.poetry.group.dev] optional = true [tool.poetry.group.dev.dependencies] django-listing = {path = "../django-listing", develop = true} [build-system] requires = ["poetry-core"] build-backend = "poetry.core.masonry.api" When I do : poetry install --with prod --without dev It is always the develop version of django-listing that is used : why ? This is the same thing if I clear caches and if I remove/re-create the environment : how can I proceed ? I am using Poetry 1.4 and python 3.11 -
How to add username in urls with OneToOne field
I have model and serializer and i want api to use username not pk How can i do that? I actually tried to use lookup field but thats not rly working models.py class IndividualUser(models.Model): individual_user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) first_name = models.CharField(_("first name"), max_length=150) last_name = models.CharField(_("last name"), max_length=150) urls.py path('api/profile/<str:individual_user>/', IndividualClientDetailApiView.as_view()), views.py class IndividualClientDetailApiView(generics.RetrieveAPIView): queryset = IndividualUser.objects.all() serializer_class = IndividualClientSerializer permission_classes = (IsAuthenticated, IsOwnerOrAdminOrReadOnly) lookup_field = 'individual_user' -
Incorporating a blog into a django project
So, I have built an ecommerce app, so a primary use case is to sell products, but I also have a blog page, my question is to what is the best way to tackle this? Is it to use a WYSIWYG like CKEditor which I am currently using or are there better ways. The blogs will be simple with normal photo uploads. -
Django 3.2.3 trying to access admin url getting 403 CSRF verification failed
Settings.py MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CSRF_COOKIE_SECURE = False # Hosted with Apache 2 with no SSL. I'm trying to access my admin section. -
twilio: KeyError: 'TWILIO_ACCOUNT_SID'
client = Client(os.environ['TWILIO_ACCOUNT_SID'], os.environ['TWILIO_AUTH_TOKEN']) ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^ File "", line 679, in getitem KeyError: 'TWILIO_ACCOUNT_SID' alwise shows the error import os import sys from twilio.rest import Client from twilio.base.exceptions import TwilioRestException client = Client(os.environ['TWILIO_ACCOUNT_SID'], os.environ['TWILIO_AUTH_TOKEN']) verify = client.verify.services(os.environ['TWILIO_VERIFY_SERVICE_SID']) def send(phone): verify.verifications.create(to=phone, channel='sms') def check(phone, code): try: result = verify.verification_checks.create(to=phone, code=code) except TwilioRestException: print('no') return False return result.status == 'approved' -
Deploy multiple services in docker-compose.yml using hub, on own server (django)
I've a Django project, and i'm using docker with a docker-compose file + DockerFile and .env folder with user/pass for access. Locally, it's working fine. I wonder if I can push all the services (web, postgres and pgadmin) in the same times. After, on my own server, I would pull them all. For now, I push 2 services (web + postgres) on the docker's hub, and pull them. But when I run the postgres/postgis image with "-e" parameter. But I don't like this solution because the docker-compose file don't "help me" to deploy. And, how can I use the ".env/" folder (see docker-compose.yml) instead of using "-e" parameter ? #./dj/docker-compose.yml version: '3.7' services: web: env_file: - ./env/django.env build: context: ./my_project dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 container_name: web_container_my_project image: my_company/my_project_web_api_my_project volumes: - ./my_project:/opt/my_project ports: # HOST:CONTAINER - "8050:8000" depends_on: - db restart: always db: environment: - TZ=Europe/Paris env_file: - ./env/postgresql.env image: postgis/postgis container_name: postgres_container_my_project hostname: db volumes: - /var/lib/postgresql/data-my_project:/var/lib/postgresql/data ports: # HOST:CONTAINER - "5433:5432" restart: always pgadmin: env_file: - ./env/pgadmin.env image: dpage/pgadmin4 container_name: pgadmin_container_my_project ports: # HOST:CONTAINER - "8059:80" volumes: - /var/lib/pgadmin/data:/var/lib/pgadmin/data links: - "db:pgsql-server" restart: always logging: driver: none volumes: pgadmin_data: postgres_data: driver: local Thanks a lot F. -
React TypeError: Cannot read properties of undefined (reading 'source')
I am getting this error from my frontend when i tried to register a new user, the error message from my useEffect hooks each time i click the register button Cannot read properties of undefined (reading 'source') Here is the code snippet function Register() { const navigate = useNavigate(); const [sendRequest, setSendRequest] = useState(false); const [usernameValue, setUsernameValue] = useState(''); const [emailValue, setEmailValue] = useState(''); const [passwordValue, setPasswordValue] = useState(''); const [password2Value, setPassword2Value] = useState(''); function FormSubmit(e) { e.preventDefault(); console.log('The form has been submitted'); setSendRequest(!sendRequest) } useEffect(() => { if (sendRequest) { const source = Axios.CancelToken.source(); async function SignUp() { try { const response = await Axios.post( "http://localhost:8000/apiv1-auth-djoser/users/", { username: usernameValue, email: emailValue, password: passwordValue, re_password: password2Value, }, { cancelToken: source.token } ); console.log(response); } catch (error) { console.log(error.response) } } SignUp(); return () => { source.cancel(); }; } }, [sendRequest]); return ( <div style={{ width: "50%", marginLeft: "auto", marginRight: "auto", marginTop: "3rem", border: "5px solid black", padding: "3rem", }} > CREATE AN ACCOUNT <Grid item container style={{ marginTop: "1rem" }}> <TextField id="username" label="Username" variant="outlined" fullWidth value={usernameValue} onChange={(e) => setUsernameValue(e.target.value)} /> </Grid> <Grid item container style={{ marginTop: "1rem" }}> <TextField id="email" label="Email" variant="outlined" fullWidth value={emailValue} onChange={(e) => setEmailValue(e.target.value)} /> </Grid> <Grid … -
Cannot redirect logged in users to home page in django
When I log in I cannot get the site to redirect me to the home page. Instead, it simply logs me out again. urls.py urlpatterns = [ path("", views.home, name='home'), path("accounts/login/", views.login, name="login"), path("accounts/register/", views.register, name="register"), path("accounts/", include("django.contrib.auth.urls"), name="accounts"), path("search/", views.search), ] views.py def home(request): return render(request, template_name="home.html", context={"session":request.session.items}) def login(request): if (request.method == "POST"): form= UserLoginForm(request.POST) user = authenticate(username=request.POST["username"], password=request.POST["password"]) if (user.is_authenticated): user.save() return HttpResponseRedirect(reverse("home", kwargs={"user":user})) else: return render(request, "registration/register.html", {}) else: return render(request, "registration/login.html", {}) Then I handled logging in and registering by inheriting the default classes used for that. So this is what it looks like: forms.py class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) username = forms.CharField(max_length=32, help_text='username') class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user class UserLoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(UserLoginForm, self).__init__(*args, **kwargs) username = UsernameField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': '', 'id': 'hello'})) password = forms.CharField(widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': '', 'id': 'hi', } )) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user Lastly the error is: django.urls.exceptions.NoReverseMatch: Reverse for 'home' with … -
Danjgo Model update_or_create with field pre-processing
I am new to Danjgo and it maybe a simple thing, but random searching does not seem to have helped. I am using Django Ninja API example, but I think this is not about Ninja. In a simple model e.g. models.py class Person (models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) schemas.py class PersonIn(ModelSchema): class Config: model = Person model_fields = ["first_name", "last_name"] I want to have simple create/read api e.g. api.py def create_person(request, payload: PersonIn): data = payload.dict() try: person, created = Person.objects.update_or_create(**data) except Exception: return { "mesg": "Some error happened"} What I wanted was to ensure that First Name and Last names are capitalized, before storing in DB. I found that one method is to override Model method .save class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def save(self, *args, **kwargs): self.first_name = self.first_name.capitalize() self.last_name = self.last_name.capitalize() super().save(self, *args, **args) But, in this case update_or_create always creates a new object as it first checks for lower case fields and never finds it. I also found that one can overwrite .clean method class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def clean(self): self.first_name = self.first_name.capitalize() self.last_name = self.last_name.capitalize() In this caseI understand I need to call .clean method manually. But … -
Handling a JSON API with Django and putting the data in a model
I have a basic JSON API with some data, I need to dynamically get this data in python and put it in a model, more basically, Let's say the API is for cars, each car has a name and model, how to get the data from the JSON API for cars and put in a model called "Car" in models.py? I searched but I couldn't find a way to do that. -
how to post images from client side to Next.js API endpoint and then to Django REST Framework API
I attempted to create a feature that allows users to upload product images to an ecommerce website. My plan initially was to receive the form submission from the client side in Next.js, and then pass it to the built-in Next.js API endpoint. I wanted to add an authorization token to the header and post it to the Django REST framework API, where I save the image and connect it to the user model using a foreign key. Although posting the image directly from the client side to the Django server worked well, I needed to add an authorization token to the header to retrieve the user in the backend. As I used the HTTP-only method, so I had to post it to the Next.js API endpoint. The problem is I keep running in to is when I post it to the api end point I couldn’t get the image directly to repost it to a djano api end point. Any help would be appreciated. Nextjs client side code. import React,{useState} from 'react' import { useSelector} from 'react-redux'; import { Oval } from 'react-loader-spinner'; function ProductUpload() { const loading = useSelector(state => state.auth.loading) const [formData, setFormData] = useState({ name: '', alt: … -
Django not getting static files in Docker
im not getting any static files in my django app when running docker with nginx. Can someone please look at my config and point out where the issue is? Let's start with Dockerfile for the app from python:3.11-slim-buster ENV PYTHONUNBUFFERED=1 ENV PYTHONWRITEBYTECODE 1 WORKDIR /usr/src/app COPY requirements.txt requirements.txt RUN pip install --no-cache-dir -r requirements.txt COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] COPY . . In entrypoint.sh we can find python manage.py collectstatic --no-input gunicorn core.wsgi:application --bind 0.0.0.0:8000 --reload docker-compose for the app version: "3.11" services: app_django: build: . volumes: - .:/usr/src/app/ - staticfiles:/usr/src/app/staticfiles ports: - 8000:8000 env_file: - .env image: app_django:django container_name: meant_container nginx: build: context: ./nginx/ ports: - 80:80 volumes: - ./nginx/conf.d/:/etc/nginx/conf.d/ - staticfiles:/home/app/staticfiles container_name: nginx_container volumes: staticfiles: here is docerfile for nginx FROM nginx:1.24-alpine RUN mkdir -p /home/app/staticfiles and Nginx cofig upstream dserver { server app_django:8000; } server { listen 80; location / { proxy_pass http://dserver; } location /static/ { alias home/app/staticfiles/; } } here is folder location django settings STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / "staticfiles" -
How to add extra columns for a model if in particular category in Django + Postgres
I need to add extra columns if product is in a particular category. I thought of using JSON or allowing null columns, but is there any better way of handling this situation. I'm using Postgresql database. Here are my model structure. class Product(Base): def __str__(self): return self.name name = models.CharField(max_length=255, unique=True, validators=[validate_alphanumeric]) is_safari = models.BooleanField(default=True) Product table has mapped to agents like this class Agent(Base): def __str__(self): return self.agent_user.username agent_user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.RESTRICT, ) country = CountryField() city = models.CharField(max_length=255) AgentProduct model class AgentProduct(Base): agent = models.ForeignKey( Agent, on_delete=models.RESTRICT, ) product = models.ForeignKey( Product, on_delete=models.RESTRICT, ) a_rate = models.IntegerField() c_rate = models.IntegerField() I would like to add some extra information if is_safari is true to the AgentProduct model like per_v_charge = models.IntegerField() extra_p_charge = models.IntegerField() # something like this -
'TemporaryUploadedFile' object has no attribute 'get'
I'm getting this error every time I'm trying to upload video file, and I think the problem is come from the moviepy library that I'm using to cut every video that are higher than 10 minute. the error: AttributeError at /CreateVideo 'TemporaryUploadedFile' object has no attribute 'get' views: from moviepy.video.io.VideoFileClip import VideoFileClip from django.core.exceptions import ValidationError def create_video(request): if request.method == 'POST': title = request.POST['title'] video = request.FILES['video'] banner = request.FILES['banner'] video_file = video video_clip = VideoFileClip(video_file.temporary_file_path()) duration = video_clip.duration video_clip.close() if duration > 600: # 10 minute in seconds raise ValidationError('the video cannot be longer than 10 minute') return video_file new_video = Video.objects.create( user=request.user, title=title, video=video, banner=banner ) new_video.save() return redirect('Video') return render(request, 'video/create_video.html') models: class Video(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=70) video = models.FileField(upload_to='videos') created_on = models.DateTimeField(auto_now_add=True) banner = models.ImageField(upload_to='banner') slug = models.SlugField(max_length=100, unique=True) -
How to organize Django REST Framework urls
so I am working on some dummy e-commerce application in Django (DRF) and I am a bit confused how to write good REST API's. Models class Category(models.Model): name = models.Char... class Product(models.Model): category = models.ForeignKey(...) name = models.Char... Views class ProductListView(APIView): def get(self, request, category_slug=None): products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) serializer = ProductSerializer(products, many=True) return Response(serializer.data, status=status.HTTP_200_OK) First Question So my question is if I should put logic for filtering with capture value (categori_slug) in this view or would it be more clear if I create two endpoints? Second Question In DRF is bottom code good practice to send multiple data trough result/endpoint? return Response({data: serializer.data, other_data: serializer_other.data}, status=st...) So as I am learning all the time only one serializer.data is passed trough one Response API but what if I want that client can also access some other data. Is better to split it in multiple views and than let client make multiple requests? PS: This is my first Stackoverflow question so I would appreciate some feedback on this as well. -
How to use 'auth_user' table of remote database in django?
I want to access 'auth_user' table from another Django project and use it in my current Django project. I am using database routers:- DATABASE_ROUTERS = ['to.your.router.CurrentRouter'] DATABASES = { 'default': eval(os.environ.get('DATABASE_REMOTE', str(DEFAULT_DATABASE))), 'database_current': eval(os.environ.get('DATABASE_CURRENT', str(DEFAULT_DATABASE))) } class CurrentRouter: route_app_labels = { 'admin', 'contenttypes', 'sessions', 'tracking', 'data_collect' } def __str__(self): super().__str__() def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'database_current' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'database_current' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'database_current' return None How can i use 'auth_user' table from DATABASE_REMOTE for logging into django admin panel and delete object from DATABASE_CURRENT. And how to set permission deleting objects in current database using User of remote database? For logging into admin panel using remote database user I have used custom authentication. https://docs.djangoproject.com/en/4.2/topics/auth/customizing/ class CustomAuthenticationBackend(BaseBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: user = User.objects.get(email=username) except ObjectDoesNotExist: return None if user.check_password(password): return user else: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except ObjectDoesNotExist: return None But when deleting an object from DATABASE_CURRENT using the DATABASE_REMOTE 'User' …