Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter model based on max date
I have a model Drugs with following entries : id location num date country 1 UC ABC 2021-03-26 ZAF 2 UC DEF 2021-03-26 ZAF # line to retrieve with filter 3 UC ABC 2021-09-06 ZAF # line to retrieve with filter I want to select record based on max date for a combinaison loc - num - date for example, in the test case above, I want to only return the laste 2 records as id 3 is more recent than id 1 -
Model form data not showing up in database. Form not saving data
The form I created is not inserting the data into my database table. As far as I can tell I've done everything correctly but it still refuses to save into the database. Instead it "post" in the console and clears the form fields without creating nothing in the database. None of the data that is being entered is being saved anywhere? This is extremely confusing considering that I've done everything correctly. ps. I've connected my database, ran migrations and created a superuser as well but still nothing. models.py from django.db import models Media_Choices = ( ("TV", "TV"), ("Radio", "Radio"), ("Youtube", "Youtube"), ("Podcast", "Podcast"), ) class Appear(models.Model): Show = models.CharField(max_length=100) Media = models.CharField(max_length=30, blank=True, null=True, choices=Media_Choices) Episode = models.IntegerField() Date = models.DateField(max_length=100) Time = models.TimeField(auto_now=False, auto_now_add=False) Producer = models.CharField(max_length=100) Producer_Email = models.EmailField(max_length=254) def __unicode__(self): return self.Show + ' ' + self.Producer_Email forms.py from django import forms from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Appear class AppsForm(ModelForm): class Meta: model = Appear fields = '__all__' views.py from django.shortcuts import redirect, render from django.http import HttpResponse from .forms import AppsForm from .models import Appear def AppS(request): if request == 'POST': form = AppsForm(request.POST) if form.is_valid(): Apps = form.save(Commit=False) Apps.save() … -
Rendering multiple views and documents based on user settings
I am currently creating a settings menu to figure out what "type" of trial balance a user would like to pull and whether they would want to preview it , print it to pdf or print it to excel My code looks like this... Views.py: def home(request): return render(request , 'main/home.html') def KyletrbSettings(request): if request.GET.get('Excel'): return redirect('main/pdf-trialbalance.html') if request.GET.get('PDF'): return redirect('main/pdf-trialbalance.html') if request.GET.get('Preview'): return redirect('main/Kyletrb.html') def Kyletrb(request): all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] AS genLedger'\ ' Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = genLedger.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType'\ ' WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122)' cursor = cnxn.cursor(); cursor.execute(all); xAll = cursor.fetchall() cursor.close() xAll_l = [] for row in xAll: rdict = {} rdict["Description"] = row[0] rdict["Account"] = row[1] rdict["Debit"] = row[2] rdict["Credit"] = row[3] xAll_l.append(rdict) creditTotal = ' Select ROUND(SUM(Credit) , 2) FROM [Kyle].[dbo].[PostGL] ' cursor = cnxn.cursor(); cursor.execute(creditTotal); xCreditTotal = cursor.fetchone() debitTotal = ' Select ROUND(SUM(Debit) , 2) FROM [Kyle].[dbo].[PostGL] ' cursor = cnxn.cursor(); cursor.execute(debitTotal); xDebitTotal = cursor.fetchone() return render(request , 'main/Kyletrb.html' , {"xAlls":xAll_l , 'xCreditTotal':xCreditTotal , 'xDebitTotal':xDebitTotal}) def printToPdf(request): response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' all … -
Django - how to match URL pattern regex with additional parameters?
I have the following endpoint at my urls.py url(r'^stream/(?P<pk>[0-9a-f-]+)$', App_Views.stream, name='stream'), That would mean that the endpoint would look like this on call: http://localhost/stream/5409caac-fc9c-42b8-90af-058eff65a156 Now I'm adding some extra parameters to the URL before calling it, so that it looks like this: http://localhost/stream/5409caac-fc9c-42b8-90af-058eff65a156?st=zD3H0cHJrbcUAHZPNbPGyg&e=1630915404 Now to my actual question, how does the regex at urls.py has to look like in order to accept the second URL example? Already dealing with this since 2 days and was not able to find a solution. Thanks in advance -
How to retrieve the .count in a django template through ManyToManyField
I have some models, which are connected via manytomany or foreignkey. I would like to get a .count value for tutor.students.lessons.type and display the number of lessons online or class based. I have tried to pass in tuttype= tutorObj.students.get(type="CLASS") through the views which does not get the required result and have been trying out {{tutorobj.students.type.ONLINE.get}} {{tutorobj.students.get(type=ONLINE)}} in the templates with no luck also models.py class Tutor(models.Model): name = models.CharField(max_length=200, null=True, blank=True) students = models.ManyToManyField('Student', blank=True) lessons = models.ManyToManyField('Lesson', blank=True) lesson_reviews = models.ManyToManyField('LessonNote', blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) def __str__(self): return self.name class Student(models.Model): GENDER_CHOICES = ( ('M', 'Male',), ('F', 'Female',) ) TYPE_CHOICES = ( ('CLASS', 'Class',), ('ONLINE', 'Online',) ) YEAR_CHOICES = ( ('K1', 'Kindergarten 1',), ('K2', 'Kindergarten 2',), ('K3', 'Kindergarten 3',), ('P1', 'Primary 1',), ('P2', 'Primary 2',), ('P3', 'Primary 3',), ('P4', 'Primary 4',), ('P5', 'Primary 5',), ('P6', 'Primary 6',), ('M1', 'Mathayom 1',), ('M2', 'Mathayom 2',), ('M3', 'Mathayom 3',), ('M4', 'Mathayom 4',), ('M5', 'Mathayom 5',), ('M6', 'Mathayom 6',), ('C', 'College',), ('U', 'University',), ('A', 'Adult',), ) taught_by = models.ForeignKey(Tutor, on_delete=models.SET_NULL, null=True, editable=False) name = models.CharField(max_length=200, null=True, blank=True) school_year = models.CharField(max_length=2, choices=YEAR_CHOICES, null=True, blank=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True, blank=True) type = models.CharField(max_length=7, choices=TYPE_CHOICES, null=True, blank=True) hours_weekly = … -
How to connect Google Sheets with PostgreSQL database in a server?
So I have a server with a Django backend using PostgreSQL, but now I need to connect the database to this Google sheet to add on to the current database. How do I do this? I did some research and installed the KIPbees addon in Google Sheets. However, I do not know what the hostname for the database should be. -
how does django class based view cycle go around?
got request a worker initialize a class based view instance returns a response and destroies the view instance or view instance is initialized when server starts up workers wait in queue to get response and returns a response from view instance view instance lives forever I suddenly came to realize that i've been using Django for several years and still don't know how it works so.. which one is it? Thanks -
Django - How to properly receive multi-image upload via POST?
I have this view.py and models.py files below that supposed to support uploading multiple images. I have tests that work and do generate images, but the images are attached to the POST request as a ByteIO format. I'd like this endpoint to receive a POST request from a React Native front-end containing an image and I don't know if it'll be in ByteIO format. I tried sending an image in byte format by doing with open('./media/test.png', 'rb') as f: image = f.read() But it turns the QueryDict that is request.data into an immutable dict for some reason. As you can see below that's an issue as I do change it. Is the way I've implemented it correct for receiving multiple image uploads from React Native? view.py class PostView(APIView): def post(self, request): post_body = request.data['body'] hash_tags_list = extract_hashtags(post_body) hash_tags = [HashTag.objects.get_or_create( hash_tag=ht)[0].hash_tag for ht in hash_tags_list] request.data['hash_tags'] = hash_tags serializer = PostSerializer(data=request.data) if serializer.is_valid(): try: post_obj = serializer.save() if 'images' in request.FILES.keys(): for img in request.FILES.getlist('images'): Photo.objects.create(post_id=post_obj, image=img) except django.db.utils.InternalError as e: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) models.py class Post(AbstractBaseModel): creator_id = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator_id") goal_id = models.ForeignKey(Goal, on_delete=models.CASCADE) body = models.CharField(max_length=511, validators=[MinLengthValidator(5)]) hash_tags = … -
How to upload image/media file from React to Django API?
I am able to save the data without the image field. I am new to react so don't know pretty much about this type of problems. What is the problem with the image field?? this isn't showing me any error just my image data is not saving. I am sharing all my code it will be really helpful if you guys help me out. #models.py class Test(models.Model): full_name = models.TextField(max_length=200, blank=True, null=True) image = models.ImageField(null=True, blank=True) address = models.TextField(max_length=200, blank=True, null=True) def __str__(self): return str(self.id) #views.py @api_view(['POST']) def add(request): data = request.data test = Test.objects.create( full_name = data['full_name'], address = data['address'], ) serializer = TestSerializer(test, many=False) return Response(serializer.data) #this is screen for react page import React from 'react'; class Test extends React.Component{ constructor(){ super(); this.state={ full_name:'', image: '', address:'' } this.changeHandler=this.changeHandler.bind(this); this.submitForm=this.submitForm.bind(this); } // Input Change Handler changeHandler(event){ this.setState({ [event.target.name]:event.target.value }); } // Submit Form submitForm(){ fetch('http://127.0.0.1:8000/api/orders/test',{ method:'POST', body:JSON.stringify(this.state), headers:{ 'Content-type': 'application/json; charset=UTF-8', }, }) .then(response=>response.json()) .then((data)=>console.log(data)); this.setState({ full_name:'', image: '', address:'' }); } render(){ return ( <table className="table table-bordered"> <tbody> <tr> <th>Full Name</th> <td> <input value={this.state.full_name} name="full_name" onChange={this.changeHandler} type="text" className="form-control" /> </td> </tr> <tr> <th>Voucher</th> <td> <input value={this.state.image} name="image" onChange={this.changeHandler} type="file" className="form-control" /> </td> </tr> <tr> <th>Address</th> <td> <input … -
why the user is not logged in after registration in django
views.py ( after registration it is not logged in , can anyone help me to solve why this is happening there after successfully creating user but not logged in by user. User creates table in data base successfully and register consider all the required added def login_view(request): if request.method == "POST": # Attempt to sign user in email = request.POST["email"] password = request.POST["password"] user = authenticate(request, username=email, password=password) # Check if authentication successful if user is not None: login(request, user) return redirect('home') else: return render(request, "login.html", { "message": "Invalid email or password." }) else: return render(request, "login.html") models.py ( consider all required install or added ) class User(AbstractUser): G = [ ('Female', 'Female'), ('Male', 'Male'), ('Others', 'Others'), ] address = models.TextField(max_length=50 ,default='' ,null=True,blank=True) phone = models.CharField(max_length=15 ) email = models.EmailField(max_length=100 ,default='') password = models.CharField(max_length=500) Gender = models.CharField(max_length=150,choices=G ,default='',null=True,blank=True) def __str__(self): return self.email def register(self): self.save() @staticmethod def get_customer_by_email(email): try: return User.objects.get(email=email) except: return False def isExists(self): if User.objects.filter(email = self.email): return True return False is_staff = models.BooleanField(('Staff status'),default=True,) is_active = models.BooleanField(('Active'),default=True,) login.html ( where user can logged but not working ) <div class="loginContainer"> {% if message %} <div><i>{{ message }}</i></div> {% endif %} <div class="login__form"> <h2>Login</h2> <form action="{% url 'login' … -
django.db.utils.ProgrammingError: relation "Industry" does not exist // LINE 1: SELECT "Industry"."id", "Industry"."Name" FROM "Industry" OR
enter image description here enter image description here django.db.utils.ProgrammingError: relation "Industry" does not exist LINE 1: SELECT "Industry"."id", "Industry"."Name" FROM "Industry" OR... -
How can I display data stored in a Django model using CSS styles?
I have a for loop to display an image, title and description from a Django model, and it works good. but I want the title and description to be displayed as overlay on the image. Is there any way to do that? This code displays the data: <div class="tz-gallery"> <div class="row"> {% for service in services %} <div class="col-sm-6 col-md-4"> <h6 class="text-center">{{service.title}}</h6> <a class="lightbox" href="{{service.image.url}}"> <img src="{{service.image.url}}" alt="Park"> </a> <p>{{service.content}}</p> </div> {% endfor %} </div> </div> And I want the service.title and service.image.url to be displayed with this css style while the for loop iterates .tz-gallery .lightbox:after { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; background-color: rgba(46, 132, 206, 0.7); content: ''; transition: 0.4s; } .tz-gallery .lightbox:hover:after, .tz-gallery .lightbox:hover:before { opacity: 1; } How could I do that? -
Django Models Design: Solo-Player OR Team with players in Game
I'm designing a Django based webinterface for a game which can be played eiter solo OR as a team. A game is based on points; First party to reach set number of points wins. For later statistics and displaying, points have a timestamp. My Problem: How can I have either two Players OR two Teams in one Game? My Models look like this at the moment: from django.db import models # Create your models here. class Player(models.Model): slug = models.SlugField(unique=True) # will be autogenerated when inserting new Instance name = models.CharField(max_length=100) wins = models.IntegerField() losses = models.IntegerField() picture = models.ImageField(upload_to='images/player_pics') # games_played = wins + losses def __str__(self): return self.name class Team(models.Model): slug = models.SlugField(unique=True) name = models.CharField(max_length=100) players = models.ManyToManyField(Player) wins = models.IntegerField() # from here on seems redundant to Player class losses = models.IntegerField() picture = models.ImageField(upload_to='images/team_pics') # games_played = wins + losses def __str__(self): return self.name class Point(models.Model): val = models.IntegerField() timestamp = models.DateTimeField() class Game(models.Model): slug = models.SlugField(unique=True) timestamp = models.DateTimeField() players = models.ManyToManyField(Player) # here should be either Team or Player points = models.ManyToManyField(Point) My Idea was to implement another class like GameParty which can be either a Player or a Team but the same … -
How to not trigger `m2m_changed` signal when updating many to many relationship in Django?
The Use Case In my case, I have two signals that are listening on two 2 m2m fields, each of those fields are in different models. The problem happens when one signal is triggered, it triggers the other signal and vice versa, which will result in a recursive loop which will never ends. I need a convenient way to run one signal without triggering the second signal. Understand More If you are curious to know how this case could happen: I have two models which I need to make them mutually synced; if I updated the m2m field in the one model, I need those changes to be reflected on another m2m field in another model and vice versa. -
Unable to restore DB after Database change to Postgres (Django)
I have migrated from SQLite to Postgres, but now I am unable to restore my data on Postgres, i am using Django db-backup package, it is giving me this error on dbrestore command Traceback (most recent call last): File "C:\Users\atifs\Documents\food_deliveryapp\fooddelivery\manage.py", line 22, in <module> main() File "C:\Users\atifs\Documents\food_deliveryapp\fooddelivery\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\dbbackup\management\commands\dbrestore.py", line 53, in handle self._restore_backup() File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\dbbackup\management\commands\dbrestore.py", line 94, in _restore_backup self.connector.restore_dump(input_file) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\dbbackup\db\base.py", line 92, in restore_dump result = self._restore_dump(dump) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\dbbackup\db\postgresql.py", line 56, in _restore_dump stdout, stderr = self.run_command(cmd, stdin=dump, env=self.restore_env) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\dbbackup\db\postgresql.py", line 21, in run_command return super(PgDumpConnector, self).run_command(*args, **kwargs) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\dbbackup\db\base.py", line 150, in run_command raise exceptions.CommandConnectorError( dbbackup.db.exceptions.CommandConnectorError: Error running: psql --host=localhost --port=5432 --username=postgres --no-password --set ON_ERROR_STOP=on --single-transaction postgres ERROR: syntax error at or near "AUTOINCREMENT" LINE 1: ...S "auth_group" ("id" integer NOT NULL PRIMARY KEY AUTOINCREM... -
AttributeError: 'function' object has no attribute 'as_view' | Django
Don't know why this error occur. ERROR Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Qasim Iftikhar\anaconda3\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Qasim Iftikhar\anaconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Qasim Iftikhar\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module … -
Jquery CurrentLink Detector with wildcard support for django?
I have a snippet which words good on html files, as it check filename and compare url to make menu active ! It also works on web framework like django, but the problem is that it doesnt support sub urls, Menu changes active, when i go to "example.com/profile" But it doesnt gets active when i go to "example.com/profile/another/123" How to make this snippet which can support wildcard urls' I need it to make active irrespective to what comes after the /profile CurrentLink = function(){ var _link = '.nk-menu-link, .menu-link, .nav-link', _currentURL = window.location.href, fileName = _currentURL.substring(0, (_currentURL.indexOf("#") == -1) ? _currentURL.length : _currentURL.indexOf("#")), fileName = fileName.substring(0, (fileName.indexOf("?") == -1) ? fileName.length : fileName.indexOf("?")); $(_link).each(function() { var self = $(this), _self_link = self.attr('href'); if (fileName.match(_self_link)) { self.closest("li").addClass('active current-page').parents().closest("li").addClass("active current-page"); self.closest("li").children('.nk-menu-sub').css('display','block'); self.parents().closest("li").children('.nk-menu-sub').css('display','block'); } else { self.closest("li").removeClass('active current-page').parents().closest("li:not(.current-page)").removeClass("active"); } }); }; This is the snippet ! Am asking this for django -
How to unpack OrderedDict in python?
serializers.py def create(self, validated_data): choice_validated_data = validated_data.pop('choices') print("jdsfd this from vdata sdjfdsjf", validated_data) question = Question.objects.create(**validated_data) for each in choice_validated_data: choice = Choice.objects.create(text=each, question=question) choice.save() return question Output i want... { "title": "Added from admin", "choices": [ { "id": 144, "text": "asdf1" }, { "id": 145, "text": "asdf2" } ] } Can anyone help me out to fix this issue, I am facing it from almost 5 days. Please can anyone fix the code. -
Duplicate key value violates unique constraint Dajngo python
My goal. If the id matches, you need to update the creation time column in the model. I can't figure out how I can solve this problem. It doesn't seem complicated, but I'm stuck. if a:=Defect.objects.get(id_leather=id_file_name) == True: a.update(created=datetime.datetime.now()) else: Defect.objects.create(id_leather=id_file_name, path=path_file_save) Models.py class Defect(models.Model): created = models.DateTimeField(auto_now_add=True) Error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "files_defect_id_leather_key" DETAIL: Key (id_leather)=(9998) already exists. -
Get distinct titles from product list with min and max price of that product title in django
I have list of products with same title but of different price. This is my Product model: class Product(BaseModel): title = models.ForeignKey( ProductTitle, on_delete=models.CASCADE, related_name="product_title", null=True, blank=True, ) quantity = models.PositiveIntegerField(default=1) price = models.FloatField(validators=[MinValueValidator(0.00)]) unit = models.CharField( max_length=20, blank=True, null=True, help_text="Standard measurement units.eg: kg, meter,etc..", ) description = models.TextField( blank=True, null=True, help_text="Short Info about Product" ) slug = models.SlugField(null=False, unique=True) Say, I have 10 products of same title but with different price, and same goes for other products as well. Now i want to get single(distinct) product of particular title with Min and Max price for that product and so on. So, i should get say Orange with min and max price, apple with min and max price and so on. I have tried some ways but its not working. Like in this query its giving me: product_qs = ( Product.objects.filter(is_deleted=False) .order_by("title__title") .distinct("title__title") ) p_list = product_qs.values_list("title", flat=True) product_list = product_qs.filter(title__in=p_list).annotate( max_price=Max("price"), min_price=Min("price") ) NotImplementedError at /api/product/unique_product/ annotate() + distinct(fields) is not implemented. Can somebody help me with this -
How to make certain field not visible in an api output using python and django?
i have parent (AccessInternalSerializer) and child serializer (AccessSerializer) classes like below, class AccessInternalSerializer(AccessBaseSerializer): private_key = serializers.FileField( allow_null= True, required=False) ca_cert=serializers.FileField( allow=True, required=False) def to_representation(self, obj): data = super().to_representation(obj) data['private_key'] = obj.private_key data['ca_cert'] = obj.ca_cert return data class Meta(AccessBaseSerializer.Meta): model=Access extra_kwargs = { 'auth_failure': { read-only: True } } class AccessSerializer(AccessInternalSerializer): private_key = serializers.FileField( write_only=True, allow_null=True, required=False) ca_cert=serializers.FileField( write_only=True, allow_null=True, required=False) class Meta(AccessInternalSerializer.Meta): extra_kwargs={ **AccessInternalsSerializer.Meta.extra_kwargs, 'private_key': { 'write_only':True, } 'ca_cert': { 'write_only': True, } } Now with above code for some reason private_key and ca_cert are shown in the output of api using AccessSerializer. with AccessInternalSerializer to_representation i make the private_key and ca_cert fields visible in api output that uses AccessInternalSerializer. however it behaves the same using AccessSerializer. i expect the api output to not return private_key and ca_cert fields using AccessSerializer. I am not sure where i am going wrong. i am new to python and django programming. i am stuck with this from long time. could someone help me with this. thanks. -
How to Fix django migrate issue?
I am try to run my django project before run I did makemigrations all my apps and then I run command migrate but I am getting this error I am not able to understand what exactly this error. Please help. -
Using CDN fro django-jet theme's Static Files
Can i move every Static file related to Django-jet (like static/admin/css/autocomplete.css) theme to CDN ? Is it required to keep the referenced libraries within code base ? -
Free SMTP for Django Projects
What is the best Free SMTP Service for website? Also what are the Django settings for the same. Currently, I am developing a Django project based on amounts due to pay in the organization. The person whose amount are due should get a proper email notification regarding the remaining amount to be paid. So I want to use a free SMTP service for the base usage. -
Sum multiple annotates in django orm
Here's my model: class Product: name = models.CharField(max_length=80) price = models.FloatField() category = models.CharField(max_length=40) class ProductInventory: inventory = models.IntegerField() product = models.OneToOneField(Product, on_delete=models.RESTRICT) and here's raw sql of what I want to achieve but how do I write this in django ORM? SELECT product.category, SUM(price) * SUM(product_inventory.inventory) FROM product LEFT JOIN product_inventory ON product.id=product_inventory.product_id group by product.category; Thank you.