Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue in running django server while pulling code from GIT
I am working on a project which also contains a got repo initialized in it, we are multiple people working on same project but on different branches,my scenario is one of my friends pushes code to his branch then i pull that code from his branch so now i am having merged code(his and mine) now i push the code to my branch that contains final code. Now the problem is when i pulled code from his branch then my django server isn't starting, i think there is a directory issue, one more problem is when is witch to project view in pycharm it shows limited files with yellowish background and when i switch to project files it shows all files i am attaching both pictures My project directory project View Project_files_vies -
Django: How to verify a form whose fields are generated from a queryset in the forms __init__ method?
I have some trouble coming up with a good solution to validating a form whose fields are set in its init method. Quickly explaining my models: Every Product is supposed to have Variations, with each variation in turn having multiple VariationOptions. Every Product can have multiple Variations, like 'Color' or 'Material' Variations can have multiple VariationOptions (ManyToMany-Relation), like 'red' or 'concrete' When rendering the AddToCartForm, every Variation corresponds to a ChoiceField with the VariationOptions being used as choices for said ChoiceField. (see forms.py) Since every product can have different variations and therefore different fields, the AddToCart Form must be generated dynamically from a queryset containing the products variations (views.py), or at least thats what I'm thinking right now. My Questions: How can I validate this kind of form? Do you see a better way of achieving the same idea? I would very much appreciate your help. Thanks in advance! Here is my simplified code: MODELS.PY class Product(models.Model): .. class Variation(models.Model): name = models.CharField() product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='variations') options = models.ManyToManyField(VariationOption, blank=True) class VariationOption(models.Model): value = CharField() FORMS.PY class AddToCart(forms.Form): quantity = forms.PositiveIntegerField() # for every variation get all its choices and add new ChoiceField to form def __init__(self, variations, … -
Authenticating a User, without using Django rest framework?
Hey everyone I have a couple questions in regards to refactoring some old api endpoints as far as authentication goes. I have a view for example... @csrf_exempt # PARAMETERS: username, password def submit_offer(request): """Submit an offer""" username = request.GET.get("username") password = request.GET.get("password") # Authenticate user to set instance.user value into BuyerForm user = authenticate(username=username, password=password) if not user: # Always want our potential Buyer to be logged in & authenticated return JsonResponse({'message': 'Please login to continue.'}) if request.method == 'POST': form = BuyerForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) # sets current user as Buyer.user instance.user = user instance.save() return JsonResponse({'success': True}, status=200) else: data = form.errors.as_json() return JsonResponse(data, status=400, safe=False) else: return JsonResponse(data={'status': 403}) Now every view that uses a form, and needs to grab the instance.user, has the same lines of code below...now I thought using request.user would do the job, but when testing that way I am getting back an AnonymousUser, which is kind of confusing me? username = request.GET.get("username") password = request.GET.get("password") # Authenticate user to set instance.user value into BuyerForm user = authenticate(username=username, password=password) Now is there a better way to authenticate the user, like in a regular django view using request.user, rather than having … -
django serialization with nested object
I have real hard time to understand how django serializer works. I have an api_view function in charge to create a BGES object with a nested object Laboratoire such that : @api_view(['POST']) def add_bges(request): laboratoire_data = request.data.pop('laboratoire') laboratoire_serializer = LaboratoiresSerializer(data=laboratoire_data) if laboratoire_serializer.is_valid(): laboratoire_serializer.save() request.data["laboratoire"] = laboratoire_serializer.data["id"] bges_serializer = BGESSerializer(data=request.data) if bges_serializer.is_valid(): bges_serializer.save() return Response(bges_serializer.data, status=status.HTTP_201_CREATED) return Response(bges_serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(laboratoire_serializer.errors, status=status.HTTP_400_BAD_REQUEST) My BGESSerializer looks like this class BGESSerializer(serializers.ModelSerializer): class Meta: model = BGES fields = '__all__' This way, the returned object does not contain the Laboratoire object, so I change it by class BGESSerializer(serializers.ModelSerializer): laboratoire = LaboratoiresSerializer(read_only=True) class Meta: model = BGES fields = '__all__' But this way, when I set the variable laboratoire with the id in api_view like this request.data["laboratoire"] = laboratoire_serializer.data["id"] it's no longer working. I understand django is now expecting an object, by adding : laboratoire = Laboratoire.objects.get(pk=laboratoire_serializer.data["id"]) laboratoire_serializer2 = laboratoire_serializer(laboratoire) request.data["laboratoire"] = laboratoire_serializer2.data But still not working, the laboratoire field in the final answer is None, what am I doing wrong ? -
QuerySet appends _id in a field django
I have a model below class HomeImages (models.Model): homepage_id=models.ForeignKey(HomeAbout,on_delete=models.CASCADE) home_image=models.ImageField(upload_to="home_image",blank=True,null=True) I using a filter for a serializer def get(self,request,homeid): try: homeimg = HomeImages.objects.filter(homepage_id=homeid).values() except (KeyError, HomeImages.DoesNotExist): return Response('Data not found', status=status.HTTP_404_NOT_FOUND) else: if len(homeimg)>0: print("home object",homeimg) return Response([HomeImgSerializer(dat).data for dat in homeimg]) return Response([],status=status.HTTP_200_OK) problem is when I got the result of filter in homeimg object, it returns the field of homepage_id as homepage_id_id which incorrect how can I fix this it should mentioned homepage_id in result of queryset? Below is the queryset result <QuerySet [{'id': 1, 'homepage_id_id': 1, 'home_image': 'home_image/edit.png'}]> it shows homepage_id_id, whereas in model it is defined as homepage_id -
Generate Django Model objects through an API
I am building a Django application where I have defined all the necessary models I need for the project, but instead of having the database directly connected to it (with ORM), I want to use an API. Right now, I can fetch objects by ID, by making a request like this: def getStudentById(id): response = requests.get("http://localhost:8080/students/" + str(id)) if response.status_code != 200: raise DatabaseError("Error: getStudentById did not returned 200.") json_data = json_clean(json.loads(response.content)) return Student.load(json_data) The “json_clean” method, right now, deletes the “_links” provided by our API, that follows HATEOAS format. The “load” method from Student reads all the attributes provided by the JSON that it receives, like this: @classmethod def load(cls, json): j2m = dict(id='id', firstName='firstName', lastName='lastName', fullName='fullName', degree='degree', number='studentNumber', email='email', countryNic='countryNic', photo='photo') return cls(**{j2m[k]: v for k, v in json.items()}) Now, this is working perfectly fine, these objects are very much usable but, there is only a “big” problem, we cannot use or reference foreign keys with this model. My idea was to fetch all the necessary attributes (even the foreign keys that would need to be converted to another object), but it got me thinking about all the unnecessary memory usage that it would take, as different objects … -
Django Forms created from Model with overfull Queryset Output
I am trying to create a ModelForm for my Model Class "Asset" in Django 3 from django.db import models from django.contrib.auth.models import User from django.forms import ModelForm class Manufacturer(models.Model): name = models.CharField(max_length=100) class Asset(models.Model): serial = models.CharField(max_length=200) manufacturer = models.ManyToManyField(Manufacturer) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) I managed to create a Form via the following code from django import forms from .models import Manufacturer class AssetForm(forms.Form): serial = forms.CharField(max_length=150) manufacturer = forms.ModelChoiceField(queryset=Manufacturer.objects.all().values('name')) name = forms.CharField(max_length=200) description = forms.TextInput() status = forms.CharField(max_length=200) category = forms.CharField(max_length=200) The querySet results in a dropdown being filled out with either "{'name':'Apple'}" or "('Apple',)" depending on using values or values_list respectively. How can I just display the name itself? -
Join Tables with SQL Raw Query in Django Rest Framework
I have legacy database and want to make API with Django RestFramework. I have two tables and want to join those tables without using models. Here is my model.py after inspect legacy DB: class TblDivision(models.Model): id = models.BigAutoField(primary_key=True) strdivisionname = models.CharField(db_column='strDivisionName', max_length=35, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'Tbl_Division' class TblEmployee(models.Model): id = models.BigAutoField(primary_key=True) strname = models.CharField(db_column='strName', max_length=70, blank=True, null=True) # Field name made lowercase. stremployeeid = models.CharField(db_column='strEmployeeID', max_length=10, blank=True, null=True) # Field name made lowercase. intposition = models.IntegerField(db_column='intPosition', blank=True, null=True) # Field name made lowercase. intdivision = models.IntegerField(db_column='intDivision', blank=True, null=True) # Field name made lowercase. bitactive = models.BooleanField(db_column='bitActive', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'Tbl_Employee' This is my serializer.py : from rest_framework import serializers from .models import TblEmployee,TblDivision class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = TblEmployee fields=['id','strname','stremployeeid','intposition'] class DivisionSerializer(serializers.ModelSerializer): class Meta: model = TblDivision fields=['id','strDivisionName'] And this my view.py: @api_view(["GET", ]) def api_list_employee_view(request): try: employee_list = TblEmployee.objects.raw("Select * from Tbl_Employee") except TblEmployee.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == "GET": serializer = EmployeeSerializer(employee_list, many="true") dataEmployee = serializer.data return Response(dataEmployee) My expected output in API is employee name, employee ID, and the division name. It means I … -
How to clone model instances in Django?
I want a user to be able to copy a blog post by some other user and save it as their own post. Basically, when a user copies a blog post I want to create a new blog post by copying all of the fields from the original blog post but without any changes in an original blog post. Following is the code which I tried. The problem with this code is that when I try to copy blog post it is changing the primary key of the original blog post. I want the original blog post to remain untouched. Any suggestions would be appreciated. Thank you! class CopyView(LoginRequiredMixin, UpdateView): model = Entry template_name = 'entries/create_entry.html' fields = ['entry_title','entry_text', 'entry_input', 'entry_output'] def form_valid(self, form): form.instance.entry_author = self.request.user post = self.get_object() post.save() post.pk=None post.save() return super().form_valid(form) -
ModelForm Related To Specific Instance Django
So basically I am creating a jobs board using Django. I have a model such as: class Job(models.Model): title = models.CharField() description = models.CharField() reference = models.Charfield() etcetc I have a page that displays Job.objects.all() where users can go to a detail view that displays the detail of each instance, and on each detail view there's an Apply Now button, which takes the users to a form. The form has a field like: reference_code = forms.TextField() When a user clicks on the Apply Now button, I want the form to know which instance the user is applying for. I was thinking maybe prepopulating the form with the the 'reference' of the instance they have just came from may be the best way? (I.e. user on detailview > user clicks apply now > taken to apply page > form on page already knows which instance the user is applying for.) Any help is much appreciated. Thanks guys! -
Django search form with multiple search criteria
in my Django website I've got a simple search form. The User can look for a band name or an album name. But if the album and band name are the same I'd like the user to be redirected to a page where he can choose between looking for the band or the album. Hope someone could help me, I'm really stuck with this. Thanks a lot! this is the form in HTML: <form method="post" action="{% url 'searches' %}"> {%csrf_token%} <input type="text" name="srh" class= "form-control" placeholder=" Type Album or Band Name..."> <!-- <button type="submit" name="submit">Search</button> --> </form> views.py class searchesView(TemplateView): template_name = "search/searches.html" def post(self, request, *args, **kwargs): print('FORM POSTED WITH {}'.format(request.POST['srh'])) srch = request.POST.get('srh') if srch: sr = Info.objects.filter(Q(band__icontains=srch)) sd = Info.objects.filter(Q(disco__icontains=srch)) if sr.exists() and sd.exists(): return render(self.request, 'search/disambigua.html') else: paginator = Paginator(sr, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(self.request, 'search/searches.html', {'sr':sr, 'sd': sd, 'page_obj': page_obj }) else: return render(self.request, 'search/searches.html') The "searches" page where are listed the results: {% if sd %} {% for y in sd %} <div class="container"> <div class="album"> {%if y.cover%} <img src= "{{y.cover.url}}" width="100%"> {%endif%} </div> <div class="info"> <table class="talbum" style="height:400px"> <tr><th colspan="2"><h2>{{y.disco}}</h2></th></tr> <tr><td> Band: </td><td> {{y.band}} </td></tr> <tr><td> Anno: </td><td> {{y.anno}} … -
Why the pagination doesn't work in my Django website?
I followed the django documentation and I added the pagination and everything looks fine. Here is how it looks how the pagination looks like. I think the views.py, urls.py, and the template are okay and the problem is in the models.py, I don't know exactly. When I click to any page number in the pagination which will redirect me to the page with the url "example?page= " and the problem comes here, because my website doesn't work with the "?page=". Here is the error I got: IntegrityError at /new_search NOT NULL constraint failed: global_store_app_search.search Request Method: GET Request URL: http://127.0.0.1:8000/new_search?page=2 Django Version: 2.1.2 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: global_store_app_search.search Exception Location: /home/ubuntu/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 296 Python Executable: /usr/bin/python3 Python Version: 3.6.9 Python Path: ['/home/ubuntu/Desktop/TunisiaGlobalStoreDjango/global_store_project', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/ubuntu/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Thu, 2 Apr 2020 18:08:59 +0000 Here is the template: <div class="pagination"> {% if posts.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ posts.previous_page_number }}">Previous</a> {% endif %} {% for num in posts.paginator.page_range %} {% if posts.number == num %} <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a> {% elif num > posts.number|add:"-3" and num < posts.number|add:"3" %} <a … -
django: avoid repeating strings spanning relationships?
I have lookup strings that span multiple relationships and want to select/filter on fields of a related table. I end up with something like MyTable.objects \ .filter(aaa__bbb__ccc_field1=5) \ .values('aaa__bbb__ccc_field2') \ .annotate(Sum('aaa__bbb__ccc_field3')) Is there any way to refer to the multiple fields of aaa__bbb__ccc without repeating the whole string (obviously, I'm not asking about string concatenation, but whether there's any django-specific support). -
Django storage app files are always uploaded to same folder
I want every user to have his own folder with files. No matter on what account I am logged in, files are always uploaded to first registered user's folder. For instance, when I am logged as user "tester" files should go to /media/files/tester. models.py from django.contrib.auth.models import User def user_directory_path(instance, filename): return '{0}/{1}'.format(instance.user.username, filename) class FileModel(models.Model): title = models.CharField(max_length=50, blank=True) file = models.FileField(upload_to=user_directory_path) uploaded_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) def __str__(self): return self.title views.py @login_required() def main_page(request): files = FileModel.objects.filter(user=request.user) return render(request, 'dropbox/main_page.html', {'files': files} ) @login_required() def upload_file(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('main_page') else: form = FileForm() return render(request, 'dropbox/upload_file.html', {'form': form}) What to do to have files uploaded to proper folders depending on who is logged in? -
when I try to run python manage.py runserver , i am facing someproblem
enter image description here I'm neither getting an error nor getting a successful message -
how to insert my own form into ready Codepen template of search bar
Guys i have ready search input which i took from CodePen which looks great. <div class="input-group"> <input type="text" class="form-control" placeholder="Search this blog"> <div class="input-group-append"> <button class="btn btn-secondary" type="submit"> <i class="fa fa-search"></i> </button> </div> </div> I have the form which work good but is ugly : <form method="POST" > {% csrf_token %} {{ form}} <button lass="btn btn-secondary" type="submit"><i class="fa fa-search"></i></button></form> I want to combine my form into ready CodePen template instead of input. However when i tried the boxt of my form get into box of CodePen form and looks ugly. How to insert form into the first template which i took from the internet? I am not experienced with design so wanted your help make my form more beatiful and worksable. Thanks in advance -
Django - get objects that have a related objects with certain field only
Given the following models: class Person(models.Model): objects = PersonManager() ... class Job(models.Model): person = models.ForeignKey( to=Person, related_name='jobs' ) workplace = models.ForeignKey( to=Workplace, related_name='workers' ) position = models.CharField(db_index=True, max_length=255, blank=False, null=False, choices=( (POSITION_1, POSITION_1), (POSITION_2, POSITION_2), (POSITION_3, POSITION_3), )) A person can have several jobs with the same position and with different positions too. person1: [workplace1, POSITION_1], [workplace1, POSITION_2], [workplace2, POSITION_1] person2: [workplace1, POSITION_2], [workplace2, POSITION_2] person3: [workplace3, POSITION_3] I want to write a single method in PersonManager which will retrieve all persons with multiple jobs of a certain given position (and that position only); or if multiple positions are given then persons that work in all of these positions. Person.objects.get_multiple_jobs(jobs=[]) will return person1, person2 Person.objects.get_multiple_jobs(jobs=[POSITION_2]) will return person2 ONLY (as he's the only one with only POSITION_2 multiple jobs). Person.objects.get_multiple_jobs(jobs=[POSITION_1, POSITION_2]) will return person1 Person.objects.get_multiple_jobs(jobs=[POSITION_3]) won't return anything Using Person.objects.filter(jobs__position__in=[...]) won't work as in the 3rd case I'll get person2 as well. Chaining filter/exclude like Person.objects.filter(jobs__position=POSITION_1).exclude(jobs__position__in=[POSITION_1,POSITION_3] will work but it's not maintainable - what if in the future more positions will be added? Deciding which jobs to exclude dynamically is cumbersome. It also results in filters being very hard-codded when I wanted to encapsulate the logic under a single method … -
User Authentication in Django using MySQL database
My apologies, if the question has been asked multiple times. Trust me, I tried looking for an answer, but couldn't find it. I am building an Admin backend application in Django(Frontend is developed in PHP). I am trying to do user authentication. The user database is stored in UserInfo Table. I save the md5(password) in the UserInfo table. I would like to authenticate the user from the registered email address/password. Any idea how this can be achieved? Here is the small snippet of the code: from django.contrib.auth import authenticate email = 'kiran.chandrashekhar@gmail.com' passsword1 = '12345' user = authenticate(username=email, password=passsword1) print(user) -
error issue on connecting mysql for django project
I am new to Django.i am learning Django for the past few weeks,i have some trouble on changing the databse to sqllite to mysql. setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydb', 'USER': 'root', 'PASSWORD': ' ', 'HOST': 'localhost', 'PORT': '3306', }} When i try to run the server using py manage.py runserver It show me the error like django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)") SPECIFICATION python-3.8 django-3 MySQL(xampp) OS-windows -
populate django model with scraped data
I had Scrapped Data from https://www.worldometers.info/coronavirus/ for countrywise stats using bs4. but i want to use that data to populate my django model with same fields as scrapped data which i dont know how. i am also having trouble with scraping tabular data with other libraries like scrapy (celery).this is the xpath of the table i am try to scrap "//*[@id="main_table_countries_today"]". if anyone could help me how to use this scarp data to store in django models would be great. PS not using external CSV or Json Files. -
Post-Form Validation using Ajax and Django
I'm using Ajax to submit a form in Djangos Updateview. When not using AJAX to Post the form but a "submit"-Button and the form is invalid, the page gets reloaded and the user gets Information about what went wrong (f.e. email in wrong format). This is a Default Django-Feature. I was wondering if I can use the exact same feedback on an AJAX Form-POST? I mean Posting the form with Ajax and displaying the same information to the user about what went wrong, as if the Form was submitted via a "submit"-Button. Thanks in Advance! -
Conditions in querysets
I have a Dashboards table and a table that defines the "editor" permission as follows: Dashboard ========= id Name Owner -- ---- ----- 1 Dashboard1 555 DashboardUsers ============== id dashboard_id user_id editor -- ----------- ------- ------- 1 1 222 true 2 1 333 true Lets say that Owner that exists in Dashboard table is also an editor but this info does not exists in DashboardUsers table. So i m trying to construct a queryset that checks editor rows (including the Owner ). So i replace @userparamexample with 222 the queryset will correctly return a row. But if i replace the @userparamexample with 555 i will not get anyting. How do i have to moderate the query to get if someone is an editor(owner). models.Dashboard.filter( dashboarduser__user_id=@userparamexample dashboarduser__editor=True ) -
OperationalError: no such column: django-modeltranslation. Django
I have a working app in English. I have started translating tables and istalled django-modeltranslation. I have 11 similar pre-populated tables with the similar content. 8 tables have successfully migrated via python3 manage.py makemigrations and python3 manage.py migrate Migration of remaining 3 tables causes the same error for all three tables. django.db.utils.OperationalError: no such column: rsf_dirt.dirt_en django.db.utils.OperationalError: no such column: rsf_application.application_en django.db.utils.OperationalError: no such column: rsf_dirtproperties.dirtproperties_en All tables properly work via admin panel. Please help. models.py from django.db import models from django.utils.translation import gettext_lazy as _ class FP_sealing(models.Model): value = models.CharField(_('Material Sealing'), max_length=10) descr = models.CharField(_('Description'), max_length=200, default="") def __str__(self): return("Seal: " + self.value) class FP_ventil(models.Model): value = models.CharField(_('Backflush valve'), max_length=20) descr = models.CharField(_('Description'), max_length=200, default="") aufpreis_el_ventil = models.IntegerField(_('Extra Cost el.Valve'), default=0) def __str__(self): return("Ventil: " + self.value) class FP_motor(models.Model): value = models.CharField(_('Motor Power'), max_length=20) descr = models.CharField(_('Description'), max_length=200, default="") def __str__(self): return("Motor: " + self.value) class FP_material_geh(models.Model): value = models.CharField(_('Material Housing'), max_length=25) descr = models.CharField(_('Description'), max_length=250, default="") def __str__(self): return("Mat.Geh.: " + self.value) class FP_coating(models.Model): value = models.CharField(_('Coating'), max_length=25) descr = models.CharField(_('Description'), max_length=250, default="") def __str__(self): return("Coating: " + self.value) class FP_color(models.Model): value = models.CharField(_('External Color'), max_length=25) descr = models.CharField(_('Description'), max_length=200, default="") def __str__(self): return("Color: " + self.value) class … -
How do I specify order of fields in Django form?
We are using Django 2.2 and I want to upgrade to Django 3.0. We have a mixin (written in 2017) that add fields to forms: class LocalizedFirstLastNameMixin(object): def __init__(self, *args, **kwargs): self.language_code = kwargs.pop('language_code', 'en') super().__init__(*args, **kwargs) for loc_field in reversed(self.get_localized_fields()): self.fields[loc_field] = User._meta.get_field(loc_field).formfield() self.fields[loc_field].required = True self.fields.move_to_end(loc_field, last=False) self.initial[loc_field] = getattr(self.instance, loc_field, '') This mixin is used as one of the bases classes for forms which inherit from ModelForm: class RegistrationForm(AddAttributesToFieldsMixin, CleanEmailMixin, CleanNewPasswordMixin, CleanDateOfBirthMixin, LocalizedFirstLastNameMixin, forms.ModelForm): .... class ProfileForm(AddAttributesToFieldsMixin, CleanDateOfBirthMixin, LocalizedFirstLastNameMixin, forms.ModelForm): .... It works with Django versions up to 2.2. But when I upgrade to 3.0, I get this error message: AttributeError: 'dict' object has no attribute 'move_to_end' This function's info: Move an existing element to the end (or beginning if last==False). And it belongs to OrderedDict. So I guess we want these fields to be in the beginning of the form fields. Is there a change in the implementation of the fields in forms in Django 3.0 and how do I specify the order of fields? And if I change it, will it work in previous versions such as Django 2.2? I checked the Django 3.0 release notes and also releases from 3.0.1 to 3.0.5 and I … -
How to Implement django model methods
I am trying to build a system where we run depreciation on all assets in the database. Asset models is defined as below: class Asset(models.Model): Asset_description=models.TextField(max_length=100) Tag_number=models.TextField(unique=True) Asset_Cost=models.IntegerField(default=0) Monthly_Depreciation=models.IntegerField(default=0) Current_Cost=models.IntegerField(default=0) def __str__(self): return self.Asset_description How can i implement the depreciation formula in the models, e.g. Monthly_Depreciation=Asset_Cost/3/12 and Current_Cost=Asset_Cost-Monthly_Depreciation?