Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multi databases in django project, dublicate the database
Multi databases in django project, dublicate the database While posting the form of models, it must be stored in two databases at a time. like dublicate the database. settings.py DATABASES = { 'default': {}, 'auth_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'auth_db.db.sqlite3'), }, 'primary': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'primary.db.sqlite3'), }, 'app_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'app_db.db.sqlite3'), }, 'app2_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'app2_db.db.sqlite3'), } } DATABASE_ROUTERS = ['routers.AuthRouter', 'routers.PrimaryReplicaRouter'] Routers file in project read, write in first routers is working(auth_db), if create same in other it is not working. routers.py import random class AuthRouter: """ A router to control all database operations on models in the auth and contenttypes applications. """ route_app_labels = {'auth', 'contenttypes'} def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'auth_db' return None def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'auth_db' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth or contenttypes apps is involved. """ 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 … -
error while hosting django site on local system
I am facing the following error while hosting a Django site on my local machine. I am doing the same thing in a VM and it is working fine. Can someone, please let me know what should I do differently while hosting it in local environment. Thanks in advance. -
How can I find if there is memory leak for my Docker + Django app?
I'm running my Django app with docker compose. There are 4 containers, web, postresql, nginx, cron. The web container in my dev server is using 170MB Ram, mainly running gunicorn / Django / Python / DRF. The web container in my production server is using 600MB Ram. It's definitely growing over time. I've set max requests and max request jitter for gunicorn (gunicorn byob.wsgi:application --workers=4 --threads=4 --max-requests=1000 --max-requests-jitter=30 --worker-class=gthread -b 0.0.0.0:8000) I don't want to restart the container coz it may affect some users. My questions are: how can I find out if there is a memory leak? how can I reduce memory usage? I am thinking to add a task queue to my 2GB ram server. But this issue may use up the memory. -
Have issues getting data to display on my web application
I am trying to get the "About us" information from my database to my web application but its not displaying, what could be wrong... here is the code from the database class About(models.Model): about_us = models.TextField() achieve = models.TextField(blank=True) image_abt = models.ImageField(upload_to="admin_pics", null=True) class Meta: verbose_name_plural = "About Us" def __str__(self): return self.about_us and here is the Html code ` {% extends 'jtalks/base.html' %} {% load static %} {%block content%} <section id="about-home"> <h2>About Us</h2> </section> <section id="about-container"> {% for about in abouts %} <div class="about-img"> <img src="{{ about.image_abt.url }}" alt=""> </div> <div class="about-text"> <h2>Welcome to TechEduca, Enhance your skills with best Online Courses</h2> <p>{ about.about_us}</p> <div class="about-fe"> <img src="images/fe1.png" alt=""> <div class="fe-text"> <h5>400+ Courses</h5> <p>You can start and finish one of these popular courses in under our site</p> </div> </div> <div class="about-fe"> <img src="images/fe2.png" alt=""> <div class="fe-text"> <h5>Lifetime Access</h5> <p>You can start and finish one of these popular courses in under our site</p> </div> </div> </div> {% endfor %} </section> {% endblock %} Nothing is displaying in the frontend of the website. -
Django and PostgresSQL - cannot cast type integer to date
When I run python3 manage.py migrate, I get this: Operations to perform: Apply all migrations: admin, auth, contenttypes, main, sessions Running migrations: Applying main.0024_alter_userrents_return_date...Traceback (most recent call last): File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.CannotCoerce: cannot cast type integer to date LINE 1: ...TER COLUMN "return_date" TYPE date USING "return_date"::date ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 249, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 535, in alter_field old_db_params, new_db_params, strict) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/db/backends/postgresql/schema.py", line 122, … -
Django: PNG not downloading, but opening in browser
I have one API response in which I have one URL, when I am clicking on the URL it is opening in the browser and not getting downloaded. I want to make it downloadable through the backend only. { "count": 1, "next": null, "previous": null, "results": [ { "id": 132, "certificate_url": "https://temp.com/images/export/61ca22ef07dd8b000980b7a9/image-1640637167913.png" } ] } -
django: html form submit without jumping into new page or refreshing/reloading
I am new to django and html. below is my first test web page of a simple online calculator. I found a problem that when clicking the "submit" button, it tends to jump to a new web page or a new web tab. this is not what I want. Once the user input the data and click "submit" button, I want the "result" field on the page directly show the result (i.e. partially update only this field) without refresh/jump to the new page. Also I want the user input data kept in the same page after clicking "submit". I saw there might be several different ways to do this work, iframe/AJAX. Since I am new, what is the really simplest way to achieve this goal? BTW, I dont write javascripts. html: <form method="POST"> {% csrf_token %} <div> <label>num_1:</label> <input type="text" name="num_1" value="1" placeholder="Enter value" /> </div> <div> <label>num_2:</label> <input type="text" name="num_2" value="2" placeholder="Enter value" /> </div> <br /> <div>{{ result }}</div> <button type="submit">Submit</button> </form> view.py def post_list(request): result = 0 if request.method == "POST": num1 = request.POST.get('num_1') num2 = request.POST.get('num_2') result = int(num1) + int(num2) print(request.POST) print(result) context = { 'result': result } return render(request, 'blog/post_list.html', context) -
Django Template :: How to Use POP() in django template
In Below code, am iterating through 2 list. users and roles, where I want to print first element from the roles list for the first element from the user. user = ['abc','cde'] roles = [[1,2,3] , [4,5,6]] for user 'abc' roles should be printed as 1,2,3 only. but am getting all roles for 'abc' user. <table> {% for u in users %} <tr> {% for r in roles.0 %} <th><b>{{ u }}</b></th> <td><b>{{ r }}</b></td> {% endfor %} {{ roles.pop.0 }} </tr> {% endfor %} </table> Can someone help me understanding that why the {{ roles.pop.0 }} is not deleting first element in the roles list? -
How to change the field of username to user_name in to django custom user model?
I have created custom user model. now I want to use user_name as username field instead of username. like shown in below code snippet. class CustomUser(AbstractBaseUser): username_validator = UnicodeUsernameValidator() user_name = models.CharField( _('username'), max_length=100, unique=True, help_text=_('Required. 100 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) USERNAME_FIELD = 'user_name' i'm unable to do that. i'm getting below error: SystemCheckError: System check identified some issues: ERRORS: <class 'accounts.admin.CustomUserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'accounts.CustomUser'. <class 'accounts.admin.CustomUserAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'username', which is not a callable, an attribute of 'CustomUserAdmin', or an attribute or method on 'accounts.CustomUser' the reason of using this, is because all the project's database tables convention is like this. It would be more better if i could define field name is database just as we do for tables in Meta class like below. where i'm calling my customuser model as user model in db. class Meta: db_table = "user" is there anyway to call table field like this way ? class Meta: db_table_user_name = "username" if it possible then we dont need to change … -
How to include Bearer Token in Header using Django Rest Framework?
I'm using rest_framework_simplejwt package for JWT authentication in Django. I created some APIs for login, reg, token_verify, referesh_token and student_data. I restricted to view student details which are fetched from Database. So, user can't see it without authentication. Here is the image for better understanding. As you brothers can see that I pass a Bearer token in postman and then student api work. how i can do this same thing when i have to show the data on frontend? How i'm able to pass bearer token when user is generated the access token by logedin to student route for auth? If I open the link in browser. when i go on student then this happens How I can pass the access_token so i'm authenticated and see the students data? I am trying to this thing for last 10Hours here is the code. View.py ACCESS_TOKEN_GLOBAL=None class Register(APIView): RegisterSerializer_Class=RegisterSerializer def get(self,request): return render(request, 'register.html') def post(self,request,format=None): serializer=self.RegisterSerializer_Class(data=request.data) if serializer.is_valid(): serializer.save() msg={ 'msg':"Registered Successfully" } return render(request, 'login.html',msg) else: return Response({"Message":serializer.errors,"status":status.HTTP_400_BAD_REQUEST}) class Login(APIView): def get(self,request): if 'logged_in' in request.COOKIES and 'Access_Token' in request.COOKIES: context = { 'Access_Token': request.COOKIES['Access_Token'], 'logged_in': request.COOKIES.get('logged_in'), } return render(request, 'abc.html', context) else: return render(request, 'login.html') def post(self,request,format=None): email = … -
Rabbitmq not showing messages in django
I'm reading Django 3 by example book and in Chapter 7 of the book we use rabbitmq,celery and flower. I configed rabbitmq,celery and flower but there is a few problems my task is a email that it sends after a order is created and the task is executed in celery terminal and in flower flower panel but i cant see the email. and in rabbitmq panel the messages are unacked and the other problem is that broker tab in flower is empty and it does'nt show rabbitmq. Here is the screenshots and my code. rabbitmq server is runnig rabbitmq admin panel flower panel celery logs Here is my tasks.py: from __future__ import absolute_import, unicode_literals from celery import shared_task from django.core.mail import send_mail from .models import Order @shared_task def order_created(order_id): """Task to send an e-mail notification when order is successfully created.""" order = Order.objects.get(id=order_id) subject = f'Order nr. {order.id}' message = f'Dear {order.first_name},\n\n' \ f' You have successfully placed an order.' \ f'Your order ID is {order.id}' mail_sent = send_mail(subject, message, 'admin@onlineshop.com', [order.email]) return mail_sent celery config file, celery.py: import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Onlineshop.settings') broker = "amqp://test:test@localhost:5672/" … -
Django view return data
I have a view that returns an HTML response using render. The data returned is specific to a template. If I want to consume that data on another page, should I write another view with the same logic, or is there a way to pass the data from view 1 to view 2 view return render(request, 'pages/project_details.html', {"project": project, urls path('show_project_details/<project_id>', view=show_project_details, name="show_project_details"), I know that a view is just a function, which takes a request and does something with it, but I don't get how I make a request to a view within a template and consume the response within an existing page. Example here: ## filename: views.py from django.shortcuts import render from .models import Team def index(request): list_teams = Team.objects.filter(team_level__exact="U09") context = {'youngest_teams': list_teams} return render(request, '/best/index.html', context) I want to return the data within this context to home.html and index.html. Hope this makes sense? -
Connecting Django to PostgreSQL database (GeoDjango)
I am having issues connecting to my Postgresql database with my Django website. My database is set up at Port 5434 as there is already an existing database in the default 5432 port. This is the error I am getting Traceback (most recent call last): File "c:\users\anouphong\appdata\local\programs\python\python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\users\anouphong\appdata\local\programs\python\python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\core\management\commands\runserver.py", line 127, in inner_run self.check_migrations() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\core\management\base.py", line 505, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\migrations\loader.py", line 53, in __init__ self.build_graph() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\migrations\loader.py", line 223, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations if self.has_table(): File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\utils\asyncio.py", line 25, in inner return func(*args, **kwargs) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\backends\base\base.py", line 270, in cursor return self._cursor() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\backends\base\base.py", line 246, in _cursor self.ensure_connection() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\utils\asyncio.py", line 25, in inner return func(*args, **kwargs) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\backends\base\base.py", line 230, in ensure_connection self.connect() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\backends\base\base.py", line 230, in ensure_connection self.connect() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\utils\asyncio.py", line 25, in inner return func(*args, **kwargs) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\backends\base\base.py", line 211, in connect self.connection … -
Angular.js @angular/core bug
Welcome everyone... how can i fix this im working on it 2 days but nothing change. Can you help me ?See my all codes in app.module.ts That's my nodejs screen import { AngularFireModule} from '@angular/fire/compat'; //it should be '@angular/fire' import { AngularFireDatabaseModule } from '@angular/fire/compat/database'; //it should be '@angular/fire/database' imports: [ AngularFireModule.initializeApp(environment.firebaseConfig), AngularFireDatabaseModule ]; Thank you, -
DRF: validate_empty_values() is called when not empty
I created a subclass of ChoiceField in order to add custom code to supply the default value. At this point, I've copied the validate_empty_values() method over to my new class without modifying it at all - I just want to understand how it works. Here's that method (copied straight from the Field class in /rest_framework/fields.py): def validate_empty_values(self, data): """ Validate empty values, and either: * Raise `ValidationError`, indicating invalid data. * Raise `SkipField`, indicating that the field should be ignored. * Return (True, data), indicating an empty value that should be returned without any further validation being applied. * Return (False, data), indicating a non-empty value, that should have validation applied as normal. """ if self.read_only: return (True, self.get_default()) if data is empty: if getattr(self.root, 'partial', False): raise SkipField() if self.required: self.fail('required') return (True, self.get_default()) if data is None: if not self.allow_null: self.fail('null') # Nullable `source='*'` fields should not be skipped when its named # field is given a null value. This is because `source='*'` means # the field is passed the entire object, which is not null. elif self.source == '*': return (False, None) return (True, None) return (False, data) I have done a PATCH (we use PATCH for … -
Django lists of objects in a template max out
Not an expert on django and I have a problem that I have tried to find documentation about. Hopefully someone can help me out. Sometimes my templates do not return the intended page html, but instead returns a text based html list of the objects .I suspect this is related to number of rows in the queryset. Where can I find the documentation about this? Is it a django setting or the CSS class for the list that determines this? -
How to set on delete and on update cascade in django?
Look at these modules: class Customer2(models.Model): Customer_Name=models.CharField(max_length=30) Customer_Address=models.CharField(max_length=100) Customer_Phone=models.IntegerField() Customer_Email=models.EmailField(max_length=50) class Meta: db_table="Customer_Table" class Product(models.Model): Product_Name=models.CharField(max_length=100) Quantity=models.FloatField(max_length=100) Comming_Date=models.DateField(max_length=15) Expire_Date=models.DateField(max_length=15) Comming_Price=models.FloatField(max_length=50) Picture=models.ImageField(upload_to='Images',blank=True, null=True) class Sale(models.Model): Customer=models.ForeignKey(Customer2, default=1, on_delete=models.CASCADE) Product=models.ForeignKey(Product, default=1, on_delete=models.CASCADE) Quantity=models.FloatField() Price=models.FloatField() Date=models.DateTimeField() Customer_Name1=models.CharField(max_length=20,default=0) Product_Name1=models.CharField(max_length=20,default=0) class Meta: db_table="Sale_Table" In the above modules,when I am trying to to delete (customer) from customer it gives me(Do you really want to execute "DELETE FROM customer_table WHERE customer_table.id = 2"?)message, while I already used on delete cascade in customer table,What should I do? I want to set on update and on delete cascade in customer table. -
unable to send post request using HTMX + Django
I'm trying to create a CRUD page using django + HTMX and unable to send POST request. hx-post sends a GET request instead of POST request. my Role Models is as follows: class Role(models.Model): name = models.CharField(max_length=200) I'm creating the form using Cripsy Forms as follows class RoleForm(forms.ModelForm): class Meta: model = Role fields = ('name', ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.fields['name'].label = "Role" self.helper.add_input(Submit('add_new_Role', 'Add', css_class='role_button')) self.helper.layout = Layout( Row( Column('name'), ) ) I'm using the form in my template like this : {% extends 'main.html' %} {% load crispy_forms_tags %} {% block content %} <div class="row"> <div class="card col-md-6 ml-auto mr-auto"> <div class="card-body"> {% crispy role_form %} </div> </div> </div> <div id="role_list"> {% include 'role_list.html' %} </div> {% endblock %} {% block javascript %} <script type="text/javascript"> $(document).ready(function(){ $("form").removeAttr("method"); $('.role_button').attr("hx-post", '{% url "role_add" %}'); $('.role_button').attr('hx-target', '#role_list'); }); </script> {% endblock %} The CDN link is added in the main.html file. My understanding is that clicking the ADD button should trigger a POST request. However GET request is initiated, which makes me feel like the HTMX part did not work at all -
Get object URL from boto3, AWS S3, Django
I have a view in Django like this : f=request.FILES['image'] filename=str(f).split('.')[0] cloudFilename = 'blog/' + filename s3 = boto3.resource('s3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY) bucket = s3.Bucket('django-pnp-talk') bucket.put_object(Key=cloudFilename, Body=f) how can I get the URL from the recently object that I put into the bucket? -
Even though its a class why is AttributeError: 'function' object has no attribute 'as_view'
even though its a calss based func why is this attribute error popping up when i use login_required error Message path('active/<int:pk>', UpdateActiveStatus.as_view(), name="activeStatus"), AttributeError: 'function' object has no attribute 'as_view' views.py @login_required(login_url='/admin/') class UpdateActiveStatus(UpdateView): model = FutsalTimeline form_class = UpdateActiveStatus template_name = 'timeline.html' success_url = reverse_lazy('timeline') -
Django, How to filter context output from HTML template?
I have a ListView that sends context as news in the HTML template. The below code is supposed to slice the context array from the 4th element to until its end {% for post in news[4:0] %} ............ {% endfor %} But following error occurs Could not parse the remainder: '[4:]' from 'news[4:]' -
Annotation of Similar Article Tags In Django Admin
I want to display similar tags count in the Django admin Tag section like this: name | posts ------------------------------- business | 3 Currently in my Tag table I have something this. This different posts that have similar tags to them. name | post_id ------------------------------- business | 1 business | 2 business | 3 My models class Posts(models.Model): title = models.CharField(max_length=500, verbose_name='Post Title') class Tags(models.Model): name = models.CharField(max_length=500) date_created = models.DateField(auto_now_add=True, verbose_name='Date Created') last_modified = models.DateField(auto_now=True, verbose_name='Last Modified') post = models.ForeignKey(Posts, on_delete=models.CASCADE, verbose_name='Posts') I have this in the admin.py class TagAdmin(admin.ModelAdmin): list_display = ('name', 'post_count', 'date_created', 'last_modified') search_fields = ['name'] ordering = ['id'] readonly_fields=('date_created', 'last_modified') def post_count(self, obj): return obj.post_count def get_queryset(self, request): queryset = super().get_queryset(request) queryset = queryset.annotate(post_count=Sum("post")) return queryset admin.site.register(Tags, TagAdmin) This is how it looks in the admin panel name | post_count ------------------------------- business | 3 business | 3 business | 3 How do I achieve only displaying one instance of a tag name with all the posts that have that tag instead of the repetition above and instead the desired outcome below? name | posts ------------------------------- business | 3 -
Drf: authenticating without the USERNAME_FIELD
` extended from: Drf how to: simple-jwt authenticating without the USERNAME_FIELD I was tryna figure out how to authenticate a user with a field that is not set as the USERNAME_FIELD and faced some issues, it lets me input in the correct data fields, but it never authenticates I'm using this snippet from the previous questions answer: class MyTokenStudentSerializer(TokenObtainPairSerializer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['student_id'] = serializers.CharField(required=False) # self.fields['password'] = serializers.CharField(write_only=True, required=True) self.fields['password'] = PasswordField(trim_whitespace=False) username_field = 'student_id' auth_fields = ['student_id'] produces { "detail": "No active account found with the given credentials" } any modifications would be greatly appreciated. -
Annotate on Generic Relation
apologies, I'm fairly sure there's a way to do this with Q filters/F expressions but I can't quite get it right. I have a Generic Versioning Model, and several versionable models: class Version(models.Model): content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, limit_choices_to=VERSIONED_OBJECTS_LIMIT ) object_id = models.PositiveIntegerField() source = GenericForeignKey("content_type", "object_id") object_uri = models.TextField(max_length=1024, null=True) version_number = models.IntegerField(default=1) is_latest = models.BooleanField(default=1) class Dataset(models.Model): versions = GenericRelation(Version) class DataModel(models.Model): versions = GenericRelation(version) I figured this approach would be wise as we version quite a few models. However, I'm struggling to create the annotation/query that would retrieve for me all model instances annotated by the latest version. For a given instance it is of course trivial, but I can't figure it out for the model writ large. latest_datasets = Dataset.objects.annotate(uri = version.uri).filter(versions__islatest=True) Obviously returns all datasets, since by design each dataset has at least one "is_latest" Version. Apologies -- maybe this is just bad db design, but I do think making "Version" a Generic abstraction made sense for our use case. So, if theres a way to get all instances of Model_x with the appended uri WHERE version.is_latest = True, I would love to know how. Thanks in advance, sorry for my ignorance. -
How to get user with POST Ajax call in django?
I'm trying to realize comments for products on site with AJAX, but faced the problem that I can not receive an author of comment in this case of code: new_comment.author = request.user I got this error in this case: "Exception Value: Object of type User is not JSON serializable" But without user I got parameters from back-end and have result 200, like this author "" content "dasda" created_at "2021-12-31T07:34:12.766Z" product 4 So the question how to be "author = request.user" can be serialized? Or it is can be realised only with Django Rest Framework? (I don't have experience in DRF, but know some things in theory) Can somebody advice please? def ajax_receiver(request): product = Product.objects.get(id=4) is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' if request.method == 'POST' and is_ajax and request.user.is_authenticated: form = UserCommentForm(data=request.POST) if form.is_valid(): new_comment = form.save(commit=False) #new_comment.author = request.user new_comment.product = product new_comment.save() comment_info = { "author": new_comment.author, "content": new_comment.content, "created_at": new_comment.created_at, "product": product.id, } return JsonResponse({"comment_info": comment_info}, status=200) else: return JsonResponse({"success": False}, status=400)