Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
return id if get_or_created inserts data, django
maybe it's simple question to ask but couldn't figure out how. I am inserting data with get_or_created and if there is a insert then trying to return that row's ID. To achieve this I tried like it below. obj, created = Advertisements.objects.get_or_create(budgets_id=pid, ad_brand=ad_brand, ad_kind=ad_kind, saved_date=today) print(created.id) even if there is an insert. it returns an error. what is the right way to get an ID in this kind of situation. 'bool' object has no attribute 'id' -
How to print model fileds as json output
views.py def districts_list(request): obj_districts_list = Districts.objects.all() data = serializers.serialize( 'json', obj_districts_list, fields=('district_name')) return HttpResponse(data, content_type="application/json") models.py class Districts(models.Model): id = models.AutoField(primary_key=True) district_name = models.CharField(max_length=40) country = models.ForeignKey('Country', on_delete=models.CASCADE) state = models.ForeignKey('States', on_delete=models.CASCADE) def __str__(self): return '{}'.format(self.district_name) OUTPUT: Output is JSON format But i just want the fields inside the Accounts.districts as output in JSON format. Thank You in advance.. HAVE A NICE DAY.. -
Django: duplication check failed
I currently develop a Django project that is currently test by a colleague One of my edit form have a validation check on duplicate (cf def clean method in forms.py) that is the combo of 3 fields: asp_ent_loc / med_num / asp_ent_dat but even with this control on form validation, my colleague managed to registered 2 records with the same combo (PA / AAB / 2020-03-16) the problem is that I did not manage to reproduce this bug... models.py: class Entree(models.Model): asp_ent_cle = models.AutoField(primary_key=True) asp_ent_loc = models.CharField("Site concerned by the operation", max_length=10, null=True, blank=True) med_num = models.CharField("Trial batch number", max_length=3, null=True, blank=True,) asp_ent_dat = models.DateField("Entry date", null=True, blank=True) asp_ent_pro_pay = models.CharField("Country of treatment origin in case of entry", max_length=10, null=True, blank=True) asp_ent_pro_sit = models.CharField("Processing source site in case of entry", max_length=10, null=True, blank=True) opr_nom = models.CharField("Input operator", max_length=10, null=True, blank=True) opr_dat = models.DateField("Entry date", null=True, blank=True) log = HistoricalRecords() class Meta: db_table = 'pha_asp_ent' verbose_name_plural = 'Entries' ordering = ['asp_ent_cle'] permissions = [ ('can_manage_drugs','Can manage trial drugs'), ] forms.py class EditForm(forms.ModelForm): # surcharge méthode constructeur (__init__) pour avoir accès aux variables de sessions # https://stackoverflow.com/questions/3778148/django-form-validation-including-the-use-of-session-data def __init__(self, request, *args, **kwargs): super(EditForm, self).__init__(*args, **kwargs) self.request = request self.language = request.session.get('language') self.user … -
Django Dropdown & Field Representation
I've got the following Situation, I have a rather large legacy model (which works nonetheless well) and need one of its fields as a distinct dropdown for one of my forms: Legacy Table: class SummaryView(models.Model): ... Period = models.CharField(db_column='Period', max_length=10, blank=True, null=True) ... def __str__(self): return self.Period class Meta: managed = False # Created from a view. Don't remove. db_table = 'MC_AUT_SummaryView' Internal Model: class BillCycle(models.Model): ... Name = models.CharField(max_length=100, verbose_name='Name') Period = models.CharField(max_length=10, null=True, blank=True) Version = models.FloatField(verbose_name='Version', default=1.0) Type = models.CharField(max_length=100, verbose_name='Type', choices=billcycle_type_choices) Association = models.ForeignKey(BillCycleAssociation, on_delete=models.DO_NOTHING) ... def __str__(self): return self.Name Since I don't want to connect them via a Foreign Key (as the SummaryView is not managed by Django) I tried a solution which I already used quite a few times. In my forms I create a ModelChoiceField which points to my Legacy Model: class BillcycleModelForm(forms.ModelForm): period_tmp = forms.ModelChoiceField(queryset=SummaryView.objects.values_list('Period', flat=True).distinct(), required=False, label='Period') .... class Meta: model = BillCycle fields = ['Name', 'Type', 'Association', 'period_tmp'] And in my view I try to over-write the Period Field from my internal Model with users form input: def billcycle_create(request, template_name='XXX'): form = BillcycleModelForm(request.POST or None) data = request.POST.copy() username = request.user print("Data:") print(data) if form.is_valid(): initial_obj = form.save(commit=False) initial_obj.ModifiedBy = … -
Creating Django's blog post scheduler [closed]
so I am making a Django blog web app and I was just wondering if it is possible for one to schedule when the blog posts should be posted and if it's possible, how would I go about it? I have tried googling out the solution but the only answer I've gotten so far was one related to scheduling tasks periodically. Any solution would be greatly appreciated. -
DRF: how to call post method once the put method has been successfully implemented
I have two separate methods: to load and validate a csv file FileUploadView(APIView) [PUT] to add new objects to the database based on their uploaded file data CsvToDatabase [POST] For this purpose, 2 different url addresses are used Now I want to combine this functionality into one, so that the file is loaded with processing and creation of instances in the database is done on a single request. That is, the final goal - the application user sends the file to the server and then everything happens automatically. file upload class FileUploadView(APIView): parser_classes = (MultiPartParser, FormParser) # renderer_classes = [JSONRenderer] permission_classes = (permissions.AllowAny,) serializer_class = VendorsCsvSerializer def put(self, request, format=None): if 'file' not in request.data: raise ParseError("Empty content") f = request.data['file'] filename = f.name if filename.endswith('.csv'): file = default_storage.save(filename, f) r = csv_file_parser(file) status = 204 print(json.dumps(r)) else: status = 406 r = "File format error" return Response(r, status=status) create instances class CsvToDatabase(APIView): permission_classes = (permissions.AllowAny,) serializer_class = VendorsCsvSerializer def post(self, request, format=None): r_data = request.data ... #some logic ... serializer = VendorsCsvSerializer(data=data) try: serializer.is_valid(raise_exception=True) serializer.save() except ValidationError: return Response({"errors": (serializer.errors,)}, status=status.HTTP_400_BAD_REQUEST) else: return Response(request.data, status=status.HTTP_200_OK) how can I correctly combine two methods in one endpoint so that if csv … -
Direct assignment to the forward side of a many-to-many set is prohibited. Use interested_time.set() instead
I'm trying to implement multiple singup form with django all auth. It is working fine for the first form because first form doesn't contain any type of many to many relationship. In case of second form it contains lots of many to many realtion ship. I'm new to django and allauth, I didn't know how to handle this problem. some of the code snippets is given below. models.py class JobSeekerProfile(models.Model): user = models.OneToOneField(User, verbose_name=_("User"), on_delete=models.CASCADE) full_name = models.CharField(max_length=255) religion = models.ForeignKey(Religion, on_delete=models.CASCADE) interested_area = models.ManyToManyField(ServiceArea) interested_time = models.ManyToManyField(WorkingShift) forms.py class JobSeekerSignupForm(SignupForm): full_name = forms.CharField( .......... ) interested_area = forms.MultipleChoiceField( required=True, error_messages={'info': 'Interested Area is required'}, label="Interested Area", choices=[[0, '']] + [[r.id, r.title] for r in ServiceArea.objects.all()], widget=forms.SelectMultiple(attrs={ 'id': "inputGroup1_17", 'class': select_input_class, 'style': "width: 100%;", 'data-placeholder': "Interested Area ", 'data-open-icon': "fa fa-caret-down", 'data-close-icon': "fa fa-caret-up", }), ) ........ def save(self, request): user = super(JobSeekerSignupForm, self).save(request) user.is_job_seeker = True job_seeker = JobSeekerProfile( user=user, full_name=self.cleaned_data.get('full_name'), interested_area_set=self.cleaned_data.get('interested_area'), ........ interested_time=self.cleaned_data.get('interested_time'), ) user.save() job_seeker.save() return user and views.py class JobSeekSignupView(SignupView): template_name = 'user/job-seeker-signup.html' form_class = JobSeekerSignupForm redirect_field_name = 'next' view_name = 'jobseekersignup' success_url = None def get_context_data(self, **kwargs): ret = super(JobSeekSignupView, self).get_context_data(**kwargs) ret.update(self.kwargs) return ret -
Could not find the GDAL library (tried "gdal203", "gdal202", "gdal201", "gdal20", "gdal111"). Is GDAL installed?
i'm trying to make location based web application with django and sub framework (geodjango) and postgresql - postgis , windows 10 i've also installed GDAL through GDAL-2.4.1-cp37-cp37m-win_amd64.whl,geos, and added this line to settings.py file GDAL_DATA = 'C://<path_to_your>/venv/Lib/site-packages/osgeo/data/gdal' GDAL_LIB = 'C://<path_to_your>/venv/Lib/site-packages/osgeo' and database DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': '...', 'USER':'....', 'HOST':'localhost', 'PASSWORD':'....', 'PORT':'5432', } } but still getting this error django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal203", "gdal202", "gdal201", "gdal20", "gdal111"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. -
django rest framework copy password to extra fields in the user table
I have a project that needs to read the password for other connection operations. So I need to be able to read the plaintext password from the database. But the password in the database is encrypted with md5 and cannot be decrypted. So I want to save a copy of the password when I register as a user/super admin, not in plain text, but encrypted by a encryption and decryption algorithm, so I can decrypt it and get the password when I need it UserModel is as follows: class User(AbstractUser): jwt_secret = models.UUIDField(default=uuid.uuid4) test= models.CharField(max_length=200, null=False) def __str__(self): return self.username method one modify UserSerializer create function class UserSerializer(serializers.ModelSerializer): def create(self,validated_data): user = User.objects.create( username=validated_data['username'], test=encry(validated_data['password']) ) user.set_password(validated_data['password']) user.save() return user This can indeed be done when registering a user, when using http://hostname:port/docs/swagger/ test registration. But, when using the python3 manage.py createsuperuser command, the test field cannot be inserted, which is shown as empty. Method two So I tried using Manager Refer to the following Customizing authentication in Django¶ MyUserManager is as follows: class MyUserManager(UserManager): def create_user(self, username, email=None, password=None, **extra_fields): extra_fields.setdefault('test', encry(password)) return self._create_user(username, email, password, **extra_fields) def create_superuser(self, username, email, password, **extra_fields): extra_fields.setdefault('test', encry(password)) return self._create_user(username, email, password, **extra_fields) … -
Developing queryset using related models
I've got two models. Event and Usercart. class UserCart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) class Event(models.Model): order = models.ForeignKey(UserCart, on_delete=models.CASCADE, null=True, blank=True) start_time = models.DateTimeField() I'd like to develop a queryset of UserCart instances where there is a related event that is in the past (based on that event's start time) pastcarts = UserCart.objects.filter(????) Thanks for your help! -
Use seperate login with django jwt and vuejs
at the moment my django login view return a vuejs site with the login and the full app. The login form sends request with axios to my django obtain token url and check if the response is correct. Than my vue router let me into the app. I would like to seperate the login to my web app. For example this is the login scenario that i want: Django return a normal html page with a login form After submit the form, the django view looks if the data correct, generate the tokens and check if the user is an employee or an employer (this my two user types) If the user an employee return vuejs page 1 and if there an employer return vuejs page 2 And at this point i have a problem. I don't know how i can return and store the access and refresh jwt token with the vuejs page 1 or 2 in the same response. At the moment i store them in vuex. This is simple because the vuejs page make the login request to the server. But if the login not a part of the vuejs app it is tricky. My idea is … -
Query to get total in django
I need to find user_id with maximum fat_intake (overall fat_intake). Database: id | user_id | fat_intake 38 1 10 39 1 15 40 1 30 41 1 14 42 2 20 43 2 30 44 2 50 What will be the query to get user_id with the maximum fat intake ? The Response should be : Output: { "user_id": 1, "total_fat_count": 46 } -
Index defined on abstract class incorrectly included in migration on concrete child of concrete child
To illustrate the issue I'm facing I'll use the following example. Let's say I have the following model hierarchy in my application: class Key(models.Model): pass class AbstractThing(models.model): key = models.ForeignKey(Key) class Meta: abstract = True indexes = [ models.Index(fields=['key']) ] class Thing(AbstractThing): pass class ChildOfThing(Thing): pass Now, since I've defined an index on the abstract AbstractThing model, I would expect all inherited models' table to have the key index as well, but not if I inherit further from one of these, since they will not contain the column. When I create the migrations however, I can see that an index is added on the non-existent ChildOfThing.key column, which of course, does not exist. Since Thing is a concrete class, the key column is contained there. The migration file is generated as follows: class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Key', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200)), ], ), migrations.CreateModel( name='Thing', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='ChildOfThing', fields=[ ('thing_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='things.Thing')), ], options={ 'abstract': False, }, bases=('things.thing',), ), migrations.AddField( model_name='thing', name='key', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='things.Key'), ), migrations.AddIndex( model_name='thing', index=models.Index(fields=['key'], name='things_thin_key_id_acfd46_idx'), ), migrations.AddIndex( model_name='childofthing', … -
How to balance the investment testing in Django (TDD)
I understand all the advantages of writing tests for your code. But writing tests takes time and time is (client) money. I try to find a good 'return on investment' for writing tests. In other words a balance between: Testing everything. For example: in examples I see people testing that verbose_name equals plural. I think this is too much. If I've put the code in the Model Meta options, it is there to stay and I can't see why it would ever break. Testing only the URL's. Test all the URL's in the applications. For example: response = self.client.get('/example/create)) self.assertEqual(response.status_code, 200) I think that this way the common reasons of breaking code will be covered. But on the other hand I've the idea that this is too little. Does anyone have a 'best practice' that is balanced? Thanks in advance -
AttributeError: 'DeferredAttribute' object has no attribute 'copy'
I'm trying to create a widget that calls from my model, "DPRLog" but I'm having a hard time implementing it in my forms. Here is my forms.py: from django import forms from profiles.models import User from .models import DPRLog class DateInput (forms.DateInput): input_type = 'date' class Datefield (forms.Form): date_field=forms.DateField(widget=DateInput) class dprform(forms.Form): class Meta: model = DPRLog widgets = {'date_field':DateInput(DPRLog.reportDate)} fields = ('login','logout',) Model.py: class DPRLog(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) reportDate = models.DateField(blank=False,null=False) login = models.TimeField(blank=False, null= False) logout = models.TimeField(blank=False, null= False) def __str__(self): return f'{self.user.full_name} DPR Log' -
I want to convert text to speech in python
(base) C:\Users\LENOVO>pip install gTTS WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip. Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue. To avoid this problem you can invoke Python with '-m pip' instead of running pip directly. ERROR: Exception: Traceback (most recent call last): File "C:\Users\LENOVO\AppData\Roaming\Python\Python37\site-packages\pip_internal\cli\base_command.py", line 186, in _main status = self.run(options, args) File "C:\Users\LENOVO\AppData\Roaming\Python\Python37\site-packages\pip_internal\commands\install.py", line 258, in run isolated_mode=options.isolated_mode, File "C:\Users\LENOVO\AppData\Roaming\Python\Python37\site-packages\pip_internal\commands\install.py", line 604, in decide_user_install if site_packages_writable(root=root_path, isolated=isolated_mode): File "C:\Users\LENOVO\AppData\Roaming\Python\Python37\site-packages\pip_internal\commands\install.py", line 549, in site_packages_writable test_writable_dir(d) for d in set(get_lib_location_guesses(**kwargs)) File "C:\Users\LENOVO\AppData\Roaming\Python\Python37\site-packages\pip_internal\commands\install.py", line 549, in test_writable_dir(d) for d in set(get_lib_location_guesses(**kwargs)) File "C:\Users\LENOVO\AppData\Roaming\Python\Python37\site-packages\pip_internal\utils\filesystem.py", line 140, in test_writable_dir return _test_writable_dir_win(path) File "C:\Users\LENOVO\AppData\Roaming\Python\Python37\site-packages\pip_internal\utils\filesystem.py", line 153, in _test_writable_dir_win fd = os.open(file, os.O_RDWR | os.O_CREAT | os.O_EXCL) PermissionError: [Errno 13] Permission denied: 'C:\Program Files\Anaconda3\Lib\site-packages\accesstest_deleteme_fishfingers_custard_tzerxu' I got this error...How to fix that? -
How to add two render in Django function views
How to add two render in single function based views. I don't know this can be done, if not please provide the alternative way of doing this. views.py def success(request): return render(request, "tools/loading.html", {}) #Raspberry pi code print("on") pin13.write(1) time.sleep(2) print("off") pin13.write(0) return render(request, "tools/booked.html", {}) Currently it won't run the raspberry pi code, it directly returns the page and skip the rest of the code down the first render. But I need to update this code so that when calling this 'success' function based view it should return the 'loading.html', after performing the Raspberry pi code it should return another page. All this should be done in backend. -
HOW TO PASS AN ID INTO THE TEMPLATE
Here is the view.py file that have a function to create a child record,and it work fine def add_child(request): form=ChildForm(request.POST) if form.is_valid(): form.save() return redirect('/child/child') else: form= ChildForm() context= { 'form':form } return render(request,'functionality/add_child.html',context) And here is models.py file by which have child details,this model it have relationship with academic model from django.db import models class Child_detail(models.Model): Firstname = models.CharField(max_length = 50) Lastname = models.CharField(max_length = 50) Tribe = models.CharField(max_length = 50) Religion = models.CharField(max_length = 50) Date_of_birth = models.DateField() Current_Address = models.CharField(max_length = 50) def __str__(self): return self.Firstname This is academy models which have relationship with child_detail models from django.db import models from child.models import Child_detail class Academic(models.Model): Student_name = models.ForeignKey(Child_detail,on_delete = models.CASCADE) Class = models.CharField(max_length = 50) Date = models.DateField() Average_grade = models.CharField(max_length = 10) Overall_position = models.IntegerField() Total_number_in_class = models.IntegerField() def __str__(self): return self.Class In views.py I have this function that show child details and academy details with respective id, and everything working as fine def more_about_child(request,pk): child = get_object_or_404(Child_detail,pk=pk) test = Clinical_test.objects.filter(child=child) result = Result.objects.filter(child=child) immunisation = Immunisation.objects.filter(child=child) medical = Medical_report.objects.filter(child=child) parent = Parent.objects.filter(child=child) academic = Academic.objects.filter(Student_name=child) context={ 'child':child, 'test':test, 'result':result, 'immunisation':immunisation, 'medical':medical, 'parent':parent, 'academic':academic, } return render(request,'functionality/more/more.html',context) After a user creating a child details,therefore he/she … -
Django text formatting in template
I am trying to format text rendered from database in django template. #models.py class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='questions') text = models.TextField('Question', max_length=1500) def __str__(self): return self.text the text what i am entering in the text field is like a=50 b=30 c=a*b Now When I am calling this value in the template like. #template.html <p>{{ question.text }}</p> the text is printing like below in the template a=50 b=30 c=a*b I want the text to be formatted with line breaks while calling the values in template a=50 b=30 c=a*b -
Posting Objects with Pre-Existing Nested Objects in Django Rest Framework
I am working on some code that interacts with my site's API, but having some issues with Django Rest Framework. I am trying to send a post request to the server to create a new character, based on the model, serializer, and viewset below. ####################Serializer#################################### class CharacterSerializer(serializers.HyperlinkedModelSerializer): relatedTo = PlayerSerializer(); class Meta: model = Character fields = '__all__' #####################################Model############################################# class Character(models.Model): characterID = models.CharField(max_length=500); lastLogin = models.DateTimeField(); relatedTo = models.ForeignKey(Player, on_delete=models.CASCADE) shouldRun = models.BooleanField(default=True, null=True, blank=True); def __str__(self): return self.relatedTo.name + ": " + self.characterID; def save(self, *args, **kwargs): if self.relatedTo.lastLogin != None: self.relatedTo.lastLogin = self.lastLogin; else: if self.lastLogin > self.relatedTo.lastLogin: self.relatedTo.lastLogin = self.lastLogin; self.shouldRun = True; else: self.shouldRun = False; super().save(*args, **kwargs) ######################################ViewSet######################################## class CharacterViewSet(viewsets.ModelViewSet): queryset = Character.objects.all() serializer_class = CharacterSerializer def get_queryset(self): queryset = Character.objects.all(); shouldRun = self.request.query_params.get('shouldRun', None) charID = self.request.query_params.get('charID', None) name = self.request.query_params.get('name', None) if charID is not None: queryset = queryset.filter(characterID=charID); if shouldRun is not None: queryset = queryset.filter(shouldRun=shouldRun); if name is not None: queryset = queryset.filter(relatedTo__name=name); return queryset; The issue lies in the fact that I must include the Player object that a character is linked to while posting the object. I've included the Player information below as well. ####################Serializer#################################### class PlayerSerializer(serializers.HyperlinkedModelSerializer): class … -
Django perpetual 404s when visiting project directory URL
I have a very strange problem with Django and OLS. I am using the OpenLitespeed Django one click install droplet on Digital Ocean. In both my custom app and the example app in the droplet, if I visit a URL that matches the django project directory (in the example app, this is /demo/), then any subsequent page visits give a 404 error, no matter what URL you do. To reproduce, I've spun up a completely clean install of the droplet, then do the following steps: Go to / -> see "Hello world!" as expected Go to /demo/ -> also see "Hello world!" even though this should be a 404, as this URL is not specified in the urls.py or anywhere else Go back to / -> 404! It seems to be looking for /demo/demo/ which doesn't exist Trying any other URL also results in a 404. The only way to get back to the normal behavior is to restart the OLS process. Everything then functions as expected unless any URL that starts with the project directory name is visited, in which case the whole thing crashes and returns 404s again. Any help that can be provided to try and further … -
Django file read error - Filename must be 1-8 alphanumeric characters
I am trying to temporary save a file in the os and read it to convert it into ZPL format. It is working fine in jupyter notebook but when I tried to run the same in Django function it is showing the following error: zplgrf.GRFException: Filename must be 1-8 alphanumeric characters Views.py for i in items: barcode = get_barcode(value=i, width=600) a = barcode.save(formats=['PNG'], fnRoot=i) print("a ",a) with open(a, 'rb') as image: grf = GRF.from_image(image.read(), str(i)) grf.optimise_barcodes() print(grf.to_zpl()) os.remove(a) zpl = grf.to_zpl() where items = ['YNT929951321', 'YNT929951322', 'YNT929951323', 'YNT929951324'] How can I resolve this ? -
Sending Payouts in django
Hello i am working on a 3d-model selling platform. I would like to add payout functionality without using Paypal. Anyone with an idea of a workaround; kindly advice. -
How can I submit 3 forms in tabs by click of one button in django?
I have 3 forms, first one collects user's personal information, second collects users educational information and the third one has a submit button along with checkbox. My forms.py class PersonalInfoForm(ModelForm): CHOICES = [('female','female'),('male','male')] enrolment = forms.IntegerField(widget=forms.HiddenInput) date_of_birth = forms.DateField(widget=DateInput) gender = forms.ChoiceField(choices=CHOICES,widget=forms.RadioSelect) class Meta: model = Personal_Info fields = [ 'enrolment', 'first_name', 'middle_name', 'last_name', 'date_of_birth', 'gender', 'address' ] class EducationalInfoForm(ModelForm): username = forms.IntegerField(widget=forms.HiddenInput()) class Meta: model = Educational_Info fields = [ 'ssc_marks', 'ssc_percentage', 'ssc_board', 'hsc_marks', 'hsc_percentage', 'hsc_board', 'college_name', 'university', 'semester' ] class AgreeInfoForm(ModelForm): agree = forms.BooleanField() username = forms.IntegerField(widget=forms.HiddenInput()) class Meta: model = Agree_Info fields = [ 'agree' ] template named 'eligible-scholarships.html' <div class="row"> <div class="col-lg-12"> <div class="card"> <!-- open the below card body for the from --> <div class="card-body"> <h4 class="header-title mb-3"></h4> <ul class="nav nav-tabs nav-bordered nav-justified" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="personal-tab-b2" data-toggle="tab" href="#personal-b2" role="tab" aria-controls="personal-b2" aria-selected="true"> <span class="d-block d-sm-none"><i class="fa fa-personal"></i></span> <span class="d-none d-sm-block">Personal</span> </a> </li> <li class="nav-item"> <a class="nav-link" id="educational-tab-b2" data-toggle="tab" href="#educational-b2" role="tab" aria-controls="educational-b2" aria-selected="false"> <span class="d-block d-sm-none"><i class="fa fa-educational"></i></span> <span class="d-none d-sm-block">Educational</span> </a> </li> <li class="nav-item"> <a class="nav-link" id="complete-tab-b2" data-toggle="tab" href="#complete-b2" role="tab" aria-controls="complete-b2" aria-selected="false"> <span class="d-block d-sm-none"><i class="fa fa-complete"></i></span> <span class="d-none d-sm-block">Complete</span> </a> </li> </ul> <div class="tab-content"> <div class="tab-pane show active" id="personal-b2" role="tabpanel" aria-labelledby="personal-tab-b2"> … -
Query to get maximum x in django
My database: id | user_id | fat_intake | item_id 38 1 10 12 39 1 15 11 40 1 30 10 41 1 14 13 42 2 20 11 43 2 30 10 44 2 50 13 What will be the query to get user_id with the maximum fat intake till, i.e the response should be : Output: - Response Code: 200 - { "user_id": 1, "total_fat_count": 46 }