Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : the database needs something to populate existing row
models . py : class Equipe(models.Model): NomEquipe = models.CharField(max_length=10,unique=True) Description = models.CharField(max_length=10,unique=True) class planning (models.Model): datedebut= models.DateField datefin=models.DateField nbrH=models.TimeField class Conseiller(models.Model): Matricule = models.CharField(max_length=10,unique=True) Nom = models.CharField(max_length=200) Prenom = models.CharField(max_length=200) Tel = models.CharField(max_length=200) Mdp = models.CharField(max_length=200) Email = models.EmailField(max_length=200) File = models.CharField(max_length=200) Preavis = models.BooleanField(default=False) sup = models.CharField(max_length=200) Equipe = models.ForeignKey(Equipe, on_delete=models.CASCADE) planning = models.ForeignKey(planning , on_delete = models.CASCADE) WHEN I try to execute Manage.py makemigrations a have the errors and i need to fix this -
How to create a list of dictionaries from a dictionary with lists of different lengths
I want to create a list of dictionaries with the same index element from each list. I have a this dictionary: d = {'name': ['bob', 'john', 'harry', 'mary'], 'age': [13, 19, 23], 'height': [164, 188], 'job': ['programmer']} The desired output is: d2 = [{'name': 'bob', 'age': 13, 'height': 164, 'job': 'programmer'}, {'name': 'john', 'age': 19, 'height': 188}, {'name': 'harry', 'age': 23}, {'name': 'mary'}] I have tried something like this: d2 = [dict(zip(d, t)) for t in zip(*d.values())] But my output is: d2 = [{'name': 'bob', 'age': 13, 'height': 164, 'job': 'programmer'}] I think this is happening because the lists have different lengths -
What's an appropriate way to setup consumer driven contract testing for django api and react clients?
I just learned a new term called consumer driven contract testing. I was thinking maybe it can help me solve my problem with writing tests for a django api provider and react frontend architecture project. The frontend and the Django API backend are in separate repos and have their own unit tests. However, once in a while there will be error because the frontend is assuming some fields that are not returned by the Django service backend. I initially thought about writing end to end test, but they are slow to run and highly brittle. I found this consumer driven contract testing and it sounds like the right thing. But when i google around, i cannot find anything suitable. Even Pact seems to be solely for just converting the contract to consumer tests. What's a suitably easy way to have consumer driven contract testing for this scenario? -
I want to send an email at 11 am everyday
I want to send an email at 11 am everyday by using Python. But I do not know hot to send at 11 am everyday.Now,I can write a code to send an email. from django.core.mail import EmailMessage def send?email(self): email = EmailMessage(subject, message, None, email_to) email.send(fail_silently=False) I checked this document,but I could not find how to send an email at designated time. https://docs.python.org/3/library/email.message.html -
How do i correctly implement web scrapping into my api
I'm making a django api that is able to return a definition of a word to a user this word is looked up by using a word=(put word here) url, this api scrapes dictionary.com to get the definition if it does not already exist inside my database, than adds it to my database if it exists on their site. i'm just trying to figure out how to actually structure it correctly instead of just throwing it into my view. I want to be able to return json to the end user with suggestions if a word is not found in the database or on their websites by scrapping their recommendations. I have tried returning json responses inside the view if a 404 error happens. Always throws a error i'm under the assumption my whole structure is wrong. def get_queryset(self): word = self.kwargs['word'] headers = {"User-Agent": "user agent stuff"} if not Word.objects.filter(word=word).exists(): page = requests.get(f"https://www.dictionary.com/browse/{word}?s=t", headers=headers) soup = BeautifulSoup(page.content, 'html.parser') try: output = soup.find("div",{"value": "1"}).get_text() test = Word(word=self.kwargs['word'].strip(), meaning=output) test.save() except: return return Word.objects.all() i expect the user to be able to get a definition if the word exists or if it doesn't to be able to return recommendations that i … -
django api throwing 500(internal server) error with connection to mysql
I get 500(Internal Server Error) for the below code, cant able to identify the problem. Please help me urls.py from django.conf.urls import url from .audfile import daywisedetail,hourwisedetail urlpatterns = [ url(r'^pyapi/api/daywise/(?P<start_date>[\w-]+)/(?P<end_date>[\w-]+)/$',daywisedetail.as_view()), url(r'^pyapi/api/hourwise/(?P<start_date_val>[\w-]+)/(?P<end_date_val>[\w-]+)/$',hourwisedetail.as_view()), ] audfile.py from rest_framework.views import APIView from django.http import JsonResponse from django.http import HttpResponse from django.shortcuts import render from django.views.generic import View from django.template.loader import get_template from rest_framework.response import Response from rest_framework import status import MySQLdb sdatabase = MySQLdb.connect(host="localhost",user="root",passwd="password",db="main") class daywisedetail(APIView): def get(self,request,start_date=None,end_date=None,format=None): db = sdatabase cursor = db.cursor() daydetail = """select id, values, name, email from day_users where date(reg_date) between '%s' and '%s' """ % (start_date,end_date) cursor.execute(daydetail) getdaydetailresult = cursor.fetchall() mainlist=[] for v0 in getdaydetailresult: for v1 in v0: mainlist.append(v1) data = { "hours": mainlist } return Response(data) class hourwisedetail(APIView): def get(self,request,start_date_val=None,end_date_val=None,format=None): db = sdatabase cursor = db.cursor() hourwisedata = """select id, values, name, email from hour_users where date(reg_date) between '%s' and '%s' """ % (start_date_val,end_date_val) cursor.execute(hourwisedata) hourwisedataresult = cursor.fetchall() mainlist1=[] for v2 in hourwisedataresult: for v3 in v2: mainlist1.append(v3) data1 = { "days": mainlist1 } return Response(data1) If i have single class(daywisedetail), api is working properly, if i am adding second class(hourwisedetail), both the apis are showning 500 responce. cant able to find where is the … -
Check Django migrations status programmatically
I need to run an initial migration for a Django project without allowing system checks (because the error will be resolved by creating the models) Right now, I'm using a custom command like so: class Command(BaseCommand): help = "Init project by launching initial migration without system checks" requires_system_checks = False def handle(self, *args, **options): management.call_command("migrate", "app", "0001_initial") This command is run by the script that bootstrap the environment (with docker-compose) It runs really well the first time, as no migrations have been executed. If I restart it however, this custom command forces the project to revert migrations back to 0001_initial. Is there a clean way to check programmatically if a migration has been executed ? I think I could get some values from the django_migrations table, but I'd rather use something cleaner if it exists. Thanks for your help! -
How to make django site https in windows10
How to make django site https in windows10. I am using public IP not local host. I tried putting the following code in settings.py got from Error "You're accessing the development server over HTTPS, but it only supports HTTP" CORS_REPLACE_HTTPS_REFERER = False HOST_SCHEME = "http://" SECURE_PROXY_SSL_HEADER = None SECURE_SSL_REDIRECT = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False SECURE_HSTS_SECONDS = None SECURE_HSTS_INCLUDE_SUBDOMAINS = False SECURE_FRAME_DENY = False I get the following error [09/Sep/2019 12:50:18] code 400, message Bad request version ('Gð\x1a\x15Ä«Öõß/\x02h|.\x9a\x11,\x93') [09/Sep/2019 12:50:18] You're accessing the development server over HTTPS, but it only supports HTTP. I even made DEBUG = False But no use still the same error. Now my issue is I am lost in trying to implement SSL in django on Windows 10 OS -
How to predict in multiple and simultanous Keras classifier sessions?
I know similar questions has been asked before and I have read all of them but none solved my problem. I have a Django project in which I am using CNNSequenceClassifier from sequence_classifiers which is a Keras model. The model files have been fit before and saved to particular destinations from which I again load them and predict what I want. clf = CNNSequenceClassifier(epochs=2) When I load the model I do this, due to the suggestions I found in searches, which is using the global model before loading the model, and then the other two lines: global clf clf = pickle.load(open(modelfilenameandpath, "rb")) global graph graph = tf.get_default_graph() and before predicting I use graph.as_default() with graph.as_default(): probs = clf.predict_proba(the_new_vecs) K.clear_session() I put K.clear_session() because I predict in a for loop and sometimes the next item of the for loop's prediction gets mixed up with the last one and raises tensorflow errors. But clearly K.clear_session() clears the session and makes it easy for the new item's prediction to work fine. The problem is in my views.py I have two functions which trigger prediction. And sometimes I need to use both simultanously. But since the probject is using Tensorflow Backend, only one session … -
I requested axios post form-data, but I got a 400 bad request response
I want to request to django by nuxt. I requested axios post form-data, and recieved 400 bad request response. I tried changing headers methods: { async submitPost() { this.post.userId = "1"; this.post.date = "123"; this.post.category = "1" const config = { headers: { "Content-Type": "multipart/form-data" } }; const formData = new FormData(); for (let data in this.post) { formData.append(data, this.post[data]); } try { for (var key of formData.entries()) { console.log(key[0] + ", " + key[1]); } let response = await this.$axios.$post("/posts/", formData, config); this.$router.push("/"); } catch (e) { console.log(e.response); } this.dialog = false; } } -
How to do PUT request without primary key?
I'm creating a Like/Dislike api for a blog using DRF. I have Like table which contains "Post", "User" and "isLike" fields. Since Django can't have composite key, I'm using unique_together constraint for ("Post" and "User"). If a user likes a post, I create a entry in Like table. Now if a user wants to remove his like from the post or want to dislike the post, I need primary key of entry from Like table for these (PUT/DELETE) methods. Since I know "User" and "Post", and since both are unique, Can I perform (PUT/DELETE) methods with unique fields? Model class class LikeDislike(models.Model): """model for like counts""" post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) isLike = models.BooleanField() class Meta: unique_together = (("post", "user"),) View for creating entry in Like table: class LikeDislikeCreateView(generics.CreateAPIView): queryset = models.LikeDislike.objects.all() serializer_class = serializers.LikeDislikeSerializer def perform_create(self, LikeDislikeSerializer): LikeDislikeSerializer.save(user=self.request.user) I can update a like/dislike using -> /like/primary-key/ but I want to do using "post" and "user" details. -
How to display a multi layer JSON in Django template?
So I have this JSON response: { "orders": [ { "orderId": "4123456789", "dateTimeOrderPlaced": "2017-02-09T12:39:48+01:00", "orderItems": [ { "orderItemId": "2012345678", "ean": "0000007740404", "cancelRequest": false, "quantity": 10 } ] } ] } I passed it in my view with the .json() method. I use this in my template: {% for key, value in orders.items %} {{ key }}: {{ value }} {% endfor %} I get this in my HTML: orders: [{'orderId': '2529081520', 'dateTimeOrderPlaced': '2019-09-07T00:12:16+02:00', 'orderItems': [{'orderItemId': '2298728074', 'ean': '8945005881389', 'cancelRequest': False, 'quantity': 1}]}] But how to dissect it further? For example to get the OrderId or the ean? -
How do I send cookies stored in variable in views to front-end of user display?
I stored recently viewed deals/items in cookies using javascript in ###array format. Then I created a view to get the cookies values stored ###and push them to frontend of user so he can watch the recently viewed ###items. I tried playing with the named variables in js code and also tried ###changing the name of the variables to same but I'm getting errors Views.py def view_deal(request, id): try: deals = Deal.objects.get(id=id) category = ProductGroup.objects.get(id=deals.product_group_id) similar = Deal.objects.filter(product_group_id=deals.product_group_id).exclude(id=id) recent = request.COOKIES["recentlyview"] recentDeals = Deal.objects.filter(['recent']) print(recentDeals) except Deal.DoesNotExist: deals = None try: comment = Comment.objects.filter(deal_id=deals).order_by('-created_on') except Comment.DoesNotExist: comment = None return render(request, 'frontend/view-deals.html',{'comment':comment, 'deal':deals,'similar': similar, 'recentDeals':recentDeals}) -
Use email as authentication field and add email verification on django custom user model
I have this custom user model on my Django project. I want to make the email as authentication field instead of the username. Also, I want to perform an email verification. models.py class es_user(models.Model): user = models.OneToOneField(User,related_name='es_user', on_delete=models.CASCADE), is_activated = models.BooleanField(default=False) def get_absolute_url(self): return reverse('user_detail', kwargs={'id': self.pk }) view.py def signup(request): signup_form_instance = SignUpForm() if request.method == "POST": signup_form_instance = SignUpForm(request.POST) if signup_form_instance.is_valid(): signup_form_instance2 = signup_form_instance.save(commit = False) username = signup_form_instance2.username password = signup_form_instance2.password signup_form_instance2.password = make_password(signup_form_instance.cleaned_data['password']) signup_form_instance2.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request,user) active_user = request.user es_user_instance = es_user.objects.create(user= active_user) # return index(request) return redirect('index') # return user_detail(request)#successful signup redirect or return # return redirect('user_detail',id = [str(request.user.id) ])#kwargs={'id': request.user.id }) else: print("SIGN UP FORM INVALID") return render(request,'signup.html',{'signup_form':signup_form_instance}) forms.py class SignUpForm(forms.ModelForm): class Meta: model = User fields = ('username', 'email', 'password') # for adding bootstrap classes & placeholders widgets = { 'username': TextInput(attrs={ 'class':'form-control', 'placeholder': 'Username *'}), 'email': EmailInput(attrs={ 'class':'form-control', 'placeholder': 'Your Email *'}), 'password': PasswordInput(attrs={ 'class':'form-control', 'placeholder': 'Your Password *'}), } help_texts = { 'username': None, } # to remove labels in form labels = { 'username': (''), 'email':(''), 'password':(''), } My project is near completion so I cannot change my user model … -
Error:variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.?
i've deployed login related project in server its not working properly and error showing variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.in console -
How to download CSV file in Django?
I created a small Django project for amazon products scraping. But don't know how to download the CSV file. I am a beginner in this so I don't know how to give a download link, so I haven't tried anything from django.http import HttpResponse from django.shortcuts import render import requests from bs4 import BeautifulSoup import csv import re def index(request): url = request.POST.get('url', '') r = requests.get(url) soup = BeautifulSoup(r.content, features="lxml") p_name = soup.find_all("h2",attrs={"class": "a-size-mini"}) p_price = soup.find_all("span",attrs={"class": "a-price-whole"}) with open('product_file.csv', mode='w') as product_file: product_writer = csv.writer(product_file) for name,price in zip(p_name,p_price): product_writer.writerow([name.text, price.text]) return render(request, 'index.html') -
Django Wagtail sitemap
I have an existing Django site for which i've added Wagtail. I would like to have a sitemap for both Django and Wagtail urls. My current sitemap.py: class StaticSitemap(sitemaps.Sitemap): priority = 0.5 changefreq = "weekly" protocol = "https" def items(self): return ["public:index", "other pages etc..."] def location(self, item): return reverse(item) My current urls.py: sitemaps = {"static": StaticSitemap} path( "sitemap.xml", sitemap, {"sitemaps": sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), The above works correctly for a standard Django sitemap. How do I include Wagtail urls? -
How to rename a model field from default Django model?
I would like to rename all the Groups field in Django admin as Roles field. But there are still some parts that didn't changed. I have successfully renamed Groups into Roles but then a field in the Users still has the name 'Groups' in it. I know it has something to do with the PermissionsMixin in django.contrib.auth.models which contains the ManyToManyField named groups that is being called in the UserAdmin. I would like to know how to rename this model field. This is the field that I want to rename. -
Access specific post data using request.data Django Rest framework
I am trying to get specific data from my post request. My code is: @api_view(['POST']) def create_user(request): if request.method == 'POST': first_name = request.data['first_name'] last_name = request.data['last_name'] This does not give me the information with the keywords. I have tried request.data.get(), request.POST[], request.POST.get(),... but none of these work. Thanks in advance -
Unable to locate sass file
I have a sass file in my django project the path inside my project is the following: Project\Project\static\style\file.scss but when i run the command python manage.py runserver i get the following error message: "Unable to locate file Login.scss while rendering tag 'sass_src' in template None" but when i create the sass file inside the following path "D:\Python\Lib\site-packages\django\contrib\admin\static " my webpage can identify my sass file and work normally. how can i do to make my webpage identify the sass file that is located in a folder inside the project like the following: "Project\Project\static\style\" ---------------- html ------------------------------ {% load sass_tags %} import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sass_processor', ] 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', ] ROOT_URLCONF = 'CvProject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'CvProject.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',}, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',}, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',}, {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',}, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' … -
Django-rest-framework API test 403 {'detail': 'You do not have permission to perform this action.'}
I'm currently writing a test to test my get request, the get request require jwt access_token in the header which i'm using django-rest-framework-simplejwt to get the token as well as using it as default authentication class settings.py: REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAdminUser', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), # 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',) } My test_api.py: from rest_framework.test import APITestCase from rest_framework import status from rest_framework.test import APIClient from django.urls import reverse from listing.models import Property from backend.models import User class PropertyTestCase(APITestCase): def setUp(self): property_1 = Property.objects.create(title="test", size=322.00, price=8000000, price_rent=300000, price_per_square_meter=500000, price_rent_per_square_meter=20000, description="description 1", type="sell", category="category 1", address="address 1", lat=21.027763, long=105.834160, images=["https://avatars2.githubusercontent.com/u/46511495?s=88&v=4"], contact_name="name 1", contact_address="test address 1", contact_phone="0923512213", contact_email="test@gmail.com", frontend=322, road=32, floor=4, bedroom=5, living_room=6, toilet=2, direction="Nam", balcony="Nam", meta_data={"menu": {"id": "file", "popup": {"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}]}, "value": "File"}}) property_1.save() property_2 = Property.objects.create(title="test2", size=322.00, price=8000000, price_rent=300000, price_per_square_meter=500000, price_rent_per_square_meter=20000, description="description 2", type="rent", category="category 2", address="address 2", lat=21.027763, long=105.834160, images=["https://avatars2.githubusercontent.com/u/46511495?s=88&v=4"], contact_name="name 2", contact_address="test address 2", contact_phone="0923512213", contact_email="test2@gmail.com", frontend=322, road=32, floor=4, bedroom=5, living_room=6, toilet=2, direction="Nam", balcony="Nam", meta_data={"menu": {"id": "file", "popup": {"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}]}, "value": … -
Django: How can I use templating to add a header to each HTML page, and only update one central file?
I have about 12 different HTML pages in my Django application. I am looking for a way to make my header in 1 template file, and then add that file to each HTML template that I need a header on. I tried following the template documentation from Django, but it wasn't concise enough for me. Would anyone be able to please break it down a little further for me? I am basically starting at square 1 with this... I was at a point where I was able to get a header to load, but no css was attached to it. I have since erased the code because I didn't want to screw anything up. -
Django2.1 : Queryset ModelChoice in a ModelForm then save two forms
I want the current logged in user to be able to create and save both forms. The second form has a ManyToManyField and ForeignKey relationships as you can see below. Currently I have tried to queryset the current user from ChatGroupUser ModelForm. With the current codes, as soon as I try to access the page, Django raise the error below: __init__() missing 1 required positional argument: 'user' it says that the error comes from line 88, which is: form_user = ChatGroupUserForm() Full Traceback Traceback (most recent call last): File "/Users/macadmin/Documents/Django_fun4/Groupixx/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/macadmin/Documents/Django_fun4/Groupixx/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/macadmin/Documents/Django_fun4/Groupixx/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/macadmin/Documents/Django_fun4/Groupixx/groupixx/core/views.py", line 88, in create_group form_user = ChatGroupUserForm() TypeError: __init__() missing 1 required positional argument: 'user' models.py class ChatGroup(models.Model): name = models.CharField(max_length=100, blank=True, null=True) group_admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name='chat_group_admins') is_active = models.BooleanField(default=True, null=True) is_current = models.BooleanField(default=False, null=True) class ChatGroupUser(models.Model): user = models.ManyToManyField(User) chat_group = models.ForeignKey(ChatGroup, on_delete=models.CASCADE, related_name='chat_group_users') forms.py class ChatGroupForm(forms.ModelForm): class Meta: model = ChatGroup fields = ['name',] class ChatGroupUserForm(forms.ModelForm): #user = forms.ModelMultipleChoiceField(queryset=User.objects.all()) class Meta: model = ChatGroupUser fields = ['user'] def __init__(self, user, *args, **kwargs): super(ChatGroupUserForm, self).__init__(*args, **kwargs) self.fields['user'].queryset = … -
How can I filter django queryset again to get unique parameters?
Hi I am trying to receive one last message per user. I have filtered out messages but I am getting many messages for one user. How can I get last message of user. queryset=MessageModel.objects.filter( Q(sUser=self.request.user) | Q(rUser=self.request.user) ).order_by('-id') return queryset I am getting this list from filtering. { "message": "Hi b do you want to buy? 2", "sUser": 1, "rUser": 15, "sent": true, "pk": 8, "user": { "pk": 15 } }, { "message": "a to c", "sUser": 1, "rUser": 16, "sent": true, "pk": 7, "user": { "pk": 16 } }, { "message": "No thanks not buying this time", "sUser": 15, "rUser": 1, "sent": false, "pk": 6, "user": { "pk": 15 } }, { "message": "c to a", "sUser": 16, "rUser": 1, "sent": false, "pk": 4, "user": { "pk": 16 } }, { "message": "Hi b do you want to buy?", "sUser": 1, "rUser": 15, "sent": true, "pk": 1, "user": { "pk": 15 } } ] I want to get message with pk 8 and 7 only because its last message to user 15 and 16 but I am getting all messages. -
Nesting fields in serialization use custom fields with Django REST framework
I'm trying to serialize foreikey to another name. For example: class User(models.Model): user_name = models.CharField(..) class Blog(models.Model): user = models.ForeignKey(User, ...) title = models.CharField(...) class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog fields = '__all__' when use BlogSerializer(blog_instance).data can get the data: { "id": 1, "user": 1, "user_info": {"id": 1, "user_name": "admin"}, "title": "hello world" }