Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django custom authentication backend with email
I am trying to make a custom authentication back end to help log in users with email but its not working and i have no errors to debug that help me plzzzzz setting.py : AUTHENTICATION_BACKENDS=( 'django.contrib.auth.backends.ModelBackend', 'accounts.authentication.EmailAuthenticationBackend' ) my authentication: from django.contrib.auth.models import User class EmailAuthenticationBackend(object): def authenticate(self, username=None, password=None): print (username) try: user=User.objects.get(email=username) if user.check_password(password): return user return None except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None -
SENDGRID w/ DJANGO REST FRAMEWORK: Customizing dynamic template
I'm trying to send a transaction email from Django using the Python Sendgrid library. I'm trying to figure out how to pass through a custom ID so that I can customize the URL of a button in my email (a password reset button). I'm not sure where I should be passing it in on the server side ("dynamic_template_data" on a personalization?) or how I should be accessing it from within the dynamic template editor (I've tried setting the button url to a bunch of things like .../setPassword/?token={{reset_url}} --- not sure what the syntax is supposed to be here). Please help! -
Django taggit tags disappear after submit. Form not initialize properly with users data
I have a "tag" form in which the user can input any tags and the result are based on the tags provided. For this I'm using django taggit with taggit_selectize. So on the screen it looks like this: The problem is that the return result delete the tags so the user can't see what was input before. My goal - is to have the user's input remain on the field tags after the submit. My Form: from django import forms from .models import Post from taggit_selectize.managers import TagSelectize class BulletTagSearchForm(forms.ModelForm): class Meta: model = Post fields = ['tags'] widgets = { 'tags': TagSelectize(attrs={'placeholder': 'input tags here to filter result','style':'width:45%',}), } and my view: def tag_search_view(request): if request.method == 'POST': form = BulletTagSearchForm(request.POST) user_tags = form.data['tags'] print ("ok search with those tags: ", user_tags) #works correctly #here I couldn't figure it out tag_search_form = BulletTagSearchForm() #tag_search_form.tags = user_tags ?????????? #tag_search_form["tags"].widgit = "TV" ?? manually trying #get data base on tags (to be completed) posts = Post.objects.filter(status_2=Post.BULLET_LIVE_CODE).order_by('-id') return render(request, 'bullets/archive_list.html' , {'posts':posts, 'tag_search_form':tag_search_form}) tag_search_form = BulletTagSearchForm() posts = Post.objects.filter(status_2=Post.BULLET_LIVE_CODE).order_by('-id') return render(request, 'bullets/archive_list.html' , {'posts':posts, 'tag_search_form':tag_search_form}) result post submit: -
How to grant cv2.VideoWriter permission python
I have an django. I create a video with a list of images by using cv2.VideoWriter. In local with this code : video_name = os.path.join(tmpdir, 'video_test_stream.mp4') video = cv2.VideoWriter(video_name, -1, 1, (640, 480)) the video file is created and everything works. But when I push on my ubuntu server, the video file is not created and my app crash. I think I don't have the good permission on the server but I don't how to add grant and for which user -
Django Tempting Date Format
I trying to record some time and dates in a MongoDB database. But I can't get them to display right. In the database it says ISODate("2018-11-05T20:57:53.233Z") but then when I try and display the date it displays as {'$date': 1541451473242}. If I use value|date:"m d Y" it will not show at all. I will post my model code below. Model.py class Promotion_Code_Info(EmbeddedDocument): promo_code = StringField(max_length=200, required=True) code_active = BooleanField(default = True) use_number = IntField(required=True) sent_when = DateTimeField(required=False) customer_email = EmailField(required=False) code_added = DateTimeField(default=datetime.datetime.utcnow) code_exp = DateTimeField(default=datetime.datetime.utcnow) class Promotion_Lists(Document): user_id = IntField(required=True) unique_promo_id = StringField(max_length=16, required=True) promo_name = StringField(max_length=200, required=True) code_list = ListField(EmbeddedDocumentField(Promotion_Code_Info)) amount_active = IntField(required=True) amount_used = IntField(required=True) total = IntField(required=True) -
How to save Django model instances with circular dependency?
models.py: class Server(models.Model): name = models.CharField(max_length=100, unique=True) last_interaction = models.OneToOneField('Interaction', on_delete=models.CASCADE, related_name='server') class Interaction(models.Model): client = models.CharField(max_length=100) time = models.DateTimeField() server = models.ForeignKey(Server, on_delete=models.CASCADE, related_name="interactions") How do I save instances? (When I want to save one, the other isn't saved yet, so it can't be saved) Notes: I been there. The accepted answer doesn't provide a solution to the problem. Indeed at runtime there will be new servers and clients. I am open to new schema suggestions, but also want to find a solution to the original question. I know the on_delete=cascade in Server is dangerous. I plan to fix it once I solve this problem. -
Unable to verify Firebase token
I am making an app in flutter which uses Google sign-in. I also have a Django backend linked to the app and I want to verify the user in the Django backend. I found many solutions on the internet but none is working. Probably I am messing up somewhere. I tried using python-jose for verification and here is the code: from jose import jwt import urllib.request, json token = '<token recieved using await user.getIdToken in flutter>' target_audience = "<tried projectid/appid>" certificate_url = 'https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com' response = urllib.request.urlopen(certificate_url) certs = response.read() certs = json.loads(certs) print(certs) user = jwt.decode(token, certs, algorithms='RS256', audience=target_audience) I also tried oauth2client, the code is here: from oauth2client import crypt import urllib.request, json certificate_url = 'https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com' target_audience = 'tried projectid/appid' response = urllib.request.urlopen(certificate_url) certs = response.read() certs = json.loads(certs) print(certs) crypt.MAX_TOKEN_LIFETIME_SECS = 30 * 86400 idtoken = 'token received from await user.getIdToken()' crypt.verify_signed_jwt_with_certs(idtoken, certs, target_audience) I also tried firebase_admin for python: import firebase_admin from firebase_admin import credentials from firebase_admin import auth cred = credentials.Certificate('<firebase service accounts private key>') default_app = firebase_admin.initialize_app(cred) token = 'token from flutter' verifyied =auth.verify_id_token(id_token=token) Just to check whether the firebase_admin library itself is working or not, I passed the userid to server from the app … -
Sorting root nodes in django-mptt
My application needs to sort root nodes with keeping the same order of children. MyModel.objects.all().ordered_by('field') sorts all nodes so that won't work. Sorted MyModel.objects.root_nodes() queryset when rebuilt with mptt.managers.TreeManager.get_queryset_descendants() is being sorted again with tree_id so it's back to it's previous state. So far I've managed to sort it converting QuerySet into a list and appending a root node and it's descendants like that: root_nodes = sorted(Entry.objects.root_nodes(), ...) qs = [] for node in root_nodes: qs.append(node) qs.extend(node.get_descendants()) My question is if there is any better and non-intrusive way to rebuild TreeQuerySet using sorted root nodes? As rebuilding QuerySet with loops seems error-prone and not performance friendly. -
Django logging user activity
I would like to keep a log in my application for each database change event. Something like a timestamp + username + which model was changed, written to a log file (just log that a model instance was modified, not what that change was). A combination of signals and logging seems like a natural fit. So in the models' signals I would do: import logging ... logger = logging.getLogger(__name__) logger.info("Order {} deleted by {}".format(order.barcode, request.user.email)) The problem with this is that the info level of the log is full of POST and GET requests. The usual recommendation is if you don't want all those request logs in your log file to go to a higher level like Warning, but it doesn't make sense to label these events as warnings here. Another option is to use a filter to get rid of the GET/POST logs, as recommended here. But by default warning and error level log events also end up in the info log which is also not desired behaviour in this case, so those would have to be filtered out as well. This log file is really just meant to log a 'this user changed this model instance' event. Also … -
Django model query "matching query does not exist"
I'm getting a "matching query does not exist" on my django app and I'm stumped on where the issue is. I know that means that it can't find a match to my query, but as shown below I can manually run the query via sql on the table. I'm not sure where else to look. (I've only provided a snippet of my view.py and model.py files as the other functions in them aren't relevant). I'm running to queries and it fails on the first one. First query is results = RateskioskEmp.objects.get(BadgeBarcodeID=barcodeid) and the second query is context['result_obj'] = RateskioskMain.objects.get(EID=empid) If I provide a manual "empid" and skip the first RateskioskEmp query it works just fine and I get results from my RateskioskMain query. Error: Exception Type: DoesNotExist at /kiosk Exception Value: RateskioskEmp matching query does not exist. Views: from ratekiosk.models import RateskioskMain from ratekiosk.models import RateskioskEmp #this is the problem model def get_emp_by_barcode_db(barcodeid): results = RateskioskEmp.objects.get(BadgeBarcodeID=barcodeid) empid = results.EID return empid def kiosk_view(request): context = dict() if request.method == 'POST': bid = request.POST.get('barcodeid') empid = get_emp_by_barcode_db(barcodeid) try: context['result_obj'] = RateskioskMain.objects.get(EID=empid) except Exception: context['result_obj'] = None return render(request, 'ratekiosk/kiosk.html', context) Model: class RateskioskEmp(models.Model): EID = models.BigIntegerField(unique=True, default=0,) UserID = models.CharField(max_length=100, blank=True, … -
ajax pagination previous page
I'm trying to implement pagination with ajax. I django paginator for this. I've already done the page changing part. The only promblem I have: when I'm for example at page 6 and I click on some item, when I hit the back button I'm going back to the page 1, not 6. What solution would you suggest? Here is the code: function ajax_get_update() { $.ajax({ async: true, type: "GET", url: url, success: function(result){ var events = $("#events", result); var page = $("span.step-links", result); $('#events').html(events); $('.step-links').html(page); } }) } $(document).on('click', '#prev', function(e) { e.preventDefault(); url = ($(this)[0].href); ajax_get_update(); }); $(document).on('click', '#next', function(e) { e.preventDefault(); url = ($(this)[0].href); ajax_get_update(); }); my views.py def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) event_list = Event.objects.all().order_by('date_start') paginator = Paginator(event_list, 6) # Show 10 events per page page = 1 if self.request.is_ajax(): query = self.request.GET.get('page') if query is not None: page = query try: events = paginator.get_page(page) except (EmptyPage, InvalidPage): events = paginator.page(paginator.num_pages) context['events'] = events return context It always takes me back to my page = 1. Maybe I could have an ajax call with previous page number triggered by back button click? I've seen some solutions here, but they don't work for me for some reason, … -
Django Dependent Dropdown without using a DB
The below form would display a dropdown of countries (US, UK, AUS). from django import forms COUNTRY_CHOICES=[ ('US','USA'), ('UK', 'United Kingdom'), ('AUS', 'Australia'), ] class PersonForm(forms.Form): countryList = forms.CharField(widget=forms.Select(choices=EXP_CHOICES, attrs={'class': 'form-control'}), label = "Dataset :") How do we create a dependent dropdown for displaying the states without using a Database? -
Python Reading and saving contents of CSV file
I have an app in Django app where the user can upload a csv file that is full of codes, the script can find each code and save it to a MongoDB database. I have all the code working form reading the file to saving it to the database. Where I am running into issues is with the very first code. It seems to have some extra data attached to it. The codes in the csv file look like this 48AG-UKEZKW-KQHX4R 48LW-5TU5F9-ZK56LJ 48A5-ZE7Z6B-KV24JG When it is read in and printed out on a terminal it shows up like 48AG-UKEZKW-KQHX4R 48LW-5TU5F9-ZK56LJ 48A5-ZE7Z6B-KV24JG Also If I put a return at the top of the file. It looks like This 48AG-UKEZKW-KQHX4R 48LW-5TU5F9-ZK56LJ 48A5-ZE7Z6B-KV24JG When I save it to the database it looks like this { "_id" : ObjectId("5be08c822dba311f34228b58"), "unique_promo_id" : "K79FD232TWK0QVIE", "code_list" : [ { "promo_code" : "?48AG-UKEZKW-KQHX4R", "code_active" : true, "use_number" : 1, "code_added" : ISODate("2018-11-05T18:31:30.199Z"), "code_exp" : ISODate("2018-12-14T00:00:00Z") }, { "promo_code" : "48LW-5TU5F9-ZK56LJ", "code_active" : true, "use_number" : 1, "code_added" : ISODate("2018-11-05T18:31:30.199Z"), "code_exp" : ISODate("2018-12-14T00:00:00Z") }, { "promo_code" : "48A5-ZE7Z6B-KV24JG", "code_active" : true, "use_number" : 1, "code_added" : ISODate("2018-11-05T18:31:30.199Z"), "code_exp" : ISODate("2018-12-14T00:00:00Z") } ], "amount_active" : 3, "amount_used" : 0, … -
Reverse for 'order_detail' with keyword arguments '{'order_id': 'JUQEDJA6QQ'}' not found. 1 pattern(s) tried:
Can't understand the problem. Here is my models and urls file. models.py class Order(models.Model): order_id = models.CharField(max_length=120, blank=True) active = models.BooleanField(default=True) objects = OrderManager() def __str__(self): return self.order_id def get_absolute_url(self): return reverse('order_detail', kwargs={'order_id': self.order_id}) urls.py from django.urls import path from .views import (OrderListView, OrderDetailView) urlpatterns = [ path('order/list/', OrderListView.as_view(), name='order_list'), path('order/<int:order_id>/', OrderDetailView.as_view(), name='order_detail'), ] template.html {% for order in order_list %} <tr> <th scope="row">{{ forloop.counter }}</th> <td><a href="{{ order.get_absolute_url }}">{{ order.order_id }}</a></td> </tr> {% endfor %} Error NoReverseMatch at /order/list/ Reverse for 'order_detail' with keyword arguments '{'order_id': 'JUQEDJA6QQ'}' not found. 1 pattern(s) tried: ['order\/(?P[0-9]+)\/$'] -
Django contact form google recaptcha decorators
I stuck somewhere. I need a little help. I started learn django. I create reCaptcha decorators for users login and register. its working very good. but i cant use same reCaptcha decorators on my contact page? when press "send mail" button without click reCaptcha button, mail is still gone and continues to success page.... How can i fix this ? i use decorator this (sendmail) view page; view.py from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse from django.shortcuts import render, redirect from .forms import ContactForm from blog.recaptcha import check_recaptcha @check_recaptcha def emailView(request, check_recaptcha): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['hi@mydomain.net']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('sendemail:success') return render(request, "email.html", {'form': form}) def successView(request): return HttpResponse('Success! Thank you for your message.') recaptcha.py(decorators) from functools import wraps from django.conf import settings from django.contrib import messages import requests def check_recaptcha(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): request.recaptcha_is_valid = None if request.method == 'POST': recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() if result['success']: request.recaptcha_is_valid = True else: request.recaptcha_is_valid = False messages.error(request, … -
How can I pass url `kwarg` to HyperlinkedIdentityField in django rest framework?
My url_conf looks like follows, ...appointments/<slug:company>/ ^service_booking/(?P<pk>[^/.]+)/$ The company part is obtained in the serializer via context. I could have created a HyperlinkedIdentityField if the url only had pk kwarg as stated in the docs. But with added company field, I am not able to do that. Currently, I am using SerializerMethodField to handle this issue as follows: def get_url(self, obj): return self.context['request'].build_absolute_uri( reverse('appointment:service-booking', kwargs=dict(company=self.context['company'].id, pk=obj.pk) ) ) I believe HyperlinkedIdentityField won't have access to context before it is actually passed to the serializer. Any help is appreciated. Thanks. -
django-push-notification 401 unauthorised
I am trying to setup push notifications using the django-push-notifications, I have copied most of the code from the example. I have a button that calls the enablePushNotifications() function: export function enablePushNotifications() { console.log("enabling push notifications..."); if (!'serviceWorker' in navigator){ console.log("Push notifications not supported"); return; } navigator.serviceWorker.ready.then( (registration)=>{ registration.pushManager.subscribe({ userVisibleOnly: true }).then( (sub)=>{ console.log(sub); let endpointParts = sub.endpoint.split("/"); let registration_id = endpointParts[endpointParts.length - 1]; let data = { 'browser': loadVersionBrowser(navigator.userAgent).name.toUpperCase(), 'p256dh': btoa(String.fromCharCode.apply(null, new Uint8Array(sub.getKey('p256dh')))), 'auth': btoa(String.fromCharCode.apply(null, new Uint8Array(sub.getKey('auth')))), 'registration_id': registration_id, 'endpoint': sub.endpoint, }; request( "/api/subscribe", data ) } ).catch( (error)=>console.error(error) ) } ) } When I open the networking tab I don't see anything strange about the passed properties or headers. Specifically the browser value is correct. The implementation for the /api/subscribe URL is as follows: import push_notifications.models as pushmodels def registerPush(request): data = requestFormatting.get_data( request ) device = pushmodels.WebPushDevice( name=request.user.username, active=True, user=request.user, registration_id=data["registration_id"], p256dh=data["p256dh"], auth=data["auth"], browser=data["browser"] ) device.save() device.send_message("hello") Calling this function raises a PushError: Push failed: 401 Unauthorized. I have tested on both chrome and firefox, both give the same error. I specify my FCM_API_KEY in settings, nothing else. I do not currently use VAPID, though I plan to in the future. I have tried various variations of … -
Saving the data from Dict to database
I am facing an error while saving the DB from the views.py to MySQL database. Please help me where i am going wrong. awaiting your suggestions. The models.py has the database model and the data is coming from a consumer API call. models.py class asin_product(models.Model): asin = models.CharField(max_length=10, primary_key=True) brand = models.CharField(max_length=255, null=True) title = models.CharField(max_length=255, null=True) def __str__(self): return self.title Views.py def search_name(request): AsinIds = [ 'B00HHBR026', ] mws1 = mws.Products(access_key=settings.ACCESS_KEY, secret_key=settings.SECRET_KEY, account_id=settings.SELLER_ID, region='US', domain='', uri='', version='', auth_token=settings.AUTH_TOKEN) for AsinId in AsinIds[0:]: try: result = mws1.get_matching_product(settings.MARKETPLACE_ID, AsinId) except Exception: continue dictres = result.parsed try: asin_obj = asin_product.objects.get(asin = dictres["Product"]["Identifiers"]["MarketplaceASIN"]["ASIN"]["value"]) #print (asin) except Exception: continue try: asin_obj = asin_product.objects.get(brand = dictres["Product"]["AttributeSets"]["ItemAttributes"]["Brand"]["value"]) #print (brand) except Exception: continue try: asin_obj = asin_product.objects.get(title =dictres["Product"]["AttributeSets"]["ItemAttributes"]["Title"]["value"]) #print (producttitle) except Exception: continue asin_obj.save() return HttpResponse(str(asin_obj), 'index.html',content_type="text/plain") -
Button event in html wont work on second time
Analyze Log button in the html code is not working when I click for second time below is my html code, it is working only for first time click <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Web Scraper</title> <link rel="stylesheet" type="text/css" href="{% static 'indexstyle.css' %}"> </head> <body> <h1>Log Analyzer Home</h1> <form action="#" method="get"> <button name="AnalyzeLogbutton" type="submit" value="Analyze Log">Analyze Log</button> </form> </body> </html> -
Django "python manage.py runserver" creates an additional python.exe process that cannot be killed and hangs ONLY when using CYGWIN
I'm using Windows 7. Everything works perfectly fine when using Command prompt or Powershell it is just with CYGWIN. When I use Cygwin and start the development server it hangs. It's suppose to return the follow: Performing system checks... System check identified no issues (0 silenced). November 03, 2018 - 15:50:53 Django version 2.1, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. In the task manager there is an extra python.exe process created. CTRL+C does not kill the process and the development service just hangs. The extra python.exe process in question is in the same Scripts/ folder as the django project. The only simliar question I found: Two processes created when run django in background it is not a reload server. Again it only happens on CYGWIN. -
.pdf is damaged after it has been stored and downloaded
I have stored a .pdf in a models.FileField, and made it downloadable for the users. But when i download the file, it is damaged. Can anyone tell if I'm storing it correctly or point me in some direction? My setup is the following: models.py class Barcard(models.Model): name = models.CharField(max_length=30) drinks = models.ManyToManyField(Drink) barcardFile = models.FileField(blank=True, upload_to='barcard') mixingFile = models.FileField(blank=True, upload_to='mixing') def generateFiles(self): bashCommand = 'make -C tkweb/apps/drinks/drinkskort/' subprocess.call(bashCommand, shell=True) barFile = open('tkweb/apps/drinks/drinkskort/bar_drinks.pdf', encoding = "ISO-8859-1") mixFile = open('tkweb/apps/drinks/drinkskort/mixing_drinks.pdf', encoding = "ISO-8859-1") self.barcardFile.save(self.name+'_barcard',File(barFile)) self.mixingFile.save(self.name+'_mixing',File(mixFile)) view.py def barcardGen(request): if request.method =='POST': card = request.POST.get('barcard') card_obj = Barcard.objects.get(id=card) barcardName = card_obj.name card_obj.generateFiles() return HttpResponseRedirect('/drinks/download/'+card) else: return HttpResponseRedirect('/drinks/') def download(request, barcard_id): if request.method == 'GET': barcard = get_object_or_404(Barcard, pk=barcard_id) return render(request, 'drinks/download.html', {'barcard':barcard}) else: return HttpResponseRedirect('/drinks/') template/drinks/download.py {% extends "drinks/base.html" %} {% block fulltitle %}Drinks{% endblock %} {% block content %} <h1>{{ barcard.name }}</h1> <p> Download barkort her: <a href='{{barcard.barcardFile.url}}'>{{barcard.name}} barkort</a> </p> <p> Download blandekort her: <a href='{{barcard.mixingFile.url}}'>{{barcard.name}} blandeliste</a></p> {% endblock %} -
How should I use trigramSimilary with django to search within sentences
I want to implement text search on several fields of my database and I would like to combine the potentials of trigramSimilary with SearchVector. Someone has done something similar ? Thanks in advance for your ideas -
Django database query search
I am using Django (2.1, python 3.6) and I would like to alter my project files to search a database and have the results returned to and displayed in an HTML file. The search is simple, it should look at one field (that contains a single word) in a model. Based on its simplicity, this is not a complex lookup and I consider Q objects to be overkill. Thus far, I have yet to get a search that returns results. My general issue is that I am not entirely grasping the process and when I look online, either the documentation shows its examples in a shell, I find examples where there is some lacking information that the reader is assumed to know (e.g. the model, url, imported module, file name for inserted code), the example is out of date, or there is still something that I am overlooking. My understanding of the general process is below, but depending on how I do the view, I think the urls.py should be in there somewhere: form (base.html) -> view.py -> query (unknown file) -> results in template (search_results.html) There is certainly data in the database, but when I place a query term … -
most efficient way to calculate with query requests
I'm currently working on a Django app that calculates prices with hours input. I have two models : the first model calculates all the prices: class Vacation(models.Model): version = models.ForeignKey(Version) field_1 = XXX ... field_n = XXX def prices(self): calculation = .... return [price_1, ... , price_n] def margin(self): calculation = .... return [margin_1, ... , margin_n] And the second sums all the prices of the objects from Vacation(model) class Version(models.Model): field1 = XXX ... field_n= XXX def totals(self): prix_tot = sum(vacation.prices()[0] for vacation in Vacation.objects.filter(version_contrat=self)) marge_tot = sum(vacation.margin()[0] for vacation in Vacation.objects.filter(version_contrat=self)) return [prix_tot, marge_tot] So I found this ways of doing it but when I refresh the page it takes ages(about 25seconds vs 5 seconds without the query request) Is there any other way of doing this ?? I've looked at Django aggregations , I might be wrong but I wasn't under the impression that it helped in my situation. Anyone has any idea of how to make this process more efficient ?? Thanks a lot in advance -
How to mask table fields in Django Rest Serializer
class ChatSerializer(serializers.ModelSerializer): creator = UserSerializer() class Meta: model = Affairs fields = ('creator', 'message', 'date') How can I hide the model fields? I want to get the same result, but have other keys in JSON.