Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
/ in urlpatterns django
I am a beginner in django and don't understand the meaning "/" in urlpatterns. Here is the urlpatterns in my project urls. My first app's name is first. urlpatterns = [ path('admin/', admin.site.urls), path('first', include("first.urls")) ] I found that it didn't work unless I amended it to following: urlpatterns = [ path('admin/', admin.site.urls), path('first/', include("first.urls")) ] I don't understand what the meaning of '/' is. I googled but did not find an answer. Could anyone help me on this? Another question is that the double quotes and single quote could be used either way. But is there any convention or better practice that I can follow to use single or double quote? Thanks a lot. -
How to send dictionary context while returning a redirect function to get context data when calling this function from an api?
I have a function which redirect to a url, this function have a context dict , i want to get this dict by calling this function from another api function call, please help me ,, my code is here web function def myfunction(request, id): context = dict() obj = Model.objects.get(id=id) obj.status = 'Draft' obj.save() # Success Message to Mobile App context['status'] = 'Success' context['message'] = 'Reset successfully' context['d'] = id context['Number'] = obj.no # i want to attach this context in return(not in the url like # kwargs or args but separately) so that i get context # when i call this function from another function return redirect('del_details',str(id)) API calling function class CallingAPI(APIView): permission_classes = (IsAuthenticated,) serializer_class = SomeSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) try: response = function1(request=request, id=serializer.data['id']) # here in response i want the context from function1 json_response = json.loads(response.content) if json_response['status'] == 'success': # Do something return JsonResponse(final_result, safe=False, status=status.HTTP_200_OK) except Exception as e: pass SO when i do response = function1(request=request, id=serializer.data['id']), i want the context dictionary in response and redirect will remain same. How to achieve it. Right now i am getting only <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/del_details/120/" in response, i need the … -
django Count on FK with Sum and filters
I have to find the number of participants where the sum of two fields is above a given field. Following models: class Examination(models.Model): total_score = models.FloatField(_('Total score'), blank=False, null=False, default=60) class ExamParticipation(models.Model): examination = models.ForeignKey(Examination, blank=False, null=False, on_delete=models.CASCADE, related_name='examination_participations') total_score = models.DecimalField(_('examination score'), max_digits=3, decimal_places=1, default=0) additional_score = models.DecimalField(_('additional score'), max_digits=3, decimal_places=1, default=0) So for a given Examination I have to count how many participants, where the sum of total_score and additional_core, have more or equal like total_score/2. Is this feasible with a queryset at all or do I have to loop over the results? I tried following query: def count_sufficient_participations(self): qs = self.values('examination_participations').order_by('examination_participations').annotate( ts=Sum(F('examination_participations__total_score') + F('examination_participations__additional_score')) ).annotate(cnt_suff=Count('examination_participations')).filter(ts__gte=30) but does not seem to work and I do not know how to replace 30 with the field total_score from examination. I want to have something like examination.cnt_suff for my template. Any help will be appreciated. -
USING A DATEPICKER WITH DJANGO AND CHART.JS
Good day, i am new to django. Can i be shown how to use a datepicker to show my chart.js for the specific date selected by a user? Can i be shown how to install a datepicker for this purpose?Below was my attempt and i have not been able to display any data. This is my model: class Complainer(models.Model): STATES = ( ('Abia', 'Abia'), ('Abuja', 'Abuja'), ('Adamawa', 'Adamawa'), ('Akwa-Ibom', 'Akwa-Ibom'), ('Anambra', 'Anambra'), ('Bauchi', 'Bauchi'), ('Bayelsa', 'Bayelsa'), ('Benue', 'Benue'), ('Borno', 'Borno'), ('Cross-River', 'Cross-River'), ('Delta', 'Delta'), ('Ebonyi', 'Ebonyi'), ('Edo', 'Edo'), ('Ekiti', 'Ekiti'), ('Enugu', 'Enugu'), ('Gombe', 'Gombe'), ('Imo', 'Imo'), ('Jigawa', 'Jigawa'), ('Kaduna', 'Kaduna'), ('Kano', 'Kano'), ('Katsina', 'Katsina'), ('Kebbi', 'Kebbi'), ('Kogi', 'Kogi'), ('Kwara', 'Kwara'), ('Lagos', 'Lagos'), ('Nasarawa', 'Nasarawa'), ('Niger', 'Niger'), ('Ogun', 'Ogun'), ('Ondo', 'Ondo'), ('Osun', 'Osun'), ('Oyo', 'Oyo'), ('Plateau', 'Plateau'), ('Rivers', 'Rivers'), ('Sokoto', 'Sokoto'), ('Taraba', 'Taraba'), ('Yobe', 'Yobe'), ('Zamfara', 'Zamfara') ) SECTOR = ( ('Federal Government', 'Federal Government'), ('State Government', 'State Government'), ('Local Government', 'Local Government'), ('Private Company', 'Private Company'), ('Public Company', 'Public Company'), ('Other', 'Other'), ) NATURE = ( ('Delay of Service', 'Delay of Service'), ('Non compliance with Regulation', 'Non compliance with Regulation'), ('Demand for Bribery', 'Demand for Bribery'), ('Vandalism', 'Vandalism'), ('Unrepaired or damaged infrastructure', 'Unrepaired or damaged infrastructure '), ('Insecurity', 'Insecurity'), ('Non … -
Update value and keep the key on python dictionary
I have a parking place app where I want to calculate the available days in a week, and the total available hours per day. I have different cities with different timeshifts, some have full time (for example 7:00-20:00) and others have separated time (for example 7:00-14:00 and 16:00-20:00). Here is the loop I tried: def get_available_hours(self): _dict = [] time = 0 query_set = TimeTableCity.objects.filter(city_id=self._city_id) for i in query_set: initial_hour_datetime = datetime.strptime(i.initial_hour, '%H:%M') end_hour_datetime = datetime.strptime(i.end_hour, '%H:%M') time = end_hour_datetime - initial_hour_datetime _dict.append({i.day_table.id: time.seconds / 3600}) time = 0 return _dict And the returned dict at the end is the following: [{4: 5.0}, {4: 4.0}, {5: 5.0}, {5: 4.0}, {1: 5.0}, {1: 4.0}, {2: 5.0}, {2: 4.0}, {3: 5.0}, {3: 4.0}] The key is the day of the week, and the value is the hours for that shift. Is there a way to sum the values for the same key? -
AbstractUser in Django is not authenticating
Django version 3.2 I have created a AbstractUser model for storing info of Bank's Customer . I am able to register the customer but it's not getting authenticated while login . In admin page the password is saved as plain text , which is not expected . It should be saved in hashed form by default in Django . Please give some directions to solve this . What I am doing wrong ? In settings.py I have added line : AUTH_USER_MODEL = 'banking.Customer' models.py : ''' This stores all customers of this bank . ''' class Customer(AbstractUser): #username = models.CharField(max_length=128, unique=True) #first_name = models.CharField(max_length=128) #last_name = models.CharField(max_length=128) #email = models.CharField(max_length=128) phone = models.CharField(max_length=128) #password = models.CharField(max_length=2048) dateJoined = models.DateTimeField(auto_now_add=True) # completed, pending, blocked, error verificationStatus = models.CharField(max_length=128) #USERNAME_FIELD = 'username' #REQUIRED_FIELDS = [] def __str__(self): return f"{self.username}, {self.first_name} {self.last_name}, {self.email}, {self.password}" views.py : def register(request): if request.method == "POST": # get the information from form print("POST request :" + str(request.POST)) userName = request.POST["userName"] firstName = request.POST["firstName"] lastName = request.POST["lastName"] email = request.POST["email"] phone = request.POST["phone"] password = request.POST["password"] # insert it in DB, keep in mind that username should be unique try: customer = Customer(username=userName, first_name=firstName, last_name=lastName, email=email, phone=phone, password=password, … -
How to integrate my Django Rest Framework with Angular?
How do I integrate my Django Apps with a new created Angular Project? For example one of my apps is called eapp and this is the app structure: newapp (folder) eapp (folder) migrations (folder) tests (folder) admin.py apps.py models.py serializers.py urls.py views.py newapp (folder) __init__.py asgi.py settings.py urls.py wsgi.py manage.py My models.py file in eapp only contains of two classes: from django.db import models class Energy(models.Model): edata = models.CharField(max_length = 200) ... def __str__(self): return self.edata class Freeze(models.Model): ... The Django Rest Framework for eapp has successfully been installed in my serializers.py, urls.py and views.py file. I have also created a new Angular Project in another Visual Studio Code. Who knows how what my next steps are, or where I can get some good info on how to integrate these two? -
Let user download files on React page sent from Django FileField connected to AWS S3 bucket
I have a React/Django website for registering job applications. The user upload pdf files on a React page. The files are then sent to a Django backend FileField which is connected to a AWS S3 bucket. On another React page I try to summerize the application. I recive the application info and the file from the FileFiled is now a reference to a AWS s3 site. How can I use this reference to let the user download the file on the React page? -
How to change the behaviour of unique true in django model?
Here I am not deleting the model objects from database. I am just changing the is_deleted status to True while delete. But while doing this unique=True gives error for the deleted objects so how can I handle this ? I want to exclude is_deleted=True objects from unique True. class MyModel(models.Model): name = models.CharField(max_length=20, unique=True) is_deleted = models.BooleanField(default=False) #views class MyViewSet(ModelViewSet): serializer_class = MySerializer queryset = MyModel.objects.all() def destroy(self, request, *args, **kwargs): object = self.get_object() object.is_deleted = True object.save() return Response(status=status.HTTP_204_NO_CONTENT) -
A section in a webpage is not getting displayed for using for loop in django
This is my view: def index(request): week_ago = datetime.date.today()-datetime.timedelta(days=7) read_blog = Post.objects.filter(time_upload__gte = week_ago).order_by('-read_count') params = { 'posts': Post.objects.all(), 'read_blogs': read_blog[:4], } return render(request,'index.html', params) This is my model: from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length = 50) overview = models.TextField() time_upload = models.DateTimeField(auto_now_add = True) author = models.ForeignKey(Author,on_delete = models.CASCADE) thumbnail = models.ImageField(upload_to='thumbnails') publish = models.BooleanField() categories = models.ManyToManyField(Categorie) mins_read = models.CharField(default=3, max_length= 3) read_count = models.IntegerField(default=0) class Meta: ordering = ['-pk'] def __str__(self): return self.title This is the portion of my index.html not rendering: {% extends 'base.html' %} {% block body %} {% load static %} {% for read in read_blogs %} <div class="mainsection-articles"> <div class="mainsection-articles-images"> <img src="{{read.thumbnail.url}}" alt="" style="width: 235px;"> </div> <div class="mainsection-articles-content"> <a href="../page1.html"> <h3> {{read.title}}</h3> </a> <span>Author:{{read.author}}|</span> <p>{{read.overview}}</p> <span>Date:{{read.time_upload}} </span><br> <a href="../blogpost.html">Read more...</a> </div> </div> {% endfor %} When I am inspecting using the browser, this whole section inside the forloop is not visible.Kindly help me out why only this portion is not rendering.Apart from this section every other section are visible and working perfectly. -
Visual Studio Code 'django-admin' command not recognized
'django-admin' is not recognized as an internal or external command, operable program or batch file... So I am getting this error in terminal. I am trying to build an app. First I opened a folder(page) in my computer D drive and then opened Visual Studio Code. From there I opened the folder(page) and from view I opened terminal. Then when I am trying to type django-admin myproject page. it is showing this error. -
nginx setup for Django Channels 3 using Daphne and Supervisor
I have created a Django application with channels. Now I am configuring it for production in AWS EC2. I can access the app when running the python manage.py runserver 0.0.0.0:8000. The apps that I deployed to AWS were using wsgi only and need only Gunicorn. But since channels use asgi the Daphne was used. It specifies few steps in the docs (https://channels.readthedocs.io/en/latest/deploying.html) /etc/supervisor/conf.d/asgi.conf [fcgi-program:asgi] # TCP socket used by Nginx backend upstream socket=tcp://localhost:8000 # Directory where your site's project files are located directory=/home/ubuntu/myproject # Each process needs to have a separate socket file, so we use process_num # Make sure to update "mysite.asgi" to match your project name command=/home/ubuntu/venv/bin/daphne -u /run/daphne/daphne%(process_num)d.sock --fd 0 --access-log - --proxy-headers myproject.asgi:application # Number of processes to startup, roughly the number of CPUs you have numprocs=1 # Give each process a unique name so they can be told apart process_name=asgi%(process_num)d # Automatically start and recover processes autostart=true autorestart=true # Choose where you want your log to go stdout_logfile=/home/ubuntu/log/asgi.out.log stderr_logfile=/home/ubuntu/log/asgi.err.log redirect_stderr=true /etc/nginx/sites-enabled/django.conf upstream channels-backend { server localhost:8000; } server { location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header … -
Django social-auth: How to handle Youtube (Google) Auth Error: AuthStateForbidden?
I am using django social-auth to authorize users in Google Analytics and Youtube. Hence one backend in 2 different templates is used. However, with Google Analytics everything works like charm, but when I try to authorize in Youtube in the end of the authentication process comes an error: social_core.exceptions.AuthStateForbidden: Wrong state parameter given. I have tried to remove already successfully authorized my app for Google Analytics Scopes from Google Account and authorize again for Youtube Scopes but it brings no difference. My youtube handler: class YouTubeLoginHandler(object): def __init__(self, client_secret): self.SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'] self.CLIENT_SECRETS_PATH = client_secret def init_youtube_api(self): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( os.path.abspath( os.path.join(os.path.dirname(__file__), self.CLIENT_SECRETS_PATH) ), scopes=self.SCOPES) flow.redirect_uri = 'http://localhost:8000/api/oauth/complete/google-oauth2/' authorization_url, state = flow.authorization_url( # Enable offline access so that you can refresh an access token without # re-prompting the user for permission. Recommended for web server apps. access_type='offline', # Enable incremental authorization. Recommended as a best practice. include_granted_scopes='true') return authorization_url My view in views.py @login_required def login_youtube(request): user = request.user youtube = YouTubeLoginHandler('client_secrets.json') authorization_url = youtube.init_youtube_api() return HttpResponseRedirect(authorization_url) -
How to convert list to json?
I have a queryset; queryset = tagReferenceLocationInfo.objects.select_related('ref').filter(tag_id__in=id_list, date__gte=startDate, date__lte=endDate) I got this queryset result data as a list; data = list(queryset) How can convert this list as a json? -
how to change a char field to list field or array field in Django model?
I want the Char field "device_id" to be changed to a list field or an array field without loosing the current data present in the field , so it can hold multiple device ids. class User(AbstractBaseUser, PermissionsMixin): id = ShortUUIDField(primary_key=True, editable=False) email = models.EmailField(verbose_name="email address", max_length=255, unique=True) phone = models.CharField(max_length=50, null=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) device_id = models.CharField(max_length=255, blank=True, null=True) Usecase :I need the user to be associated with multiple devices here after -
how to have pagination in a bootstrap modal, such that when it refreshes the modal stays there?
how to have pagination in a modal, such that when it refreshes the modal stays there? Currrently because of the django logic {%%} the page will refresh and it will go to page 2, but the modal would be hidden, I have to open it again. Is there a way to keep the modal there after refresh? Or if better, is there a way to do pagination without using django, through perhaps using javascript instead Django Views.py (this handles the backend for the pagination) paginator = Paginator(album_array, 5) page_number = request.GET.get('page') try: page_obj = paginator.page(page_number) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) if page_number is not None: if int(page_number) > 1: page_obj.previous_page_number = int(page_number) - 1 else: page_obj.previous_page_number = False if int(page_number) < paginator.num_pages: page_obj.next_page_number = int(page_number) + 1 else: page_obj.next_page_number = False html: <!-- Pagination --> {% if page_obj.has_other_pages %} <nav aria-label="Page navigation"> <ul class="pagination justify-content-center"> {% if page_obj.has_previous %} <li class="page-item"><a href="?page={{ page_obj.previous_page_number }}"><span class="page-link">Prev</span></a></li> {% else %} <li class="page-item disabled"><span class="page-link">Prev</span></li> {% endif %} {% for i in page_obj.paginator.page_range %} {% if page_obj.number == i %} <li class="page-item active"><span class="page-link">{{ i }}</span></li> {% else %} <li class="page-item"><a href="?page={{ i }}"><span class="page-link">{{ i }}</a></li> {% … -
Is it possible to use the DISTINCT tag on a filtered query?
I am currently working with Django models and I would like to do the following : First, I do a qs = model.objects.all() (where model is the name of my model) Then, I apply some filters on that qs like qs = qs.filter(id_file__startswith=file_id) for instance Finally, I would like to do a raw request (so I can use 'DISTINCT') to get all the distinct places in the "id_place column": for row in qs.raw(f"SELECT file_id, id_place as place FROM {board} group by place"): place = row.place.lower() l_place.append(place) But the problem is that it does the raw request directly in the database, not in the filtered qs. I know it can be done with : places = qs.values("id_place") l_places = set() for row in places: l_places.add(row['id_place']) But I find it not flexible enough for what I would like to do next, and I don't like the fact that I am not using the "DISTINCT" tag that would make this a lot easier and cleaner. Do you have any idea how I could do this ? Thank you in advance! -
Email Activation (Django Project)
I tried to make Account Activation in my Django Project but when i try register user and my code gives error have and does not send the email to given account. SMTPSenderRefused at /accounts/register/ (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError n27sm15044097pfv.142 gsmtp', 'webmaster@localhost') Request Method: POST Request URL: http://localhost:8000/accounts/register/ Django Version: 3.2 Exception Type: SMTPSenderRefused Exception Value: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError n27sm15044097pfv.142 gsmtp', 'webmaster@localhost') Exception Location: /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py, line 871, in sendmail Python Executable: /Users/barkhayotjuraev/Desktop/Django Apps/GreatCard/env/bin/python3 Python Version: 3.8.6 Python Path: ['/Users/barkhayotjuraev/Desktop/Django Apps/GreatCard', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload', '/Users/barkhayotjuraev/Desktop/Django ' 'Apps/GreatCard/env/lib/python3.8/site-packages'] Server time: Wed, 05 May 2021 07:22:03 +0000 i have turned off two step verifications and turned on Less secured apps -
How to make user profile fields like phonenumber, gender, publically hidden in a social media app using django?
in a Social media app how to make phone number field as a private/public field. class User(AbstractBaseUser, PermissionsMixin): groups = models.ForeignKey(Group,on_delete=models.CASCADE) email = models.EmailField(max_length=255,unique=True,) phone = PhoneField(null=False, blank=False, unique=True) phone_visibility = models.BooleanField(default=False) def get_phone_no(self): if self.phone_visibility: return(self.phone) else: return ('') -
How to detect unused python packages in DJango/Docker project using VS Code?
I have been working for moth on a Django project testing and learning and now have 73 packages listed in my requirements.txt many of these packages are not used and I want to remove them Moreover, some packages seems to conflict when I try to install a new one (django-sql-exlplorer) I've read about a first solution that is to use an new env with empty requirement.txt and missing pakcages will prone error ut I use DOcker and this seems to be painful another way, that seems to be easier is using Pycharm option that can inspect code Python: How to detect unused packages and remove them Is there a similar way doing this second method using VS Code? -
NameError at /astrologiaviva Name 'astrologiaviva' is not defined
someone could help to understand this error? NameError at /astrologiaviva name 'astrologiaviva' is not defined The index.html render a page with 3 buttons. I would like to load and display text[0] if you click on the first button, text[1] if you click on the second one and text[2] if you click on the third one. Hopefully this is enough for somone to help me, thanks! <script> window.onpopstate = function(event) { console.log(event.state.section); showSection(event.state.section); } function showSection(section) { fetch(`/${section}`) .then(response => response.text()) .then(text => { console.log(text); document.querySelector('#content').innerHTML = text; }); } document.addEventListener('DOMContentLoaded', function() { document.querySelectorAll('button').forEach(button => { button.onclick = function() { const section = this.dataset.section; history.pushState({section: section}, "", `/${section}`); showSection(section); }; }); }); </script> <body> <h1>Hello!</h1> <button data-section="astrologiaviva">Astrologia viva</button> <button data-section="aprendizajelibre">Aprendizaje libre</button> <button data-section="arte">Arte</button> <div id="content"> </div> </body> this is urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<str:name>", views.name, name="section") ] this is views.py from django.http import Http404, HttpResponse from django.shortcuts import render # Create your views here. def index(request): return render(request, "singlepage/index.html") texts = ["ABC", "GHJ", "XYZ"] def name(request, name): if name == astrologiaviva: return HttpResponse(texts[0]) elif name == aprendizajelibre: return HttpResponse(texts[1]) elif name == arte: return HttpResponse(texts[2]) else: raise Http404("No such section") -
Django: How to use a custom social-auth backend?
I have overridden the GoogleOAuth2 class in django social-auth. Currently the new class is in views.py. But I cannot find how to add it to AUTHENTICATION_BACKENDS in settings.py I have tried like this: AUTHENTICATION_BACKENDS = ( '_auth.backends.YouTubeOAuth2', <---------- new backend 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.twitter.TwitterOAuth', 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ) And adjusted the template: window.open('{% url 'social:begin' 'youtube' %}', '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes'); In the end of the Google auth process comes an error: ModuleNotFoundError at /api/oauth/complete/google-oauth2/ No module named '_auth' -
In Django ModelSerializer unable to mark a field required as false
I am trying to make a field investor required as False in Django Restframework's ModelSerializer. class WatchListSerializer(serializers.ModelSerializer): class Meta: model = WatchList fields = ['id', 'investor', 'property'] extra_kwargs = { 'investor' : { 'required' : False } } However, both the fields are defined as ForeignKeys in the model. As you can see in above implementation I am trying to override the default implementation of field investor using extra_kwargs. Unfortunately, it still asking to provide the value for investor. Here is the model Watchlist - class WatchList(BaseModel): investor = models.ForeignKey(User, on_delete=models.PROTECT, blank=False, null=True) property = models.ForeignKey(Properties, on_delete=models.PROTECT, blank=False, null=True) class Meta: unique_together = (('investor', 'property',)) def __str__(self): return f'Watch List Object {self.id}:' -
how can i convert str to float (the value of foreignkey)
please how can i convert Foreignkey value string to float ? in models.py i create a following code, the target is to get the value of foreingkey as float then use it to calculate the value of redevance. class production(models.Model): nom= models.CharField(max_length=70, blank=False, null=True) choix_type = ( ('','selectionner le type de projet '), ('exploration/production','exploration/production'), ('developpement/production','developpement/production'), ('Exploitation','Exploitation'), ) forme_projet = models.CharField(max_length=50, default='', blank=False, null=True, choices=choix_type) quantite = models.FloatField(blank=False, null=True) prix = models.FloatField(blank=False, null=True) def __str__(self): return str(self.nom) if self.nom else '' def calcule_production(self): return self.prix * self.quantite class redevance(models.Model): production_projet = models.ForeignKey(production, on_delete=models.CASCADE, null=True, blank=False) cout_transport = models.FloatField(blank=False, null=True) cout_liquifaction = models.FloatField(blank=False, null=True) cout_separation = models.FloatField(blank=False, null=True) def calcule_cout(self): return (self.cout_transport + self.cout_liquifaction + self.cout_separation) - self.production_projet type error the error seems like this: thanks -
How to Create an api to extract xml file in django
I need to create an API in Django that will use to take an XML file and extract the data from it. I have created models and serialization and now I can not understand the view part(api) please help.