Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django Serializer inserting nothing into database (no errors)
As I stated in the title, nothing is bein inserted into my database even though other fields are being inserted. My goal is to take a json post request: { "user": "0", "total_price":29.60, "type":"PENDING", "products": [{ "id_product":"0" },{ "id_product":"1" }, { "id_product":"3" } ] } I am taking this post rquest and putting it through my serializer to save it to my database. the products field in the json is "a list of foreign keys pointing to the primary key in the Products model. My models.py from django.db import models # Create your models here. class Users(models.Model): user_id = models.CharField(max_length=10, primary_key=True, default="") first_name = models.CharField(max_length=30,default="") last_name = models.CharField(max_length=30,default="") profile_image = models.ImageField(upload_to='users', default='./images/no-account-image.jpg') email = models.CharField(max_length=50, unique=True,default="") def __str__(self): return self.user_id class Products(models.Model): CATEGORY = ( ('SHIRT','Shirt'), ('PANTS','Pants'), ('SHORTS','Sorts'), ('JACKET', 'Jacket'), ('BEANIE', 'Beanie'), ('HOODIE', 'Hoodie'), ) product_id = models.CharField(max_length=10, primary_key=True,default="") name = models.CharField(max_length=10,default="") cost = models.DecimalField(max_digits=6, decimal_places=2,default=0) description = models.TextField(max_length=1000,default="") category = models.CharField(max_length=10, choices=CATEGORY,default="") image = models.ImageField(upload_to='products', default='./images/No_Image_avaliable.jpg') products_remaining = models.IntegerField(default=0) def __str__(self): return self.product_id class Transactions(models.Model): TYPE = ( ('SHIPPED','Shipped'), ('RETURNED','Returned'), ('PENDING', 'Pending'), ) transaction_id = models.CharField(max_length=10, primary_key=True,default="") user = models.ForeignKey(Users, on_delete=models.PROTECT,default="",related_name='user') total_price = models.DecimalField(max_digits=6, decimal_places=2,default=0.0) type = models.CharField(max_length=10, choices=TYPE,null=True,default="") products = models.ManyToManyField(Products) def __str__(self): return self.transaction_id my views.py from … -
How to query Boolean condition inside django model property?
I want to return item with @property by checking its Boolean value. I want to achieve on follwing way: @property def item_feature_image(self): return self.item_image.get(is_featured = True) item_image is verbose name of related item image table. How can I return the correct value here -
Django: unsupported operand type(s) for +: 'int' and 'method' in django
i am trying to write a function that would return cart total but it keep showing this error unsupported operand type(s) for +: 'int' and 'method'when i comment this code out total = sum([item.get_total for item in orderitems]) the errors goes away but i dont get my cart total, which means the code is needed. i found out that it might be because i am trying to use a Concatenation "+" with String and different types is not allowed in Pyhton. but i can't pin point where the error is coming from! views.py @login_required def cart(request): if request.user.is_authenticated: student = request.user.student order, created = Order.objects.get_or_create(student=student, completed=False) items = order.orderitem_set.all() else: items = [] context = { 'items': items, 'order': order, } return render(request, 'course/cart.html', context) models.py class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=1000) email = models.EmailField() def __str__(self): return self.user.username class Order(models.Model): student = models.ForeignKey(Student, on_delete=models.SET_NULL, null=True) date_ordered = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False, null=True, blank=True) transaction_id = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.student.user.username # return str(self.id) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class … -
Checking whether element is in ManyToMany field in Django
Hi so I have an attend session button that when clicked adds the user to the session. I got it working but I want to add a check to see whether the user is already in the ManyToMany field of attendees before I add them. How would I go about doing that? Here is my view for it def attend_session(request): session = Study.objects.get(pk=request.POST['session_id']) stud = Student.objects.get(student_user=request.user) if request.method == "POST": # Add check here to see if student is already attending session.attendees.add(stud) session.save() return HttpResponseRedirect(reverse('study:sessions')) -
ValueError: Field 'id' expected a number but got '<string>'
I have no idea what is going on and I have taken a look at many of the other stack examples and problems similar to this, but none are helping. I am trying to filter through a list of my objects in Django, and I am running to the issue mentioned in the title: "ValueError: Field 'id' expected a number but got 'EE468'." My models.py: class Course(models.Model): course_id = models.CharField(primary_key=True, max_length=25) title = models.CharField(max_length=50, blank=True, null=True) dept_name = models.ForeignKey('Department', models.DO_NOTHING, db_column='dept_name', blank=True, null=True) credits = models.FloatField(blank=True, null=True) class Meta: managed = False db_table = 'course' def __str__(self): return self.course_id + ", " + self.title + ", " + self.dept_name + ", " + str(self.credits) class Takes(models.Model): studid = models.ForeignKey(Student, models.DO_NOTHING, db_column='ID', blank=True, null=True) # Field name made lowercase. course = models.ForeignKey(Section, models.DO_NOTHING, blank=True, null=True, related_name="takes_course") sec = models.ForeignKey(Section, models.DO_NOTHING, blank=True, null=True, related_name="takes_section") semester = models.ForeignKey(Section, models.DO_NOTHING, db_column='semester', blank=True, null=True, related_name="takes_semester") year = models.ForeignKey(Section, models.DO_NOTHING, db_column='year', blank=True, null=True, related_name="takes_year") grade = models.CharField(max_length=2, blank=True, null=True) class Meta: managed = False db_table = 'takes' def __str__(self): return f"{self.studid_id}, {self.course_id}, {self.sec_id}, {self.semester_id}, {self.year_id}, {self.grade}" class Teaches(models.Model): instid = models.ForeignKey(Instructor, models.DO_NOTHING, db_column='ID', blank=True, null=True) # Field name made lowercase. course = models.ForeignKey(Section, models.DO_NOTHING, blank=True, null=True, … -
MSSQL query equivalent in django query with postgres?
this is my first question on stackoverflow. Help please I am working on a django website with an external read-only database witch i don't own .. Suppose i have the following models: class ModelF(models.Model): vref = models.CharField(..) nbr = models.CharField(..) dateDebut = models.DateField(..) dateFin = models.DateField(..) nature = models.CharField(..) type = models.CharField(..) plle = models.CharField(..) class ModelP(models.Model): name = models.CharField(..) ref = models.CharField(..) class Inter(models.Model): key = models.CharField(..) n_vers = models.DecimalField(..) date = models.DateField(..) I am looking for the django query equivalent to this sql: Select P.name, F.nature, F.dateDebut, F.dateFin, F.nbr, F.plle, SUM( iif(isnumeric(F.nbr)=1, cast(F.nbr as numeric(5, 2)), 0)) Over (Order by F.dateDebut, nature) as NCumul from ModelF F, ModelP P Where F.vref = P.ref And plle in (Select distinct key from Inter where n_vers = 100) And F.type = 'TYPE1' And DATEDIFF(DAY, F.dateDebut, (Select date from Inter where n_vers = 100)) <= 365 this is what i have done till now: keys = Inter.objects.filter(n_vers=100).distinct('key').values_list('key', flat=True) results = ModelF.objects.filter(key__in=keys, type = 'TYPE1',).annotate( NCumul=Window( expression=Sum(Case( When(nbr__isnull=False, then=Decimal(F('nbr'))), default = 0, output_field=DecimalField() )), partition_by=[F('nature')], order_by=F('dateDebut').asc(), ), ) but i get the error conversion from F to Decimal is not supported i am also asking if possible how to implement the DATEDIFF(DAY, F.dateDebut, … -
Problem with migration after changing database in Django
So i was using MySQL as database backend engine, and after changing it back to SQLite i can't make migrations. Tried removing migrations, and db.sqlite3 file but it's still not working. Console is showing me that error django.db.utils.OperationalError: no such table: books_api_book -
How to mock the count of likes for Django testing
I need to test this view: class ShowHomePageView(views.TemplateView): template_name = 'home_page.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) books = Book.objects.prefetch_related('likes'). \ filter(owner__isnull=False). \ annotate(like_count=Count('likes')). \ order_by('-like_count', 'title'). \ all()[:3] context['books_to_show'] = books return context This is my model: class Book(models.Model): TITTLE_MAX_LENGTH = 64 AUTHOR_MAX_LENGTH = 64 UPLOAD_PICTURE_MAX_SIZE_IN_MB = 2 title = models.CharField( max_length=TITTLE_MAX_LENGTH, ) author = models.CharField( max_length=AUTHOR_MAX_LENGTH, ) category = models.ForeignKey( to=Category, null=True, blank=True, default='', on_delete=models.SET_DEFAULT, ) image = CloudinaryField( "Image", null=True, blank=True, transformation={"quality": "auto:eco"}, overwrite=True, ) owner = models.ForeignKey( to=get_user_model(), on_delete=models.SET_NULL, null=True, blank=True, related_name='own_books', ) ex_owners = models.ManyToManyField( to=get_user_model(), related_name='ex_books', blank=True, ) previous_owner = models.ForeignKey( to=get_user_model(), related_name='books_to_send', null=True, blank=True, on_delete=models.SET_NULL ) next_owner = models.ForeignKey( to=get_user_model(), related_name='book_on_a_way', null=True, blank=True, on_delete=models.SET_NULL ) likes = models.ManyToManyField( to=get_user_model(), related_name='liked_books', blank=True, ) is_tradable = models.BooleanField( default=True, ) @property def likes_count(self): return len(self.likes.all()) def __str__(self): return f'"{self.title}" by {self.author}' class Meta: ordering = ['title'] def get_absolute_url(self): return reverse('book_details', kwargs={'pk': self.pk}) I have no idea how to test if the view gets the top 3 most liked books. I will easily create some books, but I do not know how to mock the value for likes count. I could create manually a lot of users add them to the book.likes but hope there is another … -
Django app isn't working with docker and nginx
I am trying to launch django + docker + nginx web application I don't see any errors in docker-compose logs. Full log: https://pastebin.com/tUpf5Wv0 But local urls 0.0.0.0:80 or 127.0.0.1:80 are not working. It seems that problem deals with nginx but I don't see any errors in logs. How can I find the reason of the problem? Application structure (full code https://github.com/mascai/django_docker_nginx_template) . ├── docker-compose.yml ├── project │ ├── core_app ... │ ├── nginx-conf.d │ │ └── nginx-conf.conf │ ├── parser_app ... Dockerfile FROM python:3.9-alpine WORKDIR /project COPY . . RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev linux-headers postgresql-dev && \ pip install --no-cache-dir -r requirements.txt nginx-conf.conf upstream app { server django:8000; } server { listen 80; server_name 127.0.0.1; location / { proxy_pass http://django:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /var/www/html/static/; } } Docker compose file (looks fine) version: '3.9' services: django: build: ./project # path to Dockerfile command: sh -c "gunicorn --bind 0.0.0.0:8000 core_app.wsgi" volumes: - ./project:/project - static:/project/static expose: - 8000 environment: - DATABASE_URL=postgres://postgres:post222@db:5432/lk_potok_4" - DEBUG=1 db: image: postgres:13-alpine volumes: - pg_data:/var/lib/postgresql/data/ expose: - 5432 environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=MY_PASSWORD - POSTGRES_DB=lk_potok_4 nginx: image: nginx:1.19.8-alpine depends_on: - django ports: … -
DateField in Django
I am having an issue with the DateField field in Django. I see "midnight" getting attached to the field in the admin page. And this only shows in my E3, not E1. models.py: class BackoutLogFile(models.Model): log_id = models.AutoField(primary_key=True) device_name = models.CharField(max_length=800, verbose_name='Device Name',default='sampledevice') log_user_id = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL, verbose_name='User ID') log_user_email = models.CharField(max_length=500, verbose_name='User Email',default='admin') change_number = models.CharField(max_length=100, verbose_name='Change Number',default='CHG00000000') #log_capture_date = models.CharField(max_length=30, verbose_name='Event Date') log_capture_date = models.DateField(max_length=30, verbose_name='Event Date',auto_now=True) log_details = models.TextField(verbose_name='Log Details') class Meta: verbose_name = 'Backout Logs' verbose_name_plural = 'Backout Logs' def __unicode__(self): return '%s %s %s %s %s %s' % (self.device_name,self.log_user_id,self.log_user_email,self.change_number,self.log_capture_date,self.log_details) place where obj is saved: obj=BackoutLogFile(log_user_id=user,device_name=spine_backout_list_name[i],log_user_email=request.user.email,change_number=changeRequestNumber,log_details=event_data) obj.save() -
Django - Add a confirmation email fuction
Create user page image So we have a fully working signup page so far, and I want to add a simple confirmation email function so that it simply sends an email to the user that their account was sucsessfully created. I don't necessarily need any extra functions like a verification link in the email to activate the account, etc. I have been looking at tutorials online, but as they all seem to have a registration feature built into them (which our prject already has). As we just need that verifcation function, I was hoping I could get a bit of direction here. I am new to Django and do not have a full understanding of what I am doing. Django version = 4.0.2 Python version = 3.9 -
is there any way to add an image in the following code?
I'm trying to make a simple website using django and following bootstrap5 examples. I'd like to know if there is any way to add a image in the indicated spot from the following picture. here is the code: {% extends "pages/base.html" %} {% block header %} <main class="container"> <div class="p-4 p-md-5 mb-4 text-white rounded bg-dark"> <div class="col-md-6 px-0"> <h1 class="display-4 fst-italic">Title of a longer featured blog post</h1> <p class="lead my-3">Multiple lines of text that form the lede, informing new readers quickly and efficiently about what’s most interesting in this post’s contents.</p> <p class="lead mb-0"><a href="#" class="text-white fw-bold">Continue reading...</a></p> </div> </div> </main> {% endblock header %} {% block content %} <p> this is a content block </p> {% endblock content %} -
Save request.user to Django Form using post method in class based view
I want to fill the user field with request.user. But I need to use CBV. I am not too good with CBVs. I have tried to build something like that in views.py but not the true way models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils.translation import gettext_lazy as _ class Entry(models.Model): title = models.TextField(max_length=30, help_text=_("Enter your title"), verbose_name=_("Title")) content = models.TextField(max_length=500, help_text=_("Enter your content"), verbose_name=_("Content")) user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: verbose_name = 'Entry' verbose_name_plural = 'Entries' def get_absolute_url(self): return reverse("model_detail", kwargs={"pk": self.pk}) views.py from django.views.generic import ListView from .models import Entry from .forms import EntryForm class EntryListViev(ListView): model = Entry context_object_name = 'object_list' template_name = 'home.html' def form_add_the_user(request, form): form.user = request.user return super().form_add_the_user(form) forms.py from django import forms from .models import Entry class EntryForm(forms.ModelForm): title = forms.CharField(max_length=30, help_text=_("Enter your title")) content = forms.CharField(max_length=500, help_text=_("Enter your content")) class Meta: model = Entry fields = ['title', 'content'] home.html <form method="POST"> {% csrf_token %} {{form}} <button type="submit">Submit</button> </form> {% for post in object_list %} {{post.title}} {% endfor %} -
Django/HTML button that disables after being clicked
I am implementing a button that when a user clicks it (this is in Django and HTML), will add them to the list of attendees but I do not want the user to be able to click it multiple times (1 user attending the same session x amount of times). What is the best way for going about this? Is there easy logic to implement this, or is it easier to implement logic that when it is clicked, it gets the user name of the user and checks if they are already in the list of attendees for the session already and if they aren't then it adds them and if they are then it just ignores it? -
Avoid multiples queries on serializer with `PrimaryKeyRelatedField` in a `ListField`
I have the following serializer class SomeSerializer(serializers.Serializer): fields = serializers.ListField( allow_empty=False, child=serializers.PrimaryKeyRelatedField(queryset=someModel.objects.all()) ) When I run the following code on my view/code: serializer = SomeSerializer(data={'fields': [1, 2, 3, 4]}) serializer.is_valid() 4 different queries are run against the DB, one get(id) for each someModel. Is there any way to ask the serializer to perform just one query?, that way the serializer uses something like: queryset.filter(pk__in=[1, 2, 3, 4]) instead of: queryset.get(1) queryset.get(2) queryset.get(3) queryset.get(4) I tried digging on the django-rest-framework source code and it looks like it only performs get in order to get the data of each model. But maybe I'm missing something. -
Django Bootstrap Message not showing box and collor
my django bootstrap messages not showing the "Colored box" like it suppose to do, this is what it shown : settings.py MESSAGE_TAGS = { messages.INFO: 'alert-info', messages.SUCCESS: 'alert-success', messages.WARNING: 'alert-warning', } views.py def testpage(request): messages.info(request, 'TEST INFO') messages.success(request, 'TEST SUCCESS') messages.warning(request, 'TEST WARNING') return render(request, 'main/testpage.html') testpage.html {% for message in messages %} <div class="container-fluid p-0"> <div class="alert {{ message.tags }} alert-dismissible" role="alert" > <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="True">&times;</span> </button> {{ message }} </div> </div> {% endfor %} -
Django Sitetree returning "expected str instance, LazyTitle found" in {% sitetree_page_title from menu %}
Django version: 3.2.9 & 4.0.4 Python version:3.8.10 OS: Ubuntu 20.04lts I have a sitetree that is using a context variable in the title. When going to that path and loading the template with {% sitetree_page_title from menu %} it returns sequence item 1: expected str instance, LazyTitle found. I didn't find any information on this exact issue, but it seems that when using context data in the title a LazyTitle object is generated. The object is not being converted to a string so the template engine is bombing. I will include the relevant code below. I was able to get around the issue by editing sitetreeapp.py and wrapping the return of get_current_page_title() in str(), but that feels excessive. The app in question is a small test app I'm working to layout an example CRUD app with the features our company needs. It does nothing fancy. The app isn't 100% complete yet so if anything looks out of place, it could be I haven't got to that point, but this portion should be working fine. The sitetree in question is loaded dynamically via the config.ready method. Menu items without context variables are working without issue. I have verified that the context … -
filter query for searching with tags throughs errror
I have added tags for records to be displayed when tag is searched.it throughs error models.py class Tag(BaseModel): name = models.CharField(max_length=64, blank=True, null=True) class Books(BaseModel): name = models.Charfield(max_length=200) tags = models.ManyToManyField('Tag', related_name='books', blank=True) def __str__(self): return self.name views.py def get_filters(self, request): filters = [] search = request.query_params.get('search', '') category = request.GET.get('category', None) if search: filters.append(Q(name__icontains=search) | Q(tags_icontains=search)) return filters errorstack django.core.exceptions.FieldError: Cannot resolve keyword 'tags_icontains' into field -
How to use django rest api to create user and how to define user level?
Create REST APIs based on Django with PostgreSQL database. It should contain: User Sign Up/Forgot Password APIs. Uses JWT authentication. Must define 3 user levels: 1. Super-admin, 2. Teacher, 3. Student (Use internal Django Groups to achieve the same). Teacher must be able to add/list the students. Admin must be able to add/list every user in the database. Students must be able to see his information only I have to solve the above assignment myself but didn't understand the question from 3rd instructions. I know to create groups and users from the Django admin panel but I think they expect to create users using API. What I am thinking to do is to create groups of super-admin, student, and Teacher manually from the admin panel. import User from from django.contrib.auth.models import User and save data to it.(Here the problem is I don't know how to import serializer for User or I should create it) And then add user to group (student, Teacher or super-admin) Please help me to understand 3rd instruction. -
Solution to installing GDAL/PROJ/GEOS in windows 10 for Django/Geodjango
Whether you are finding it difficult to install the GDAL library or have been able to install it but do not know how to make it work in Django for your geoDjango app, I would like to share how I was able to successfully get it to work for me. I hope I would not miss any step as it took me days to make it work. -
Django Channels cannot establish Websocket connection with Custom middleware
I'm learning Django Channels and trying to make my custom Authentication middleware. I start with the code from the official docs. I try to set up a connection via Postman but it doesn't work. It works well if I remove the middleware in my asgi.py Here my code: # routing.py websocket_urlpatterns = [ re_path('ws/chat/hihi', ChatRoomConsumer.as_asgi()), ] # asgi.py application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': QueryAuthMiddleware(URLRouter( chatroom.routing.websocket_urlpatterns )) }) My middleware is copied from the official docs. @database_sync_to_async def get_user(user_id): try: return User.objects.get(id=user_id) except User.DoesNotExist: return AnonymousUser() class QueryAuthMiddleware: """ Custom middleware (insecure) that takes user IDs from the query string. """ def __init__(self, app): # Store the ASGI application we were passed self.app = app async def __call__(self, scope, receive, send): # Look up user from query string (you should also do things like # checking if it is a valid user ID, or if scope["user"] is already # populated). scope['user'] = await get_user(int(scope["query_string"])) return await self.app(scope, receive, send) Here is my simple consumer class ChatRoomConsumer(JsonWebsocketConsumer): def connect(self): print('connect....') if self.scope['user'].is_anonymous: self.close() self.accept() def disconnect(self, code): print('ahihihihihi') raise StopConsumer def receive(self, text_data=None, bytes_data=None, **kwargs): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) With this, I cannot establish connection … -
Best way to include a sub-select queryset in Django in just 1 hit to the database
I have 2 models, Product and Productdetails with a OneToOne relationship like this: class Product(IotaModel): stripe_product_id = models.CharField( blank=True, max_length=100, help_text='Product ID in Stripe.' ) details = models.OneToOneField( ProductDetails, null=True, on_delete=models.SET_NULL ) I want a queryset that do this: SELECT * FROM product_details WHERE id = ( SELECT details_id FROM products WHERE id=<product_id> ) I tried this: details_id = Product.objects.filter(pk=product_pk, active=True).only('details')[:1] return ProductDetails.objects.filter(pk=details_id, active=True) But it does not work becouse .only('details') gave me the fields (id, details_id) and the next filter takes id instead of details_id. I also try to add .defer('id') but that does not work. I know that I can get the details_id using .values_list('details_id') but I think this would involve making 2 queries to the Database. What could be the best approach to reach the desired SQL query in just 1 hit to the DB? Thanks in advance! -
Gitlab CI/CD Pipeline Runs Django Django Runs Unit Tests Before Migrations
Problem I'm trying to set up a test stage in Gitlab's CI/CD. Locally, running the unit tests goes fine and as expected. In Gitlab's CI/CD, though, when running the script coverage run manage.py test -v 2 && coverage report the unit tests are executing before the migrations are completed in the test database, which is unexpected, and will always fail. Migrations on the test database need to run prior to unit tests executing. Any idea why this behavior might happen? Things I've already tried Removing coverage, and only executing python manage.py test Result: same error Removing user test, where Gitlab says the test fails: Result: same error Removing all but one unit test to attempt to isolate: Result: same error Adding and activating a virtual environment inside Gitlab's container: Result: same error Trying a SQLite3: Result: migrations fail due to necessary array field necessary in the project not supported in SQLite3 Gitlab output My actual output is much bigger. But here's the relevant parts: $ echo $TEST_SECRETS | base64 -d > config/settings/local.py $ echo RUNNING UNIT TESTS RUNNING UNIT TESTS $ coverage run manage.py test -v 2 && coverage report Creating test database for alias 'default' ('test_mia')... test_dataconnector_category_creation_delete (apps.core.tests.test_models.DataConnectorCategoryTestCase) Verify … -
Django Rest Framework Serialize Model into Object with Custom Key
I am working with Django and djangorestframework. What should I modify to get desired output? serializers.py: from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username'] views.py: from django.contrib.auth.models import User from rest_framework import viewsets from .serializers import UserSerializer class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer current output: [ { "id": 1, "username": "some_username" }, { "id": 2, "username": "another_username" } ] desired output: { "some_username": { "id": 1 }, "another_username": { "id": 2 } } -
Url Redirection in django
I have an app created in django and deployed at KeshavBits heroku. And after deploying app I purchased a domain (https://keshavbits.in/) and managed to point it to https://keshavbits.herokuapp.com/ So now I have two domains to acccess my website https://keshavbits.herokuapp.com/ https://keshavbits.in/ Both links shows the same website i.e hosted at heroku but the problem is when someone logs in at keshavbits-heroku then session is stored under its domain so when they visit keshavbits.in they have to log in again. I have checked django documentation and other stuff as well about multiple session manager but it works only when website is like home.keshavbits.in and play.keshavbits.in So I thought to redirect traffic to keshavbits.in when someone hits https://keshavbits.herokuapp.com/ But I don't have any idea to do that. Kindly help me :)