Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 4.1. changes in Admin changelist searches spanning multi-valued relationships
This question is in the context of Admin changelist searches spanning multi-valued relationships changes introduced in django 4.1 as explained here. Suppose there's a model arrangement as follows: class Person(models.Model): official_name = models.CharField(max_length=255) ... class NickName(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) nick_name = models.CharField(max_length=255) ... And suppose that NickNameAdmin is implemented as: class NickNameAdmin(admin.ModelAdmin): search_fields = ['person__official_name', 'nick_name'] ... Now, suppose a person with Robert Downey as his official name also has Iron Man and Junior as his nick names. Now, if one were to search for Iron Man, then how is the search filter going to behave for NickNameAdmin? Will it search for Iron in the person__official_name field and Man in the nick_name field? -
Cleaning Django ArrayField
I have a model which stores response data coming from an API. The API returns the data in a JSON format and we change it into a dictionary and feed it to the model like this: obj, _created = MyModel.objects.update_or_create(unique_id=value, defaults=response_dict_data) the issue here Is one of the fields is an ArrayField and in the response, if it's a single value it's returned as the value itself without being in a list. the way currently I solve this is by checking/cleaning the value in the view and I have multiple array fields that face the same issue is there a better, more dynamical way to do this? if type(response_dict_data['array_field']) is not list: response_dict_data['array_field'] = [response_dict_data['array_field']] -
Advance django query
Let say i have a model like this : class A(): field1, field2, class Data(): field_fk (FK to A.field2) field_3 (unique field) field_4, Now lets say I have two model A like this : A1.Data = field_3 field_4 A 5 B 6 C 7 A2.Data = field_3 field_4 B 4 C 8 D 6 How can I query so I have comparison like this in the template : field_3 A1_field_4 A2_fiels_4 A 5 - B 6 4 C 7 8 D - 6 Sorry if its hard to understand, but what i want is i can query it like a VLOOKUP on excel based on field_3, but the catch is there is a field_3 in former A model that in recent A model didn't have but i still want it return as None, and there is a field_3 in recent A model but the former A model didn't have and i still want it return as None. So how can i achieve this ? -
DRF Intermediary Table - POSTing data to the Intermediary Table
I have a many-to-many relationship in my DB design and I am having trouble with the POST aspect. I currently have a table called Loads, Containers, and Container_Loads (this is the intermediary table). My question is this: I want to be able to send a POST request into the ContainerLoad intermediary table and just update that table with the values it requires which are: Load ID (PK of the Load table), Container ID (PK of the Container Table) and # of pallets (unique field to the intermediary table). I am able to GET/retrieve the records just fine, but when I try to send a POST request with a payload such as { "id":3, "pallets":"4", "containerNumberId":5, "loadNumberId":53 } (where containerNumberID and loadNumberID are the existing keys in their respective tables), it seems that my code wants to create a whole new Load entry as well (as it asks me for the remaining fields of the Load model), where as I just want to create an entry in the intermediary table without creating a new entry in the Load table. So for the purpose of my project, a load can be on many containers [imagine that it's split because all of it … -
Ignore cache within Django cache_page function on Redis ConnectionError
I'm using Redis to cache some views in my Django Rest Ramework API. Let's say I have the following view: from django.utils import timezone from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page from rest_framework.response import Response from rest_framework.views import APIView class MyView(APIView): @method_decorator(cache_page(60 * 15)) def get(self, request): return Response({"timestamp": timezone.now()}) Everything works great when Redis is up and running. However, our Redis instance has been having intermittent outages lately (shoutout Heroku Redis), which is causing all endpoints that use the Redis cache and, therefore, any endpoints that use the cache_page decorator, to crash and return a 500 Internal Server Error. I want to implement a failover mechanism that will simply ignore the cache and return a response successfully when a redis.ConnectionError is raised. Here is what I have so far: def cache_page_with_failover(timeout, *, cache=None, key_prefix=None): def decorator(view_func): @wraps(view_func) def wrapper(*args, **kwargs): try: return cache_page(timeout, cache=cache, key_prefix=key_prefix)( view_func )(*args, **kwargs) except redis.ConnectionError: return view_func(*args, **kwargs) return wrapper return decorator Usage: class MyView(APIView): @method_decorator(cache_page_with_failover(60 * 15)) def get(self, request): return Response({"timestamp": timezone.now()}) This works but it's awfully verbose and I feel like I'm copying most of the cache_page signature. Is there a cleaner and more elegant way to write this? -
How do I add a unique user to form from Model that shares Foreign Key?
I'm getting the following error: author = ForeignKey(User, db_column="user") TypeError: init() missing 1 required positional argument: 'on_delete' I've tried adding the positional argument to the form but that didn't fix it. I know that with the on_delete=CASCADING attribute it will delete all objects that have references to it. I know it's a form issue but I can't seem to find any answer which is why I'm posting this. Any help/guidance would be much appreciated! models.py from django.core.validators import MaxValueValidator, MinValueValidator from django.utils import timezone from django.db import models from django.contrib.auth.models import User class Review(models.Model): title = models.CharField('Movie Title', max_length=100) rating = models.IntegerField('Personal Rating', validators=[MinValueValidator(1), MaxValueValidator(10)]) comment = models.TextField('Comment', blank=True) datetime_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) # Show table in /admin page def __str__(self): return self.title forms.py from datetime import datetime from django.contrib.auth.models import User from django.db.models import ForeignKey from django.forms import ModelForm from django import forms from . import models from .models import Review class UploadReview(ModelForm): title = forms.CharField() rating = forms.IntegerField() comment = forms.Textarea() datetime_posted = datetime.now() author = ForeignKey(User, db_column="user") class Meta: model = Review fields = ['title', 'rating', 'comment'] exclude = ['datetime_posted', 'author'] -
How to use elasticsearch for mutiple models in Django using the same search api
I am trying to implement an elastic search in Django for multiple models in a single search api. If I had to implement using different apis I can do in the following way. my models.py class Category(models.Model): name = models.CharField(max_length=32) description = models.TextField(null=True, blank=True) class Meta: verbose_name_plural = 'categories' def __str__(self): return f'{self.name}' ARTICLE_TYPES = [ ('UN', 'Unspecified'), ('TU', 'Tutorial'), ('RS', 'Research'), ('RW', 'Review'), ] class Article(models.Model): title = models.CharField(max_length=256) author = models.ForeignKey(to=User, on_delete=models.CASCADE) type = models.CharField(max_length=2, choices=ARTICLE_TYPES, default='UN') categories = models.ManyToManyField(to=Category, blank=True, related_name='categories') content = models.TextField() created_datetime = models.DateTimeField(auto_now_add=True) updated_datetime = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.author}: {self.title} ({self.created_datetime.date()})' my serializers.py class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class ArticleSerializer(serializers.ModelSerializer): author = UserSerializer() categories = CategorySerializer(many=True) class Meta: model = Article fields = '__all__' views.py class CategoryViewSet(viewsets.ModelViewSet): serializer_class = CategorySerializer queryset = Category.objects.all() class ArticleViewSet(viewsets.ModelViewSet): serializer_class = ArticleSerializer queryset = Article.objects.all() documents.py @registry.register_document class CategoryDocument(Document): id = fields.IntegerField() class Index: name = 'categories' settings = { 'number_of_shards': 1, 'number_of_replicas': 0, } class Django: model = Category fields = [ 'name', 'description', ] @registry.register_document class ArticleDocument(Document): categories = fields.ObjectField(properties={ 'id': fields.IntegerField(), 'name': fields.TextField(), 'description': fields.TextField(), }) type = fields.TextField(attr='type_to_string') class Index: name = 'articles' settings = { 'number_of_shards': … -
Get Session Data in Django Consumer
I want to get session data in consumers.py, this session data will be used to filter data. The code like this. queryset = Mail.objects.filter(status='session_data') serializer_class = PostSerializer permissions = permissions.AllowAny async def connect(self, **kwargs): await self.model_change.subscribe() await super().connect() @model_observer(Mail) async def model_change(self, message, observer=None, **kwargs): await self.send_json(message) @model_change.serializer def model_serialize(self, instance, action, **kwargs): return dict(data=PostSerializer(instance=instance).data, action=action.value) How can i get it ? -
Trouble replying Django to heroku
so I’ve just finished building my first project. Just when I thought I was done, I ran into an issue during deployment. I’m getting an H10 error that is causing my app to crash when I try deploying it. I’ve checked my Procfile, settings, etc. I’ve tried just about everything , still can’t seem to find what the issue is. I’ve attached a few photos for anyone that is willing to help. Thanks in advance! enter image description here -
How to filter by field in django rest framework class based views
I have an app (class based views) with content in many languages and I want to give the option to filter by language in my endpoint like this: localhost:8000/api/resources/?language=ES This is my JSON data: { "id": 10, "contents": [ { "id": 5, "language": "EN", "name": "First" }, { "id": 6, "language": "ES", "name": "Primero" } ], "created_at": "2022-08-07T20:27:16.581115-05:00", "updated_at": "2022-08-07T20:27:16.581115-05:00" } What is the most elegant way of doing this? -
how do i change the language prefix to the user stored prefered language
I am working on a multilanguage Django project and i am using i18n for that, what i want to do is store the user-preferred language, I have already done that and added a language field in the User model, so my approach to solve this problem was creating a middleware to change to the user preferred language: from Django.utils import translation class LanguageMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated and request.user.language: translation.activate(request.user.language) else: translation.activate(translation.get_language()) response = self.get_response(request) return response and I set the user language to 'ar', but if I try to enter with the URL 127.0.0.1:8000/en it doesn't work as expected and gives me this 1.ar/ The current path, en/, didn’t match any of these. but what I wanted is to redirect it to this 127.0.0.1:8000/ar either from this 127.0.0.1:8000 or this 127.0.0.1:8000/en and of course, that will be based on the preferred language, and if the user is not authenticated it will be just based on the language data in the request, how can I do that please? -
CS50 Project 1 Help - Wiki Search w/ Django - Stuck on how to save a new page
So I am creating my Wiki Search Page with Django and everything is going fine so far. I am now stuck on how to create a new entry in my search encyclopedia. On my home bar the "Create new Page" link works fine and takes me to a new page where I can create a new entry. The problem is when I try and save the entry into my encyclopedia I get this message: ValueError at /new/ The view encyclopedia.views.new didn't return an HttpResponse object. It returned None instead. I think it is a problem in my views.py section but can't seem to figure it out. Here is my views.py def new(request): if request.method == 'GET': return render(request, "encyclopedia/new.html", { "create_form": CreateForm(), "search_form": SearchForm() }) file_content = request.POST.get("content","") file_title = request.POST.get("title", "") if (len(file_content) == 0 or len(file_title) == 0): return render(request, "encyclopedia/error.html", { "message": "Bad Request", "description": "Title and content cannot be empty", "status": 400 }) if util.get_entry(file_title): return render(request, "encyclopedia/error.html", { "message": "Bad Request", "description": "This page already exists", "status": 400 }) Everything with the page works fine. I get the correct error when trying to save the page without any entry. The problem is it just won't … -
Overriding Django's default id in it's User Model
We have a working Django project in a multi-master database environment. That means the we have multiple instances of the project's database running in separate machines and that all individual changes are propagated to the other databases. Is working very well in this setup and without any issues. Up to now, we were not using Django's Auth tooling, meaning that there was not user login or password. That has to change. For this to work in our replication environment, thou, we need to change User's default id to something akin of a UUID to avoid collisions when the replications occurs. So, the challenge at hand is this: how to change the id field of the User model in the Auth App? We don't have any other specific requirement except this. We don't need any extra field and anything. Just to change the id. In the case that writing our own custom User model is inescapable maybe someone could point us at some good blog post about it or share any other resource. Ideally we would like to preserve everything else. including access to admin's interface, groups and permissions. Thanks in advance -
Customer isn't created for a user while trying to log in with google
For my website, its all okay if I register and then log in. But when I try to log in with google Customer objects is unable to create. Therefore I found the error that User has no Customer. Here's my model view for customer: user = models.OneToOneField(User, on_delete=models.CASCADE, related_name = 'customer', null=True, blank=True) I tried to implement Customer creation but it seems no effect. here's my views.py: def google_login(request): redirect_uri = "http://127.0.0.1:8000/accounts/google/login/callback/" % ( request.scheme, request.get_host(), reverse('pain:google_login') ) if('code' in request.GET): params = { 'grant_type': 'authorization_code', 'code': request.GET.get('code'), 'redirect_uri': redirect_uri, 'client_id': settings.GP_CLIENT_ID, 'client_secret': settings.GP_CLIENT_SECRET } url = 'https://accounts.google.com/o/oauth2/token' response = request.post(url, data=params) url = 'https://www.googleapis.com/oauth2/v1/userinfo' access_token = response.json().get('access_token') response = request.get(url, params={'access_token': access_token}) user_data = response.json() email = user_data.get('email') if email: user, _ = User.objects.get_or_create(email=email, username=email) Customer.objects.get_or_create(email=email, username=email) gender = user_data.get('gender', '').lower() if gender == 'male': gender = 'M' elif gender == 'female': gender = 'F' else: gender = 'O' data = { 'first_name': user_data.get('name', '').split()[0], 'last_name': user_data.get('family_name'), 'google_avatar': user_data.get('picture'), 'gender': gender, 'is_active': True } user.__dict__.update(data) user.save() user.backend = settings.AUTHENTICATION_BACKENDS[0] login(request, user) else: messages.error( request, 'Unable to login with Gmail Please try again' ) return redirect('/') else: url = "https://accounts.google.com/o/oauth2/auth?client_id=%s&response_type=code&scope=%s&redirect_uri=%s&state=google" scope = [ "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email" ] scope = " ".join(scope) … -
QuerySet object has no attribute "email"
I am trying to get a list of all pathologists in my system. I need to filter the user on 2 basis i-e is_pathologist and Lab_Id=request.data[email] I have tried switching between filter and get but then I get Authentication.models.User.MultipleObjectsReturned: get() returned more than one User -- it returned 12! This is the code of my view @api_view(['POST']) def getAllPathologists(request): user = get_user_model().objects.get(is_pathologist=True) # If user exists, get the employee print("user is: ", user) pathologist = Employee.objects.get(user=user.email, Lab_Id=request.data['email']) pathologistSerializer = EmployeeSerializer(pathologist, many=True) return Response(pathologistSerializer.data) This is user model class User(AbstractUser): # Add additional fields here id = None email = models.EmailField(max_length=254, primary_key=True) name = models.CharField(max_length=100) password = models.CharField(max_length=100) contact_number = models.CharField(max_length=100) is_patient = models.BooleanField(default=False) is_doctor = models.BooleanField(default=False) is_homesampler = models.BooleanField(default=False) is_pathologist = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_lab = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now=True,editable=False) last_login = models.DateTimeField(auto_now=True) first_name = None last_name = None username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'password'] objects = CustomUserManager() def __str__(self): return self.email # Ensure that the password is hashed before saving it to the database def save(self, *args, **kwargs): self.password = make_password(self.password) super(User, self).save(*args, **kwargs) def has_perm(self, perm, obj=None): return self.is_superuser This is Employee model class Employee(models.Model): user = … -
How can I send a message to all posts in Django Allauth?
I am trying to send an email to all registered users in Django Allauth, but when I try to get a list of all users' emails and send it via the send_mail() method, I get an error : too many values to unpack (expected 2) When I manually specify the mail in the recipient_list list, then everything works. But I need it to be automatically sent to the emails of all users. Tried to do through : def email(request): cleaned_data = super().clean() title = cleaned_data.get('articles_title') message = cleaned_data.get('articles_text') recipient_list = User.objects.get('email') email_from = 'mymail' send_mail(title, message[:50], email_from, recipient_list) return title, message or iterate through the for loop: def email(request): cleaned_data = super().clean() title = cleaned_data.get('articles_title') message = cleaned_data.get('articles_text') mails = User.objects.get('email') recipient_list = [] for i in mails: recipient_list.append(i) email_from = 'mymail' send_mail(title, message[:50], email_from, recipient_list) return title, message But nothing helps, does someone know some alternative method? -
Should I use Django or FastAPI?
I am developing an app Can I use FastAPI? Or is using apps only in Django? And in general If I need to develop a very fast application In which framework would you recommend? (My application is coded in Python, React Native, and Mongo) -
Why is Django having trouble accessing my User table?
I am new to Django and web development in general. I am trying to test my app, recipe_book, using the admin page. When try to login at http://127.0.0.1:8000/admin, I get the following error: no such table: recipe_book_user I have a model class named "User", defined below: from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass I then successfully made migrations and migrated the changes. To resolve this issue, I've tried registering the User class in admin.py, with no success. I've also tried following the steps to reset the database in the following question: Django - no such table exception Does anyone know how I can resolve this? -
Query with two ForeignKeys in a model and filter on one of the ForeignKey
I have the three models: class SegmentEffort(models.Model): id = models.BigIntegerField(primary_key=True) activity = models.ForeignKey(to=Activity) segment = models.ForeignKey(to=Segment) class Segment(models.Model): id = models.BigIntegerField(primary_key=True) name = models.CharField(max_length=255) class Activity(models.Model): id = models.BigIntegerField(primary_key=True) user = models.ForeignKey(to=settings.AUTH_USER_MODEL) name = models.CharField(max_length=255) I want to get all distinct segments from SegmentEffort where SegmentEffort is filtered by Activity belonging to a specific user. I can get a list of all the segment ids by: sids = SegmentEffort.objects.filter(activity__user=10).order_by('segment_id').values_list('segment_id', flat=True).distinct() But I can't get my head around getting distinct a segment queryset... Not enough experience with queries on two ForeignKeys in a model (SegmentEffort). Thanks for your help, and don't hesitate to ask for clarification id the question is unclear! -
Application Load Balancer Health Django Elastic Beanstalk Barebones
Using this guide below to setup a simple app: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html I used the interactive eb create to chose an Application Load Balancer vs the Classic (I used CLASSIC before and it works).. Anyways, why does this not work "OUT OF THE BOX" like the Classic Load Balancer? What do I need to configure as the docs are all over the place (and outdated)? Like really, this should work out of the box (I am using the most barebones django test app) Works in Classic Load Balancer and not in Application Load Balancer. Thanks. some docs: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/target-group-health-checks.html https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.managing.elb.html -
Trying to create a separate comments app for a django ticket project
I'm trying to create a separate comments app for a ticket project using class-based views for both the tickets and the comments. I think I got most of the functionality down, because when I try to use the comment feature on the site itself, it shows up in the django admin but not on the site. I believe the problem lies in my urls.py files or it could be my model, but I'm not so sure how to proceed. Please help Here's the traceback Installed Applications: ['tickets.apps.TicketsConfig', 'users.apps.UsersConfig', 'comments.apps.CommentsConfig', 'demo.apps.DemoConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['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'] Traceback (most recent call last): File "C:\Users\mikha\bug_env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\mikha\bug_env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\contrib\auth\mixins.py", line 71, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\base.py", line 101, in dispatch return handler(request, *args, **kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 174, in post return super().post(request, *args, **kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 144, in post return self.form_valid(form) File "C:\Users\mikha\issuetracker\comments\views.py", line 41, in form_valid return super().form_valid(form) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 128, in form_valid return super().form_valid(form) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 59, in … -
Assistance Required to select and set different OAuth ClientId and ClientSecret credentials for all views
I am working on my first ever Django project and have been trying to do something that I have been stuck with for weeks and looking for any assistance, please. each of my views uses a CLIENT_ID, CLIENT_SECRET and I have a page with a drop-down to select one of the OAuth Accounts that I would like to use. Menu Screenshot HTML Snippet <h2>Select Menu</h2> <p>To style a select menu in Bootstrap 5, add the .form-select class to the select element:</p> <label for="cust" class="form-label">Select list (select one):</label> <select class="form-select" id="cust" name="customer"> <option>Auth 1</option> <option>Auth 2</option> <option>Auth 3</option> <option>Auth 4</option> </select> <input type="submit" value="click" class="btn btn-primary"> Views.py snippet def data(request): # OAuth when using Client Credentials CLIENT_ID = CLIENT_ID CLIENT_SECRET = CLIENT_SECRET def getdata(request): # OAuth when using Client Credentials CLIENT_ID = CLIENT_ID CLIENT_SECRET = CLIENT_SECRET When an Auth Selection is made via the dropdown, I would like to set the CIENT_ID and CLIENT_SECRET to be used for all of my views. Ultimately I would like to use dotenv as well. I am struggling to get the selection and then set the CIENT_ID and CLIENT_SECRET to each view. Thank you very much. -
Querying One model item from another model
Please help me. I have a list of Artist (Musicians) and their Albums they created. T My models looks like the following: from django.db import models # Create your models here. class ArtistModel(models.Model): Artist_name = models.CharField(max_length=50, null=True, default=False) def __str__(self): return self.Artist_name class AlbumsModel(models.Model): Genre = { ('Hip-Hop','Hip-Hop'), ('Rnb','Rnb'), ('Rock n Roll','Rock n Roll'), ('House','Housep'), ('Gospel','Gospel'), ('Classical','Classical'), } Album_name = models.CharField(max_length=50, null=True, default=False) Album_by = models.ForeignKey(ArtistModel ,max_length=50, null=True, default=False, on_delete=models.CASCADE) Music_genre = models.CharField(max_length=50, null=True, default=False, choices=Genre) def __str__(self): return self.Album_name My Views from django.shortcuts import render from . models import AlbumsModel, ArtistModel # Create your views here. def Albums(request): AllAlbums = AlbumsModel.objects.all() return render(request, 'Albums/Home.html', {'AllAlbums':AllAlbums}) def Artist(request): AllArtist = ArtistModel.objects.all() return render(request, 'Albums/Artist.html', {'AllArtist':AllArtist}) My HTML is the following: {% extends 'Albums/Layout.html' %} {% block content %} <h1>Artist</h1> <br/> {% for artistview in AllArtist %} <a href="{% url 'Artist_album' %}"> {{artistview}}<br> </a> {% endfor %} {% endblock %} My shell looks like the following: In [24]: All_Albums Out[24]: <QuerySet [<AlbumsModel: THE EMINEM SHOW>, <AlbumsModel: THE MARSHELL MATHERS LP>, <AlbumsModel: BLUEPRINT>, <AlbumsModel: THE BLACK ALBUM>, <AlbumsModel: 4:44>, <AlbumsModel: MAGNA CARTA HOLY GRAIL>, <AlbumsModel: JESUS IS KING>, <AlbumsModel: DONDA>, <AlbumsModel: GRADUATION>]> In [25]: Artist_all Out[25]: <QuerySet [<ArtistModel: Eminem>, <ArtistModel: Jayz>, <ArtistModel: … -
How to update value in JSON field in Django Rest Framework
I am making an API with Django Rest Framework and I have a problem. When I try to change the value of JSONfield from False to True (or vice versa) it doesn't change the value of specific key, but it changes the whole JSONfield to True(or False). How do I change the value of just a key? My models.py: class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", unique=True, max_length=100) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) fruit = models.JSONField(default={"Apple":False, "Pear": True, "Orange":False}) #This is that field USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) My serializers.py: class FruitSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ["fruit"] def update(self, instance, validated_data): instance.fruit = validated_data.get('fruit', instance.fruit) instance.save() return instance My views.py: class UpdateFruitView(generics.UpdateAPIView): queryset = Account.objects.all() serializer_class = FruitSerializer permission_classes = (IsAuthenticated,) def update(self, request, *args, **kwargs): fruit = request.data.get("fruit") select_fruit = request.user.fruit[fruit] if select_fruit == False: select_fruit = True data_to_change = {'fruit': select_fruit} serializer = self.serializer_class(request.user, data=data_to_change, partial=True) if … -
Unable to use ManyToMany Field with Django and Postgres
I am working on a project with Django, Postgres. I typed that : user_test = User.objects.first() food_test = Food.objects.first() user.food.add(food_test) When I type that : user.food I got that : <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7471bd30> Then if I type that : user.food.name I got that : AttributeError: 'ManyRelatedManager' object has no attribute 'name' Whereas the field name exists. Could you help me please ? Thank you very much !