Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using DRF FlexFields on Extra Actions
I want to use flexfields on viewset extra action serializers.py class FarmSerializer(FlexFieldsModelSerializer): class Meta: model = Farm fields = [ 'id', ... 'varieties', 'conditions', 'created_at', 'updated_at', 'created_by' ] expandable_fields = { 'varieties': ('labels.serializers.VarietySerializer', {'many': True}), 'conditions': ('labels.serializers.ConditionSerializer', {'many': True}), } views.py class GrowerViewSet(BaseViewSet): ... serializer_class = GrowerSerializer @action(detail=True, methods=['GET']) def farms(self, request, pk=None): ... serializer = FarmSerializer(queryset, many=True) return Response(serializer.data) Then, when I request http://localhost:5000/api/labels/grower/3/farms/?expand=varieties,conditions flexfield expand params dont work: -
Django how do you loop using range through two lists simultaneiously
I'm working with Django and would like to iterate through two lists so that the're side by side: my views file: def displayDict(request): data = ["a", "b", "c"] data2 = ["x", "y", "z"] return render(request, 'chattr.html', {'range': range(0,len(data)-1),'dictItems': data, "otherDict" : "other_bot", "dictItems_bot": data2, "otherDict2": "bot" , "duo" : (data, data2)}) my template: {% for i in range %} <p> {{i}} <br> <b>{{otherDict}}:</b> {{dictItems.i}} <br> <b>{{otherDict2}}:</b> {{dictItems_bot.i}} <br> {% comment %} {{a|add:1}} {% endcomment %} </p> {% endfor %} I'd like a webpage that looks like: other_bot: 'a' dictItems_bot: 'x' other_bot: 'b' dictItems_bot: 'y' other_bot: 'c' dictItems_bot: 'z' Currently nothing renders except the bot names: other_bot: dictItems_bot: other_bot: dictItems_bot: I may also be able to do this inner loop using tuples, Django Template: looping through two lists. But this would be a lot more complex,... -
How can I define and refer to custom user groups in Django that I can sort against like user.is_superuser?
I’ver created some custom user groups in my Django app because I want to show them different admin fieldsets. I thought they would work similarly to user.is_superuser. But they don’t. I have this def in my ModelAdmin: def is_approver(user): return user.groups.filter(name='approver').exists() (I don’t know what that’s called, by the way. Do you just call it a “def”?) So this works: def get_fieldsets(self, request, obj=None): if request.user.is_superuser: return self.superuser_fieldset I get the expected fieldset. But this doesn’t work: def get_fieldsets(self, request, obj=None): if request.user.is_approver: return self.approver_fieldset However, this does work: def get_fieldsets(self, request, obj=None): if request.user.groups.filter(name='approvers').exists(): return self.approvers_fieldset So, I guess my basic question is: why don’t my defs work like I expect? (Python 3.9.7, Django 3.1) -
In Django, how do I define a string value for IntegerChoices enum?
I'm using Django 3.2 and Pythnon 3.9. In my model, I define an int enum. I woudl also like to define readable string values for it, so I tried class Transaction(models.Model): class TransactionTypes(models.IntegerChoices): BUY = 0 SELL = 1 labels = { BUY: 'Buy', SELL: 'Sell' } translation = {v: k for k, v in labels.items()} but this definition fails with the error TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict' How would I define strings for each value? I don't mind if hte strings are just the literal variable names (e.g. "BUY", "SELL") -
Django bulk update db table using model from html table
MODEL class BGD(models.Model): #need to update name # id=models.IntegerField(primary_key=True) Workgroup = models.CharField(max_length=50) Center = models.CharField(max_length=50, blank=True, null=True) Description = models.CharField(max_length=250) InsertDate = models.DateTimeField(default=datetime.now, blank=False) Is_Active = models.CharField(max_length=25, blank=True, null=True) # def __str__(self): # return "%s" % (self.id) class Meta: managed = False db_table="table" View def Control_Bidding_Groups (request): B_G_Results=BGM.objects.all() if request.method == 'POST': data = request.POST.dict() data.pop('csrfmiddlewaretoken', None) print('//////',data) for i in data.B_G_Results(): print('???',i) obj = Bidding_Group_Description.objects.get(id=i[0].split("_")[1]) print('55',obj) # Bidding_Group_Description.objects.filter(id=id).update(Is_Active) if not str(obj.Is_Active) == str(i[1]): #here check int or char datatype since 1 not equal "1" obj.Is_Active = i[1] print(obj.Is_Active) obj.save() return render(request, "Control_Bidding_Groups.html", { "B_G_Results": B_G_Results}) else: return render(request, "Control_Bidding_Groups.html", { "B_G_Results": B_G_Results}) #, "edit": edit HTML <section id="golf"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="mainbg padding-all-zero"> <div class="row panelBg"> <label class="parav" for="ddlSubmit"> <button class="btn btn-danger" value="Insert Records"> <span class="glyphicon glyphicon-upload" style="margin-right:5px;"></span>Submit</button> </label> <table class="table table-striped" width="100%"> <thead> <tr> <th>Workgroup</th> <th>Center</th> <th>Bidding Group Description</th> <th style="text-align:left;">Is Active</th> <th>Is Active</th> </tr> </thead> <tbody class="ui-sortable"> {% for d in B_G_Results%} <tr> <td>{{d.Workgroup}}</td> <td>{{d.Center}}</td> <td>{{d.Description}}</td> <td>{{d.Is_Active}}</td> <td><input type="text" value="{{d.Is_Active}}" name="d_{{d.id}}"> </td> </tr> {% endfor %} </tbody> </table> </div> </div> </form> </section> ERROR 'dict' object has no attribute 'B_G_Results' data {'17': '17', '18': '18', '19': '19', '74': '74', '75': '75', '76': '76', '77': … -
Printing the table with same foreign key as users id . Using django and mysql
I am trying to print all the lists in the list table for a logged-in user on my web app on the main page. I have assigned a foreign key in the list model. I am not familiar with the syntax but I do know I have to do something to match my foreign key with the user id and print all the stuff in the list model. for that I will run a for loop in my HTML, but the syntax to get objects from different table and match with the table im worming in, I m not familiar with it. my views.py look like this def addnew(request): if request.method == 'POST': form = Sublist(request.POST) if form.is_valid(): try: form.save() messages.success(request, ' Subscirption Saved') name = sublist.objects.get(name=name) return render (request, 'subscrap/main.html', {'sublist': name}) except: pass else: messages.success(request, 'Error') pass else: form = Sublist() return render(request, 'subscrap/addnew.html', {'form': form}) @login_required(login_url='login') @cache_control(no_cache=True, must_revalidate=True, no_store=True) def main(request): return render(request, 'subscrap/main.html') def mod(request): student = students.objects.all() return render(request, 'subscrap/mod.html' , {'students': student}) Add new is supposed to add new data to the list model. It works but there is one thing it doesn't know the id of the user and ask me when inputting … -
I am not able to create OneToOneField and ForeignKey field with User model?
I have these two model class TaskModel(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,primary_key=True) name=models.CharField(max_length=100) start=models.DateField() end=models.DateField() note=models.CharField(max_length=300) class ProfileModel(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) img=models.ImageField(upload_to='profileimg',blank=True) desc=models.TextField(max_length=500) occupation=models.CharField(max_length=100) martial=models.CharField(max_length=50) but when i run makemigrations command then it showing me this error:: eg:- app.TaskModel.users: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField. HINT: ForeignKey(unique=True) is usually better served by a OneToOneField. This is my problem, I made TaskModel as a ForeignKey but it working like OneToOne Filed. I am new in django please help me? -
PYODBC not looping through sql queries
I currently have a view function in Django that is needed to calculate 2% interest on accounts that are in debt of more than 200 and print that to an excel sheet However, I am running into a problem whereby my function is only displaying one record for each table it loops through The structure of the function is as follows: It loops through the database fetching a list of table names: def InterestCharge(request): # Getting list of DB Names cnxn = pyodbc.connect('DRIVER={SQL Server};' 'SERVER=;' 'PORT=;' 'UID=kyle_dev_ro;' 'PWD=;') databaseName = "SELECT name FROM sys.databases WHERE database_id > 4 AND name <> 'SageEvolution' AND name <> 'DEMO' AND name <> 'Stonearch' AND name <> 'Caro Brooke HOA' AND name <> 'Casper' AND name <> 'Copy of Dennehof' AND name <> 'Founders View' AND name <> 'Hadedas' " \ "AND name <> 'Hillside' AND name <> 'Hillside Estate HOA' AND name <> 'SageCommon' AND name <> 'Villa Grove' AND name <> 'Kyle' and name <> 'Prudential House' AND name <> 'The Pearls of Fourways' " cursor = cnxn.cursor(); cursor.execute(databaseName); XdatabaseNames = cursor.fetchall() cursor.close() dbNames = [] for row in XdatabaseNames: rdict = {} rdict["name"] = row[0] dbNames.append(rdict) Then from there, it creates … -
Django, Effective way to redirect URL
When a DOM change occurs, a Javascript function fires and redirect to the same website's page with certain parameters. From the performance point of view, is the below method right? const fire=(arg)=>{ location.href = '/admin/arg/'; } Or should I use the {% URL 'path' %} tag ? if so, how ? -
How do I pass an image from URL to a Django template?
I have the following view: import requests def home(request): r = requests.get("https://via.placeholder.com/150") # Use the headers (r.headers) for something here ... return render(request, 'index.html', {'image': r.content}) And then in template, I want to use the image in an <img> tag, like so: <img src="{{ image }}"> Unfortunately, the image is broken in the template. When printing r.content, I get the following: >>> r.content b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x96\x00\x00\x00\x96\x04\x03\x00\x00\x00\xce/l\xd1\x00\x00\x00\x1bPLTE\xcc\xcc\xcc\x96\x96\x96\xaa\xaa\xaa\xb7\xb7\xb7\xc5\xc5\xc5\xbe\xbe\xbe\xb1\xb1\xb1\xa3\xa3\xa3\x9c\x9c\x9c\x8b*p\xc6\x00\x00\x00\tpHYs\x00\x00\x0e\xc4\x00\x00\x0e\xc4\x01\x95+\x0e\x1b\x00\x00\x01\x00IDATh\x81\xed\xd21o\x830\x18\x84\xe1\x8b1&\xa3\t\xb4s\x93!3\xde:\xc2\xd0\x9d\xaa\x1d\x18\x89\x84P\xc6D\x91\x98QR\xa9\xfd\xd9\xfd\x0ci;\x9b\xb5\xf7\x8c\x87\xf4\x06\x1c\x03DDDDDDDDDD\xb4\x82I\xd3\x16\xc7\xdb\xdfd\xa7\xc9|\x15\xa1\xad-\xd4\xd0\xd7\xd1\xe3\xa1\xfcY\x94\x9d&\xd7\xe7\x81)\x97"\x91\xdfOZ\xd5\xc2\xe4:\x03\xa2\xd4N\xd3\x80}`\xeb\xc5!y\x97/-\xa3\x11\xb8\xaa\x13\xa0\xdf\xec4\xe5x\x0el\xa1\xc2\xea\xbcAU\xc6\xd2r\xae\x96E[?\xe9\x1c\xcd\x82V\xd7\xb4\x95/ \xd9\xe0\xde\xea\x9a\xce\xca\xa3\xe0\x96\x1c\xd18\xbf\x97\xc9\xee-\x99>\x16\xbd\x17\x10\xdb\xf9\xbc\xd6\x9f\xbf\xad\xd8.:/\x07s\x92\xff\xf1\t8\xbe\x16s\xcbO\x03v\xe1\xad\xf5\xe5P\xc8\xfd\xaa\xa135\xce-?\xb9\xfe!\xbc\x15\x9f\xe5\xce\xfb{\xafF\x7f\xbf|\xcbO\x0b\xee=\x11\x11\x11\x11\x11\x11\x11\x11\x11\xfd?\xdfY\xa5%Q\x8a\xf0\x7f\xae\x00\x00\x00\x00IEND\xaeB`\x82' What do I need to do to format the content to be usable in my template? Thanks for any help! Edit I know the URL can be used in the <img> tag directly. However, I need a specific header from the URL in my Python code, so this way, I can save one extra request. -
Django there is no unique constraint matching given keys for referenced table
I have 3 models: class Event_type(models.Model): """ Event_type is like a category model for patient, datebase relationship is one to many """ name = models.CharField(max_length=40,unique=True) class Meta: verbose_name = "event_type" verbose_name_plural = verbose_name def __str__(self): return self.name class Patient(models.Model): patient_id = models.AutoField(unique=True, primary_key=True) # patient identification patient_name = models.CharField(max_length=30,unique=True,verbose_name='patient_name') class Meta: verbose_name = 'Patient' verbose_name_plural = verbose_name ordering = ['-patient_id'] def __str__(self): return self.patient_name class Event(models.Model): event_id = models.AutoField(unique=True, primary_key=True) event_type = models.ForeignKey(Event_type, on_delete=models.CASCADE, blank=True, verbose_name='event type', to_field='name' ) event_value = models.PositiveIntegerField(default=0, verbose_name='even value', blank=True) event_unit = models.CharField(max_length=100, blank=True, verbose_name='event unit') event_time = models.DateTimeField(auto_now=False,verbose_name='event time') patient = models.ForeignKey(verbose_name='patient', to='Patient', to_field='patient_id', on_delete=models.CASCADE) class Meta: verbose_name = 'Event' verbose_name_plural = verbose_name ordering = ['-event_id'] def __str__(self): return self.event_type.name Event is the primary table,Event_type and Patient are both foreign tables of it. After I add: to_field='name' into class Event error comes: django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "patients_event_type" Any friend can help ? -
API returning an array inside of an object how to display contents- Django
So I am requesting spot price from cex API, it returns something like this {"data":[{"amount: "67000.0", "base": "BTC", "currency": "USD"}]} of course there is more than one returned so I want to loop over it. In my views.py I am passing it into my context 'price': price. Then inside of my .html file I have a list with a for loop for example: <ul> {% for x in price %} <li>{{ x }}</li> {% endfor %} </ul> Then when I open my .html page I get data But what I'd like to be able to do is make a table where I have three columns to show the amount, base and currency. I am unsure on how to extract this data individualy? -
Unable to install Django Version 1.11.22 with python 2.7 installed on windows 10
I have python 2.7 installed on my machine globally and the pip version is pip 20.3.4. I want to install Django version 1.11.22. When I am trying to do so with pip install Django==1.11.22, I am getting the error as mentioned in the picture. This is not just while installing Django, I am getting the same error while installing anything like pip install openpyxl. -
400 (Bad Request Vue Js, axios and Django rest framework for POST and PUT Method
My Get and Delete Request is working perfectly. But, getting 400 Bad request while POST or PUT method are calling. And for your kind information my Django rest framework is working fine in POST-MAN and in my local http://127.0.0.1:8000/doctor. And I am including my local machine picture too. This is working fine. In my Axios code: data(){ return{ doctors:[], modalTitle:"", DoctorName:"", DoctorId:0, DoctorNameFilter:"", DoctorIdFilter:"", doctorsWithoutFilter:[] } }, methods:{ refreshData(){ axios.get(variables.API_URL+"doctor/") .then((response)=>{ this.doctors=response.data; this.doctorsWithoutFilter=response.data; }); }, addClick(){ this.modalTitle="Add Doctor"; this.DoctorId=0; this.DoctorName=""; }, editClick(doc){ this.modalTitle="Edit Doctor"; this.DoctorId=doc.id; this.DoctorName=doc.name; }, createClick(){ axios.post(variables.API_URL+"doctor/",Qs.stringify({ data:this.DoctorName })) .then((response)=>{ this.refreshData(); alert(response.data); }); }, updateClick(){ axios.put(variables.API_URL+"doctor/"+this.DoctorId, Qs.stringify({ data:this.DoctorName })) .then((response)=>{ this.refreshData(); alert(response.data); }); }, deleteClick(id){ if(!confirm("Are you sure?")){ return; } axios.delete(variables.API_URL+"doctor/"+id) .then((response)=>{ this.refreshData(); alert(response.data); }); }, FilterFn(){ var DoctorIdFilter=this.DoctorIdFilter; var DoctorNameFilter=this.DoctorNameFilter; this.doctors=this.doctorsWithoutFilter.filter( function(el){ return el.DoctorId.toString().toLowerCase().includes( DoctorIdFilter.toString().trim().toLowerCase() )&& el.DoctorName.toString().toLowerCase().includes( DoctorNameFilter.toString().trim().toLowerCase() ) }); }, sortResult(prop,asc){ this.doctors=this.doctorsWithoutFilter.sort(function(a,b){ if(asc){ return (a[prop]>b[prop])?1:((a[prop]<b[prop])?-1:0); } else{ return (b[prop]>a[prop])?1:((b[prop]<a[prop])?-1:0); } }) } }, mounted:function(){ this.refreshData(); } } My Django settings.py: """ Django settings for DrAppointment project. Generated by 'django-admin startproject' using Django 3.2.8. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like … -
Django - Search field as form input from different table
I have a form which creates an object with the following two fields : These are created from my models.py as : class Propositions(models.Model): ClientName = models.CharField(max_length=50, null=False, blank=False) ClientSiret = models.CharField(max_length=14, null=False, blank=True) views.py : class PropositionsCreateView(LoginRequiredMixin, generic.CreateView): #LoginRequiredMixin template_name = 'propositions_/propositions-create.html' form_class = PropositionModelForm def form_valid(self, form): print(form.cleaned_data) form.instance.user = self.request.user return super().form_valid(form) def get_success_url(self): return reverse('propositions_:propositions-list') hmtl : I've another table which stores few millions companies and their respective ids: class Companies(models.Model): CompanyName = models.CharField(null=False, blank=True) OfficialID= models.CharField(null=False, blank=True) I'd like transform the "Client" input field as a "dropdown search input field" which filters results from the "Companies" table and also populates the id "N° Siret" once the name is found. What would be the most "djangoic" way of doing this ? -
Exclusion of admin.logenty from dumpdata
I am trying to dump my data using python manage.py dumpdata --exclude=admin.logentry but it still gets included in the final json. Any hint what am I doing wrong ? -
Processing Repeated Bootstrap Modals in Django
How do people process bootstrap modals in Django that need to be shown on multiple pages? Do you have a special class to handle a second form? Do you use Crispy Forms? For example, if I have a Contact Us modal that is launched from a navigation bar on all pages in the application, how would I appropriately process that modal information? I can't imagine copying and pasting the same modal form and view code all over. That's clearly not DRY. I would imagine that there would be a way to do this, since it's a common problem. -
Using Python's deepcopy for different django models
I have two different django models with many attributes which differ in only 1 or 2 attributes. Based on some conditions, I would want to read one row from one model of a table and write to the other table. As of now, I am reading a row into an object, doing a deepcopy and then changing the class name using python's __class__ so that data of other attributes is persisted and I can add details of other attributes. The reason for doing this is because there are so many attributes and manually trying to copy every attribute should be avoided if we can. An example code goes something like this. There is a Program model and a ProgramRepository model. The ProgramRepository model has an extra attribute owner program = get_object_or_404(Program,pk=id) new_program = copy.deepcopy(program) new_program.id = None new_program.__class__ = ProgramRepository new_program.owner = creator new_program.save() Will this cause any problems? Is there a better way to do this? -
DJANGO Boolean Field form not saving
I have a simple checklist that a driver in an imaginary scenario would have to tick off before starting his day. To accomplish this i have a model that has all the tick boxes: from django.db import models from accounts.models import User from Inventory.models import trucks class CheckList(models.Model): vehicle = models.ForeignKey(trucks, primary_key=True, on_delete=models.CASCADE) driver = models.ForeignKey(User, on_delete=models.CASCADE) breaks = models.BooleanField(null=False) wipers = models.BooleanField(null=False) cargo = models.BooleanField(null=False) # If the cargo checks false its not a fatal failure but should return a warning to the previous driver saying he didn't do his task successful and warning should be issued from the office tires = models.BooleanField(null=False) oil = models.BooleanField(null=False) gas = models.BooleanField(null=False) seatbelt = models.BooleanField(null=False) date_created = models.DateTimeField(auto_created=True) def __str__(self): return self.vehicle.nickname After the model i created this form: from django import forms from .models import CheckList class driver_form(forms.ModelForm): breaks = forms.BooleanField(widget=forms.CheckboxInput, required=False) wipers = forms.BooleanField(widget=forms.CheckboxInput, required=False) cargo = forms.BooleanField(widget=forms.CheckboxInput, required=False) tires = forms.BooleanField(widget=forms.CheckboxInput, required=False) oil = forms.BooleanField(widget=forms.CheckboxInput, required=False) gas = forms.BooleanField(widget=forms.CheckboxInput, required=False) seatbelt = forms.BooleanField(widget=forms.CheckboxInput, required=False) class Meta: model = CheckList fields = "__all__" exclude = ['driver', 'date_created', 'vehicle'] And finally i added this view: def driver_checkout(request, pk): items = trucks.objects.all() truck = trucks.objects.filter(pk=pk) form = driver_form() context = { 'items': … -
how to fix (Hidden field submitted_by) This field is required error in django
I am trying to hide the submitted by field in my forms.py because I don't want user to upload the assignment on the behalf of some other user. So what I am doing is I am hiding the field but before hiding I am setting the value of logged in user to that input text using javascript but I am getting this error. (Hidden field submitted_by) This field is required. forms.py class assignmentUploadForm(ModelForm): class Meta: model = Submissions fields = ('submitted_by', 'submitted_to', 'submission_title', 'submission_file', 'submission_status') widgets = { 'submitted_by': forms.TextInput(attrs={'class': 'form-control', 'type': 'hidden', 'id': 'user', 'value': ''}), 'submitted_to': forms.Select(attrs={'class': 'form-control'}), 'submission_title': forms.Select(attrs={'class': 'form-control'}), } template <form method="post" enctype="multipart/form-data" style="margin-left: 240px;"> {% csrf_token %} {{form.as_p}} <input type="submit"> var name = "{{user.username}}" document.getElementById('user').value = name; views.py class AddAssignmentView(CreateView): model = Submissions form_class = assignmentUploadForm template_name = 'project/assignment.html' -
Problem when I try to save data in my database Django
I tried to make a pure api Django and save some data in my database for practicing. But I have some problems when I try to save data. For example I tried this code for the post method def post(self, request, *args, **kwargs): form = UpdateModelForm(self.request.POST) if form.is_valid(): obj = form.save(commit=True) obj_data = obj.serialize() return self.render_to_response(obj_data, status=201) if form.errors: data = json.dumps(form.errors) return self.render_to_response(data, status=400) data = {"message": "Not Allowed"} return self.render_to_response(data, status=400) And here is my Form validation from django import forms from .models import Update as UpdateModel class UpdateModelForm(forms.ModelForm): class Meta: model = UpdateModel fields = [ 'user', 'content', 'image' ] And the model class UpdateQuerySet(models.QuerySet): #def serialize(self): # qs = self # return serialize('json', qs, fields=('user', 'content', 'image')) def serialize(self): list_values = list(self.values("user", "content", "image", "id")) return json.dumps(list_values) class UpdateManager(models.Manager): def get_queryset(self): return UpdateQuerySet(self.model, using=self._db) # Create your models here. class Update(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.TextField(blank=True, null=True) image = models.ImageField(upload_to=upload_update_image, blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now_add=True) objects = UpdateManager() def __str__self(self): return self.content or "" def serialize(self): try: image = self.image.url except: image = "" data = { "id": self.id, "user": self.user, "content": self.content, "image": image } data_json = json.dumps(data) return data_json … -
How can i send updated request from 1 api to another api
I'm calling update_profile api by which return Response(self.profile(request).data) is suppose tp give updated users profile. but the thing is it is not giving output in real time. If i change name it is not reflecting in single api hit. Changes being reflect in 2nd api hit. Because of same request is being passed to profile api. So How can i update request and then send it to self.profile Heres my code: @action(detail=False, methods=['get'], authentication_classes=(JWTAuthentication, SessionAuthentication)) def profile(self, request): user = self.get_user() if not user: raise AuthenticationFailed() return Response( {"status": 200, "message": "Success", "data": UserSerializer(user, context={"request": self.request}).data}, status=status.HTTP_200_OK) @action(detail=False, methods=['post'], authentication_classes=(JWTAuthentication, SessionAuthentication)) def update_profile(self, request): profile_serialize = ProfileSerializer(data=request.data) profile_serialize.is_valid(raise_exception=True) AppUser.objects.filter(pk=self.get_user().pk).update(**profile_serialize.data) return Response(self.profile(request).data) -
Django: When will `auto_now` field not be updated?
Suppose I have a Django app backed by Postgres, and in that app I have model called Contact with a DateTimeField called last_updated. Suppose last_updated has auto_now set to True. I know there are some circumstances in which last_updated will not get updated when a Contact record is updated: Contact.objects.filter(xxx).update(yyy) will not update last_updated unless last_updated is included in yyy Contact.objects.bulk_update(contacts_qs, [zzz]) will not update last_updated unless last_updated is in zzz Are there other ways to update modify Contact objects (barring accessing the DB directly) where last_updated won't be updated? -
Caught LDAPError while authenticating
After we upgraded the Python version from 3.6 to 3.9 and the Django version from 2.2.16 to 2.2.17, we are getting the below error while logging in to the application using Kerberos-AD authentication. Caught LDAPError while authenticating ****************: SERVER_DOWN({'result': -1, 'desc': "Can't contact LDAP server", 'errno': 107, 'ctrls': [], 'info': 'Transport endpoint is not connected'}) Python-ldap version > 3.3.1 django-auth-ldap version > 3.0.0 -
How to make dynamic source path of FileFieldPath in django?
Info: I am try to use FileFieldPath in django. I want to make FileFieldPath(path=dynamic). I want to make every user have there own Directory path for file selection. Is there a way to user define his path from django Admin? class SourcePath(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) source = models.CharField(max_length=255) class Articles(models.Model): post_by = models.ForeignKey(User, on_delete=models.CASCADE) file_path = models.FilePathField(path=SourcePath.source)