Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django with MySQL: 'Subquery returns more than 1 row'
Using django with a MySQL DB and given these models: ModelB ---FK---> ModelA - c_id ModelC I want to get all the ModelC for each ModelA via an annotation. I tried many options looking at existing solutions but could not make it work. The following code works when there is just one ModelC for each ModelA but as soon as there is more than one, I get the Subquery returns more than 1 row error and I don't know how to get a list of the ModelC models instead. I tried to build a list of JSON objects of the ModelC without success. qs = ModelA.objects.all() c_ids = ( ModelB.objects \ .filter(modela_id=OuterRef(OuterRef('id'))) \ .values('c_id') ) all_c = ( ModelC.objects \ .filter(id__in=Subquery(c_ids)) \ .values('id') ) qs1 = qs.annotate(all_c=Subquery(all_c )) for p in qs1: print(p, p.all_c) -
IIS Django localhost opens list of directories
I am trying to deploy a Django app on IIS. After a few days of FINALLY getting HTTP Platform Handler to work now i face another problem right now when i go to local host i see a list of files in my Django app. how do i make it start the Django app right away. i am using HTTP Platform Handler. <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="httpplatformhandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" requireAccess="Script" /> </handlers> <httpPlatform startupTimeLimit="10" startupRetryCount="10" stdoutLogEnabled="true" processPath="C:\Python310\python.exe" arguments="manage.py runserver"> <environmentVariables> <environmentVariable name="foo" value="bar"/> </environmentVariables> </httpPlatform> </system.webServer> </configuration> -
Can I use an annotated subquery parameter later on in the same query?
I have a Django queryset that ideally does some annotation and filtering with 3 object classes. I have Conversations, Tickets, and Interactions. My desired output is Conversations that have 1. an OPEN ticket, and 2. exactly ONE interaction, of type mass_text, since the ticket's created_at date. I am trying to annotate the conversation query with ticket_created_at & filter out Nones, then somehow use that ticket_created_at parameter in a subsequent annotation/subquery to get count of interactions since the ticket_created_at date. Is this doable? class Interaction(PolymorphicModel): when = models.DateTimeField() conversation = models.ForeignKey(Conversation) mass_text = models.ForeignKey(MassText) class Ticket(PolymorphicModel): created_at = models.DateTimeField() conversation = models.ForeignKey(Conversation) status = models.CharField() ######################################################## open_ticket_subquery = ( Ticket.objects.filter(conversation=OuterRef("id")) .filter(status=Ticket.Status.OPEN) .order_by("-created_at") ) filtered_conversations = ( self.get_queryset() .select_related("student") .annotate( ticket_created_at=Subquery( open_ticket_subquery.values("created_at")[:1] ) ) .exclude(ticket_created_at=None) .annotate(interactions_since_ticket=Count('interactions', filter=Q(interactions__when__gte=ticket_created_at))) .filter(interactions_since_ticket=1) This isn't working, because I can't figure out how to use ticket_created_at in the subsequent annotation. -
Django UUIDField shows 'badly formed hexadecimal UUID string' error?
I have written a model before and used the UUIDField and everything worked perfectly well, now i tried doing exactly the same thing but i get the error badly formed hexadecimal UUID string, i don't know if i messed something up. I have imported the uuid package and the field goes thus id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False). I have also tried adding ..., default.uuid.uuid4() BUT it does not still work, but might the problem and best fix? class Group(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4(), editable=False) image = models.ImageField(upload_to=user_directory_path, null=True, blank=True) channel_name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) keywords = TaggableManager() joined = models.DateTimeField(auto_now_add=True) status = models.CharField(choices=STATUS, max_length=100, default="active") user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, related_name="channel") members = models.ManyToManyField(User, related_name="user_subs") -
how i create a multi step form using installed bootstrapp5
i'm new in Django programming i want to create a multi step form using bootstrap5 I have installed bootstrap 5 using this command : pip install Django-bootstrap-v5 the problem is when i search how to create a this step form i find many solution that use Js & CSS code imported from static files like this : orm id="regForm" action=""> <h1>Register:</h1> <!-- One "tab" for each step in the form: --> <div class="tab">Name: <p><input placeholder="First name..." oninput="this.className = ''"></p> <p><input placeholder="Last name..." oninput="this.className = ''"></p> </div> <div class="tab">Contact Info: <p><input placeholder="E-mail..." oninput="this.className = ''"></p> <p><input placeholder="Phone..." oninput="this.className = ''"></p> </div> <div class="tab">Birthday: <p><input placeholder="dd" oninput="this.className = ''"></p> <p><input placeholder="mm" oninput="this.className = ''"></p> <p><input placeholder="yyyy" oninput="this.className = ''"></p> </div> <div class="tab">Login Info: <p><input placeholder="Username..." oninput="this.className = ''"></p> <p><input placeholder="Password..." oninput="this.className = ''"></p> </div> <div style="overflow:auto;"> <div style="float:right;"> <button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button> <button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button> </div> </div> <!-- Circles which indicates the steps of the form: --> <div style="text-align:center;margin-top:40px;"> <span class="step"></span> <span class="step"></span> <span class="step"></span> <span class="step"></span> </div> </form> but for my situation there is no file in static directory please can you help me -
How to go about enabling side scrolling in Wagtail admin site
I have been tackling a particular design issue with Wagtail admin. Thus far I have not found a way to enable side scrolling admin listing pages. I want to extend my user model with more data about the users (e.g., occupation, education, address, and so on). While extending Wagtail with some models for a particular project, I noticed Wagtail admin listing pages do not automatically activate sides crolling as Django admin does. I have looked at Wagtail hooks doccumentation but apparently there isn't a straightforward way to do that. I don't think it would be wise to mess with core css. Does anyone have an idea on how to customize css to enable that? See pictures below: This is how Django admin handles it. We can add filters while the table adjusts itself activating side scrolling. Wagtail Bakery demo user model has few fields. So the listing admin page does not need to side scroll. I have not tested adding filters on this page yet, but I am assuming it will work just as it did to my other models. This is how my admin page looks like when using filters. The table does not activate side scrolling and gets … -
Django annotate M2M object with field from through model
Let's say I have the following models: class Color(models.Model): name = models.CharField(max_length=255, unique=True) users = models.ManyToManyField(User, through="UserColor", related_name="colors") class UserColor(models.Model): class Meta: unique_together = (("user", "color"), ("user", "rank")) user = models.ForeignKey(User, on_delete=models.CASCADE) color = models.ForeignKey(Color, on_delete=models.CASCADE) rank = models.PositiveSmallIntegerField() I want to fetch all users from the database with their respective colors and color ranks. I know I can do this by traversing across the through model, which makes a total of 3 DB hits: users = User.objects.prefetch_related( Prefetch( "usercolor_set", queryset=UserColor.objects.order_by("rank").prefetch_related( Prefetch("color", queryset=Color.objects.only("name")) ), ) ) for user in users: for usercolor in user.usercolor_set.all(): print(user, usercolor.color.name, usercolor.rank) I discovered another way to do this by annotating the rank onto the Color objects, which makes sense because we have a unique constraint on user and color. users = User.objects.prefetch_related( Prefetch( "colors", queryset=( Color.objects.annotate(rank=F("usercolor__rank")) .order_by("rank") .distinct() ), ) ) for user in users: for color in user.colors.all(): print(user, color, color.rank) This approach comes with several benefits: Makes only 2 DB hits instead of 3. Don't have to deal with the through object, which I think is more intuitive. However, it only works if I chain distinct() (otherwise I get duplicate objects) and I'm worried this may not be a legit approach (maybe … -
How Do I Add Multiple Objects Inside A Foreign key in Django
So I've been trying to make my django view to create an author model as an instance, and then save multiple objects inside the foreign key. Any Ideas on how to do this? I have tried making a author instance, and then setting the tiktok attribute of the author instance to a new tiktok model instance with the desc, likes, etc. This just updated the previous value, not appending a new tiktok object. Models.py from django.db import models # Create your models here. class TikTok(models.Model): slug = models.SlugField(max_length=300, null=True) desc = models.TextField(max_length=500, blank=True) likes = models.CharField(default=None, blank=True, max_length=100) shares = models.CharField(default=None, blank=True, max_length=100) comments = models.CharField(default=None, blank=True, max_length=100) plays = models.CharField(default=None, blank=True, max_length=100) videoUrl = models.CharField(default=None, blank=True, null=True, max_length=500) videoImg = models.CharField(default=None, blank=True, null=True, max_length=500) music = models.CharField(default=None, blank=True, null=True, max_length=500) def __str__(self): return self.desc class Author(models.Model): userhandle = models.CharField(max_length=100, blank=True) email = models.CharField(max_length=150, null=True, blank=True) verified = models.BooleanField(null=True) followers = models.IntegerField(default=0) tiktoks = models.ForeignKey(TikTok, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.userhandle And then create the instances in my views. In other words, I want one author model, and many tiktoks associated with it. This is what the output should look like: { id: 1, userhandle: 'user' email: 'user@gmail.com' verified: … -
django template tags with async view
As soon as I add async in front of a view, my template which contains {% if request.user.is_authenticated %} causes a SynchronousOnlyOperation, You cannot call this from an async context - use a thread or sync_to_async. The error only occurs when a user is logged in. What am I not getting here? view async def test(request): return render(request, 'test.html') template, test.html {% if request.user.is_authenticated %} <script> const usr = "{{user}}"; </script> {% endif %} -
Django test for 404 erroring because Client expects 200?
I am trying to test my 404 page to ensure certain elements are present on it. My test looks like this: class TestApp404PageIncludesLink(TestCase): def setUp(self): superuser = UserFactory(is_superuser=True, is_staff=True) self.client.force_login(superuser) def test_superuser_can_see_link(self): response = self.client.get("404") self.assertTrue(response.status_code == 404) self.assertContains(response, 'href="/special_link/">Specialty</a>') I am running this test as a logged in user - other tests for other views work fine. I'm trying to check the 404 page. It fails with this: Couldn't retrieve content: Response code was 404 (expected 200) 200 != 404 How do I set up the test so it knows I am trying to get a 404? -
Django sort QuerySets
Hello iam making game administration website with django and i need help with sorting 2 queryes . These are my models.enter image description here and i need to separate from them registered game_names and unregistered game_names enter image description here I was trying to make this in template but it didnt work enter image description here Help Please <3. -
Deploying github repository to Railway showing error 'ModuleNotFoundError''
I'm trying to deploy my django application to Railway using github but receiving this error from the deployment logs 'ModuleNotFoundError: No module named 'commerce.settings'. RAILWAY DEPLOYMENT LOG > File > "/opt/venv/lib/python3.8/site-packages/django/utils/connection.py", > line 50, in configure_settings settings = getattr(django_settings, > self.settings_name) File > "/opt/venv/lib/python3.8/site-packages/django/conf/__init__.py", line > 84, in __getattr__ self._setup(name) File > "/opt/venv/lib/python3.8/site-packages/django/conf/__init__.py", line > 71, in _setup self._wrapped = Settings(settings_module) File > "/opt/venv/lib/python3.8/site-packages/django/conf/__init__.py", line > 179, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) > File > "/nix/store/xq59cyi96kny4v70flfb3ymrzmymk1k1-python3-3.8.13/lib/python3.8/importlib/__init__.py", > line 127, in import_module return _bootstrap._gcd_import(name[level:], > package, level) File "<frozen importlib._bootstrap>", line 1014, in > _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'commerce.settings' DEPLOYED WEBSITE ERROR Application Error Is your app correctly listening on $PORT? View the deployment below to check for errors -
django-safedelete 1.3.0 - Cannot migrate
I built an internal app that used django-safedelete. I was working fine for months, until i recently upgraded my distro, and tried to add a field to my model. I also upgraded my python modules, everything is up-to-date, and no errors during the upgrade. Now I cannot migrate anymore: if I "makemigrations" I get an error message "django.db.utils.OperationalError: (1054, "Unknown column 'gestion_ltqmappsetting.deleted_by_cascade' in 'field list'")" if I add a boolean "deleted_by_cascade" field in my ltqmappsetting table, then the "makemigration" works, but the "migrate" fails with "MySQLdb.OperationalError: (1060, "Duplicate column name 'deleted_by_cascade'")" I tried removing the field after makemigrations, but the migrate fails with the first error message. I also tried removing the "migration" operations in the 0087...migration.py file, but it does not have any impact. Is there anyway to update the migration file between the makemigrations and the migrate commands ? Thanks a lot for any help on this. jm -
Is this security concept suitable for ehealth records webapp?
I'd like to hear your opinion on my application design regarding data security. Context & Build Steps Personal electronic health records, main purpose of app is storage (read-only). The application will be used by staff. data exchange with third parties. Users will extend to external staff. Mobile App for visualisation of health records. Users will have access to their data (read-only) Stack Backend: python+django (webapplication) DB: postgresql // Divided in two groups personal data (like name, age, adress, ...) and health records (reports, lab values, ...). health records are only files, no database records in that sense (db will have path reference in on column). All of the health records are stored in the aws S3 bucket. Host: heroku + aws S3 bucket for file storage Thoughts & Considerations The app will come with a authentification and authorisation functionality. I consider the health records with higher priority regarding data security than personal data. So what I was thinking is to upgrade my heroku server with heroku shield services which would add security features server-side and make breaches from that side harder. Additionaly I would like to use the encryption service of aws bucket to encrypt all the files in the … -
no module named pars when executing python3 script directly
pars in the django app I have made under INSTALLED_APPS within settings.py When i run this python script directly from bash that includes: from django.db import models from pars.models import tbl1, tbl2, etc technologytitle=soup.find("h1").text try: technology=CMS(nm=technologytitle) technology.save() print("saved techology: {}".format(technologytitle)) except IntegrityError as e: print("Integrity error occurring with saving: {} {}".format(technologytitle, e)) Im getting an error of: ModuleNotFoundError: No module named 'pars' ive done a ton of research, but cant seem to figure out why this is happening. Thanks -
IntegrityError at / null value in column "last_name" violates not-null constraint
I have web app which includes authentication. I have form, but when I enter my credentials and click submit I get an error: IntegrityError at /accounts/professor_register/ null value in column "last_name" violates not-null constraint. view from .forms import ProfessorSignupForm class ProfessorSignup(CreateView): model = User form_class = ProfessorSignUpForm template_name = 'authentication/dubai.html' def form_valid(self, form): user = form.save() login(self.request, user) return redirect('/') form class ProfessorSignUpForm(UserCreationForm): first_name = forms.CharField() last_name = forms.CharField() phone = PhoneNumberField() class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_professor = True user.is_staff = True user.save() professor = Professor.objects.create(user=user) professor.first_name = self.cleaned_data.get('first_name') professor.last_name = self.cleaned_data.get('last_name') professor.username = self.cleaned_data.get('username') professor.email = self.cleaned_data.get('email') professor.password = self.cleaned_data.get('password') professor.save() return user models class User(AbstractUser): is_pupil = models.BooleanField(default=False) is_instructor = models.BooleanField(default=False) class Professor(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) first_name = models.CharField(max_length=20, null=False) last_name = models.CharField(max_length=30, null=True) username = models.CharField(max_length=30, unique=True, null=True) email = models.EmailField(unique=True, null=False) password = models.CharField(max_length=60, null=False) phone_number = PhoneNumberField(null=False, blank=False, unique=True) I am using postgresql as database. I have no idea why this is happening. Every stack answer I tried to replicate gives me another error:( -
How to display data from Rest API in a template
I made an API using Django Rest Framework and I've been able to use it to create come charts using ChartJS. In the same API, after the data used for the charts I have some other data that I want to be displayed simply as a number in the same Django template, but I'm really unsure on how to do that. My API: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { (...CHARTS.JS DATA...) "total_employees": 1, "total_vehicles": 3, } I have already imported the data into the template together with the data I used for the charts. Template: <script> {% block jquery %} var endpoint = '/api/chart/data/' (Chart.JS part) var totalemployees = [] var totalvehicles = []; $.ajax({ method: "GET", url: endpoint, success: function(data){ (Chart.JS data here...) totalemployees = data.totalemployees totalvehicles = data.totalvehicles (ChartJS stuff here...) }, error: function(error_data){ console.log("error") console.log(error_data) } }) (Other ChartJS stuff here...) {% endblock %} </script> I would like to do something like this in the template: <h3 class="text-center m-4">Total number of employees: ("total_employees" value (which in this case is 1)</h3> <h3 class="text-center m-4">Total number of vehicles: ("total_vehicles" value (which in this case is 3)</h3> -
Django Sessions Loose Data with url containing target="_blank"
In my django app, I store the current breadcrumb data (an array) in the session object. When I have a link that includes target="_blank", the session data is lost. I assume this is normal operation, but just want to check that this is true. Any suggestions on where to store the breadcrumb array if I need to retrieve it when I use target="_blank" in my urls as well as whenever a page loads? Keep in mind, the breadcrumb data is on a per user basis. Thanks! -
GitHub App - User Authentication/Authorization through GitHub APIs
I am new to GitHub Apps. I have used GitHub OAuth before, but finding it a bit difficult to understand the user authentication and authorization for GitHub Apps. My use case is as follows - A user will visit my website, login with their GitHub credentials and at that time the user needs to accept the permission I seek from their profile (ex. Repository, PRs, etc.) and display those repositories and PR on my website and perform some actions on them. I have primarily 1 question at a high level. The API endpoints and what all keys are needed to authenticate and authorize a user so as to get all the requested items like repositories etc. and more importantly the next time the user logs in he should not need to accept the permission to access his repositories. (Similar to this codefactor site) I would like to have an architecture level solution if not a code example. I am using Python (Django) to build my project but code examples in other languages are also welcomed. -
success_url not working with url that-has/<int:pk>
The success_url is workin fine with a url that has-no/int:pk but does not work with a url that has /int:pk throws an error NoReverseMatch: Reverse for 'read_bty'. Views.py class HBTYOrderView(BSModalCreateView): template_name = 'accounts/modals/hairbty/create_hbty.html' form_class = HairbtyOrderForm success_message = 'Success: Order was created.' success_url = reverse_lazy('read-bty') Urls.py path('create_btyorder/', views.HBTYOrderView.as_view(), name='create_btyorder'), path('read_bty/<int:pk>', views.HBTYReadView.as_view(), name='read_bty'), -
ajax response can be seen fine in the alert box but can't print it out get undefined instead
I am trying to print out the response to an ajax request. I am getting a "undefined" when (down there) I write ${obj[property][0]} it follows the index to 1, 2 etc I can see both in the console and by alert-ing the response (data) that it does send the correct data in the form of a dictionary although it surely is json because that is what I send as response (and that is what web tools shows). However if I alert-out the "obj" I get "object" but can't see real values This is the ajax call: $(document).ready(function(){ // open document ready $('.botontest').on('click',function(){ // opening click function var value = $(this).val() alert(value); $.ajax({ // opening ajax obviously url:"{% url 'bill' %}", type:'POST', data:{'name':value, csrfmiddlewaretoken: '{{csrf_token}}'},// closes data field datatype:'json' }).done(function(data) { obj = JSON.parse( data); alert(data); // it prints me all data alright in the "alert" box // I leave out the headers. for (const property in obj) { tableHTML += "<tr><td>" tableHTML += `${property}</td> <td>${obj[property][0]}</td><td>${obj[property][1]}</td>\ <td>${obj[property][2]}</td><td>${obj[property][3]}</td><td>${obj[property][4]}</td><td>${obj[property][5]}</td>\ <td>${obj[property][6]}</td><td>${obj[property][7]}` tableHTML += "</td></tr>" } tableHTML += "</tbody></table>" //place the tableHTML in the document $("#respuesta").html(tableHTML); }); // closing ajax group console.log(value); }); // closing the click function });// closing document ready </script> My response … -
Custom manager in Django MultiDB
I'am using MySQL and PostgreSQL in my Django project. Below are the settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mysql_db', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'hostname', 'PORT': '3306', }, 'postgres_db': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'pgsql_db', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'hostname', 'PORT': '5432', } } And this is the sample model from postgres_copy import CopyManager class Items(models.Model): class params: db = "postgres_db" sales_value = models.CharField(max_length=255, null=True, blank=True) primary_email = models.CharField(max_length=255, null=True, blank=True) objects = CopyManager() I want to use Items.objects.all().to_csv('./path/to/csv) this ORM to export model data to CSV. I have used this before in exporting large dataset to csv. But in this configuration it gives below error psycopg2.errors.SyntaxError: syntax error at or near "." LINE 1: COPY (SELECT `sales_item`.`id`, `sales_item`.`sales_value`,... This seems to be an issue with multiDB. If I run this ORM in single DB configuration, or even if I set default alias on PostgreSQL this works fine. CopyManager seems to be getting default alias somehow which I have no idea about. How can I run this ORM in current settings without any issues? Any help would be appreciated. Thanks in advance. -
Building a dynamic asynchronous filesystem in django: best practices
I am trying to rebuild our website in Django, and I am currently facing a series of rather difficult challenges for which I am not prepared. I was hoping to get some help in the matter. The website I am building is an online archival platform for artists called Lekha. The core of Lekha is the dashboard page (which you can check out on this link, just sign in with the email stacko@test.com and the password test if you have the patience). On the dashboard page, users have access to a hierarchical filesystem that we would like to function like a desktop filesystem for ease of use. Users can use the filesystem to organize their 'artworks' into folders. These artworks themselves are a collection of media, along with the metadata of the artwork. To upload this media and fill in the metadata, users will use a form. If users want to edit an artwork's metadata, they can do so through an auto-populated form on the same page. The issue that I am facing is that I am struggling to find an elegant way to make all of this happen without reloading the page. Users need to be able to add, … -
relation does not exist while testing django tenant
I would like to use Selenium for my test. But when I try to connect to my tenant and then create a basic django User, I got the relation does not exist error. I suppose that because I'm in a test, the migrations to my tenant are not made but I can't figure out how to do this. my test.py class VisitCreationTestCase(StaticLiveServerTestCase): fixtures = ['save.json'] def check_connect(self, driver): driver.get(self.live_server_url.split("localhost")[0] + Domain.objects.first().domain + self.live_server_url.split("localhost")[1]) title = driver.title username = driver.find_element(by=By.NAME, value="login") password = driver.find_element(by=By.NAME, value="password") submit_button = driver.find_element(by=By.CSS_SELECTOR, value="button[type='submit']") connection.set_tenant(Client.objects.first()) User.objects.create(username="demo", password="testmdpusee") username.send_keys("demo") password.send_keys("testmdpusee") submit_button.click() driver.implicitly_wait(1) driver.find_element(by=By.XPATH, value="//p[contains(text(),'Aucun dossier ou fichier')]") def setUp(self) -> None: service = ChromeService(executable_path=ChromeDriverManager().install()) self.driver = webdriver.Chrome(service=service) self.check_connect(self.driver) my save.json [ { "model": "client.client", "pk": 1, "fields": { "schema_name": "demo", "nom": "demo", "logo": "", "raison_social": "a", "SIRET": "b", "TVA": "c", "adresse": "d", "code_postal": "e", "ville": "f", "numero_de_telephone": "g", "adresse_email": "h", "credit": 999998, "iparco_token": "i", "sender_password": null, "sender_mail": null, "sender_host": "ssl0.ovh.net", "sender_port": "587", "created_on": "2022-09-06" } }, { "model": "client.domain", "pk": 1, "fields": { "domain": "demo.localhost", "tenant": 1, "is_primary": true } } ] If anyone has ever encountered this problem, I have no more idea to solve this... -
How to get logged in user in django from custom users model
I want to get username from custom users model My Custom Users model: class Account(AbstractBaseUser, PermissionsMixin): nickname = models.CharField(max_length=150, unique=True) name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) phone = models.CharField(max_length=50, unique=True) date_of_birth = models.DateField(blank=True, null=True) picture = models.ImageField(blank=True, null=True) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) last_login = models.DateTimeField(null=True) admin_of_company = models.ForeignKey('companies.company', on_delete=models.CASCADE, default=None, blank=True, null=True) objects = AccountManager() USERNAME_FIELD = 'nickname' REQUIRED_FIELDS = ['name', 'last_name', 'phone'] def get_full_name(self): return self.name, self.last_name def get_short_name(self): return self.name.split()[0] and products model: class products(models.Model): name = models.CharField(max_length=150) about = models.TextField() price = models.IntegerField() picture = models.ImageField(default=None) admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) in products.admin I want to set default logged in user but I don't know how to get this data from custom users model