Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Merging a field in one model to another with ForeignKey, Django Subquery and OuterRef
I have two models, RetailLocation and Transaction, which share a one-to-many relationship respectively. My goal is to annotate RetailLocation with the date of the latest Transaction which corresponds to that RetailLocation. The model Transaction includes "r_loc_name" which is the exact same string as RetailLocation.name. I believe this field is redundant, and I expect there is a better solution using only the r_loc ForeignKey (and set) in RetailLocation, however I have not figured out how. Models class RetailLocation(models.Model): name = models.CharField(max_length=200, null=True) class Transaction(models.Model): date = models.DateTimeField(null=True) r_loc = models.ForeignKey(RetailLocation, null=True, on_delete=models.SET_NULL) r_loc_name = models.CharField(max_length=200, null=True) # Likely redundant Attempted Code loc_latest = RetailLocation.objects.all().annotate( latest_txn_time=Subquery( Transaction.objects.filter(r_loc_name=OuterRef("name")) .order_by("date") .values("date") .last() ) ) Another Attempt loc_latest = RetailLocation.objects.all().annotate( latest_txn_time=Value( Subquery( RetailLocation.objects.get(name=OuterRef("name")) .transaction_set.order_by("date") .last() .date ), DateTimeField(), ) ) My goal is to to reference RetailLocation.latest_txn_time, which would be the annotated datetime of the latest Transaction referenced to that RetailLocation. Thank you very much -
How do I get the data send by Ajax in Django?
I tried to get the data I send via Ajax with request.GET.get, but this does not work. Data is always None. I really appreciate any kind of help! This is my jQuery/Ajax code: $(document).ready(function(){ $(".jcf-select.jcf-unselectable").on('click', function(){ var sel = $('#sort').children("option:selected").val(); console.log(sel) $.ajax({ url: '/filter-data', data: sel, dataType: 'json', success:function(res){ console.log(res); $("#filter_products").html(res.order); } }); }); }); This is my view: def filter_data(request): if request.is_ajax: query = [] data = request.GET.get('data') if data == "gpv": query = data.order_by("price_with_shipping")[:150] elif data == "gp": query = data.order_by("lowest_price")[:150] elif data == "lp": query = data.order_by("liter_price")[:150] elif data == "tz": query = data.order_by("-lowest_price")[:150] t = render_to_string('homepage/ajax-products.html', {'order': query}) return JsonResponse({'order': t}) -
Cannot create django project in cmd
when I want to start a project with Django in cmd. I got an error. please I need help -
How do i pass a django url parameter to redirect function
I'm creating a blog website and I want it to be that when a user update a post, I want to redirect them to the view page for that article. the urls.py url_patterns = [ path('view/<str:id>/, views.viewPost, name='viewpost'), path('update/<str:id>/, views.updatePost, name='updatepost') ] My problem is that, I want to be able to redirect to the viewpost when I update a post I tried return redirect('viewpost' id) But it was giving me an error Thanks for your contribution -
Django SearchFilter Multiple models
Using Django 3.2 with Restframework. I'm trying for search filter and create a API with restframework which would output the searched term with its whole object. I had a little success on that with official doc. But from that I can only search in a single Model and not as globally. I found a blog on how to use multiple Models together? I tried for following from that: Views.py class GlobalSearchList(generics.ListAPIView): serializer_class = GlobalSearchSerializer def get_queryset(self): query = self.request.query_params.get('query', None) users = MasterUser.objects.filter(Q(firstname__icontains=query) | Q(lastname__icontains=query) | Q(email__icontains=query) | Q(category__icontains=query)) webinar = MasterWebinar.objects.filter(Q(host__icontains=query) | Q(title__icontains=query)) section = ResourceSection.objects.filter(Q(resource_name__icontains=query)) item = SectionItem.objects.filter(Q(item_title__icontains=query)) all_results = list(chain(users,webinar,section,item)) print(all_results) #Objects as output are printed in console return all_results #Blank output serializers.py class GlobalSearchSerializer(serializers.Serialize): def to_native(self, obj): if isinstance(obj, MasterIndividualMembers): serializer = MasterIndividualMembersSerializer(obj) elif isinstance(obj, MasterUser): serializer = MasterUserSerializer(obj) elif isinstance(obj, MasterWebinar): serializer = MasterWebinarSerializer(obj) elif isinstance(obj, MasterResource): serializer = MasterResourceSerializer(obj) elif isinstance(obj, ResourceSection): serializer = ResourceSectionSerializer(obj) elif isinstance(obj, SectionItem): serializer = SectionItemSerializer(obj) else: raise Exception("Not found in any instance!") return serializer.data In here, while printing the output it does print objects, but doesn't return anything as output. Any cause why there is no output, where am I doing wrong? Also I tried with serializers.ModelSerializer but … -
Why Django unique constraints did not work?
I've added UniqueConstraint into the constraints array in the Meta class which is a subclass of User table. class User(AbstractBaseUser): ... class Meta: verbose_name = _("account") verbose_name_plural = _("accounts") indexes = [ models.Index(name="email_index", fields=["email"]) ] constraints = [ models.CheckConstraint(name="check_birth_date", check=Q(birth_date__lt=f"{datetime.date.today()}")), models.CheckConstraint(name="check_phone_number", check=Q(phone_number__regex=r"^09(1[0-9]|2[0-9]|3[0-9])[0-9]{3}[0-9]{4}$")), models.UniqueConstraint(name="username_email_unique", fields=["username", "email"]) ] My expectation was that prevent user to enter username and email with same value, But actually did not work and user can do it without getting the IntegrityError Moreover, I'm using Postgresql -
how to put multiple Forms in the same views.py - Django
I need to put four Form in one views.py function, but I have no idea how to do it. I need every form to show on the site on the same time. I will take any advice on how I can solve this problem. models.py # Hotel class Hotel(models.Model): customer = models.ForeignKey(Account, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) short_description = models.TextField(max_length=250) long_description = models.TextField(max_length=2000, null=True) HOTEL_STAR = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5') ) star = models.TextField(max_length=1, default=5, choices=HOTEL_STAR, null=True) picture = models.ImageField(upload_to='images/%Y/%m/%d/',default="images/default.jpg" , blank=True) created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.name) # Room class Room(models.Model): hotel = models.ForeignKey(Hotel, null=True, on_delete=models.CASCADE) def __str__(self): return f'Room of {self.hotel}' # Single type for Room class Single(models.Model): room = models.ForeignKey(Room, null=True, on_delete=models.CASCADE) ROOM_NAME = ( ('Budget_single_room', 'Budget Single Room'), ('Standard_single_room', 'Standard Single Room'), ('Superior_single_room', 'Superior Single Room'), ('Deluxe_single_room', 'Deluxe Single Room'), ) name = models.TextField(max_length=30, choices=ROOM_NAME, null=True) ROOM_SMOKE = ( ('Smoking', 'Smoking'), ('Non-Smoking', 'Non-Smoking'), ) smoke = models.TextField(max_length=15, choices=ROOM_SMOKE, null=True) bed = models.IntegerField() capacity = models.IntegerField() room_size = models.IntegerField() def __str__(self): return f'{self.name}' # Double type for Room class Double(models.Model): room = models.ForeignKey(Room, null=True, on_delete=models.CASCADE) ROOM_NAME = ( ('Budget_Double_room', 'Budget Double Room'), ('Standard_Double_room', 'Standard Double Room'), ('Superior_Double_room', 'Superior … -
DRF changes name or ignores "create" route
I'm new to DRF's "viewsets", but I've inherited some problematic code, and am having trouble figuring out what's going on. I have stripped down the code below to isolate the behavior I don't understand. In my urls.py I have from my_app.api import CurrentUserViewSet, from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register("me", CurrentUserViewSet, basename="api-me") print(router.urls) Note the diagnostic print statement at the end. The CurrentUserViewSet is defined as: from rest_framework import viewsets from django.views.generic import View class CurrentUserViewSet(viewsets.ViewSetMixin, View): def create(self, request): """Update current user.""" instance = request.user ... @action(detail=False, methods=["post"]) def some_other_route(self, request): ... When I start a runserver instance that uses the above, it hits my print statement in "urls.py" and displays this: [ <URLPattern '^me/$' [name='api-me-list']>, <URLPattern '^me\.(?P<format>[a-z0-9]+)/?$' [name='api-me-list']>, <URLPattern '^me/some_other_route/$' [name='api-me-some-other-route']>, <URLPattern '^me/some_other_route\.(?P<format>[a-z0-9]+)/?$' [name='api-me-some-other-route']>... ] So it looks like the name of my create route is being changed to list. I don't know how or why this is happening. Interestingly, if I define an addtional route that is actually named "list", the "create" method still does not appear in the URLs created by the router. It seems to be totally ignored. As I mentioned, I inherited this code. I think that even though the original author named … -
Django - Firebase real time chat system
I need to make a chat system between a django app and an android app via a firebase real time database. I am using Pyrebase4 for handling the firebase, and Channels to handle the socket connection. I have a listener that listens to any changes in the chat room inside the Firebase real time database The listener is activated when the page is loaded: from accounts.firebase_repo import db def listen_to_chat(request, patient_key): doctor_id = request.user.id chat_id = f"{patient_key}_{doctor_id}" db.child("Chats").child(chat_id).stream(stream_handler) The stream_handler callback: def stream_handler(event): acc = AsyncChatConsumer() asyncio.run(acc.receive(event['data'])) The AsyncChatConsumer class: class AsyncChatConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, message): pass async def receive(self, text_data=None, bytes_data=None): # json_to_send = {} if text_data is not None: if 'message' not in text_data: # this is triggered on page load. Fetches all of the messages inside the room await self.send(text_data) else: # this is triggered when a new message is posted in the Firebase await self.send(text_data) the send method should trigger my javascript code. I have a chatSocket that I initialize when the DOM is loaded: window.addEventListener('DOMContentLoaded', (event) => { initializeSocket( "{{ context.key }}", "{{ context.doctor_id }}", "{% url 'send_message' %}" ); }); chatSocket = new WebSocket(wsStart + loc.host + '/ws/chat/' + … -
Django TypeError: get() got an unexpected keyword argument 'quiz_name'
I am trying to access a url from flutter webview , however, I am getting the following error. When I try to access this directly, I dont see any error. File "/home/quiz/views.py", line 629, in dispatch return super(QuizTakeAutoAuth, self).dispatch(request, *args, **kwargs) TypeError: get() got an unexpected keyword argument 'quiz_name' views.py class QuizTakeAutoAuth(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, request, format=None): content = { 'foo': 'bar' } return Response(content) def dispatch(self, request, *args, **kwargs): self.quiz = get_object_or_404(Quiz, url=self.kwargs['quiz_name']) if self.quiz.draft and not request.user.has_perm('quiz.change_quiz'): raise PermissionDenied if self.sitting is False: print("sitting false") if self.logged_in_user: return render(request, self.single_complete_template_name) else: redirecturl = "/login/?next=/quiz/"+self.kwargs['quiz_name']+"/take/" return redirect(redirecturl) return super(QuizTakeAutoAuth, self).dispatch(request, *args, **kwargs) urls.py url(r'^(?P<quiz_name>[\w-]+)/startquiz/$',view=QuizTakeAutoAuth.as_view(), name='quiz_question_auth'), What am I missing here? I am using the same view elsewhere without any knox Tokenauthentication and works as expected. -
Post working from build-in rest_framework UI (in browser) but not from Postman
while starting my backend project I've run into a problem and can't find a solution. I work with django and wanted to implement crud operations for one table named tutorials and these operations run great when I use the browser or build-in rest_framework UI from the browser but when I try the post request from postman (sending a json object) it gives me the 500 internal server error from postman this is my project structure , I have only one app called platforme : project structure This is the code in platforme/urls.py from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from platforme import views urlpatterns = [ path('tutorials/',views.TutorialList.as_view()), path('tutorials/<int:pk>/',views.TutorialDetail.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) This is the code in platforme/models.py , I only have one model from django.db import models # Create your models here. class Tutorial(models.Model): title = models.CharField(max_length=70, blank=False, default='') description = models.CharField(max_length=200,blank=False, default='') published = models.BooleanField(default=False) This is platforme/serializers.py from rest_framework import serializers from platforme.models import Tutorial class TutorialSerializer(serializers.ModelSerializer): class Meta: model = Tutorial fields = ('id','title','description','published') And finally this is the platforme/views.py : from rest_framework import generics from rest_framework import mixins from platforme.models import Tutorial from platforme.serializers import TutorialSerializer class TutorialList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = Tutorial.objects.all() serializer_class … -
Docker files to be ignored on .gitignore
I'm new to docker. I've finalized dockerizing a Django projet of mine. What files and/or folders should I add to my .gitginore before pushing the changes to the project? Or no files should be added? I'm not talking about my .dockerignore file. -
Django migrations problem: Field id expectet a number but got 'China'
I set a default value of Country field in Item model as 'China'. Then i tried migrate and i showed an error that should set a default value in each of field. I've done it but after next migrate command i got an error "Field id expecter a number but got 'China'", but i change a default value to '4'. P.S.: I don't use Model.objects.filter() anywhere. I just work with models only. It's my models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE from slugger import AutoSlugField class Item(models.Model): title = models.CharField(max_length=128) price = models.DecimalField(max_digits=7, decimal_places=2, default='0') color = models.ForeignKey('Color', on_delete=CASCADE, default='White') category = models.ForeignKey('Category', on_delete=CASCADE, default='SOMECATEGORY') age = models.ForeignKey('Age', on_delete=CASCADE, default='0') description = models.CharField(max_length=5000, default='') in_stock = models.BooleanField(default=True) country = models.ForeignKey('Country', on_delete=CASCADE, default='4') # here was default value China slug = AutoSlugField(populate_from='title', default='') def __str__(self): return self.title class Color(models.Model): color = models.CharField(max_length=32) def __str__(self): return self.color class Category(models.Model): category = models.CharField(max_length=64) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.category class Country(models.Model): country = models.CharField(max_length=64) class Meta: verbose_name_plural = 'Countries' def __str__(self): return self.country class Age(models.Model): age = models.CharField(max_length=32) class Meta: verbose_name_plural = 'Ages' def __str__(self): return self.age -
How to export python list into excel file using xlwt?
Here I am trying to export python list to the excel file but it is not working correctly. The list will be dynamic. response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="excle_file.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('datas', cell_overwrite_ok=True) row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['col1', 'col2', 'col3', 'col4', 'col5'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows = [20, Decimal('50000.00'), Decimal('10.00'), Decimal('40000.00'), Decimal('90000.00'), 21, Decimal('31000.00'), Decimal('2000.00'), Decimal('41000.00'), Decimal('74000.00')] for i,e in enumerate(rows): ws.write(i,1, e) wb.save(response) return response I want response like this. col1 col2 col3 col4 col5 20 50000 10 40000 90000 21 31000 2000 41000 74000 Current response col1 col2 col3 col4 col5 20 50000 10 40000 90000 21 31000 .... Also I want to increase the size of the column based on the text? How it will be done ? -
How to add javascript variable to django model database
I want to insert this javascript variable into django model which look like this. It's a location info variable which has address, latitude, longitude and place name. placeInfo = { address: "address example" latlng: pa {La: 51.12508408777138, Ma: 1.3337612324096222} name: "name example" } The database model consists of Posts model and Place model is subordinated to the Posts model. I want to put placeInfo javascript variable to the Place model. from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=100) lat = models.CharField(max_length=25) lng = models.CharField(max_length=25) def __str__(self): return "{}".format(self.name) class Posts(models.Model): title = models.CharField(max_length=50, null=True) pick_date = models.DateField(null=True) create_date = models.DateField(auto_now=True, null=True) music = models.CharField(max_length=100, null=True) mood = models.CharField(max_length=50, null=True) description = models.CharField(max_length=300, null=True) image = models.ImageField(upload_to="images/", null=True) place = models.ForeignKey(Place, on_delete=models.CASCADE, related_name="location") def __str__(self): return str(self.title) What I've searched until now is about AJAX handling but I'm not used to it so any help would be appreciated -
Getting ModuleNotFoundError in Django
Project Structure urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.homepage, name='homepage'), path('login_user', views.login_user, name='login_user'), path('logout_user', views.logout_user, name='logout_user'), path('register_user', views.register_view, name='register_user'), path('dashboard', views.dashboard, name='dashboard'), ] chat_app2/views.py from django.contrib.auth import logout, authenticate, login from django.http import HttpResponse from django.shortcuts import render, redirect from chat_app2.account.forms import RegistrationForm def register_view(request, *args, **kwargs): user = request.user if user.is_authenticated: return HttpResponse("You are already authenticated as " + str(user.email)) context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email').lower() raw_password = form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) destination = kwargs.get("next") if destination: return redirect(destination) return redirect('homepage') else: context['registration_form'] = form else: form = RegistrationForm() context['registration_form'] = form return render(request, 'register_user.html', context) settings.py AUTH_USER_MODEL = 'account.Account' # Application definition INSTALLED_APPS = [ 'account', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Error File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Manish Gusain\Documents\Python_Projects\chat_app2\chat_app2\urls.py", line 3, in <module> from . import views File "C:\Users\Manish Gusain\Documents\Python_Projects\chat_app2\chat_app2\views.py", line 4, in <module> from chat_app2.account.forms import RegistrationForm ModuleNotFoundError: No module named 'chat_app2.account' I'm trying to add new user to the database using a user … -
React and Django - Connect the Note model with the specific User
I am creating a notes saving app using react and django_rest_framework. My Note model - from django.db import models from django.contrib.auth.models import User class Note(models.Model): title = models.CharField(max_length=100) content = models.TextField() def __str__(self): return self.title Note Serializer - from rest_framework import serializers from .models import Note class NoteSerializer(serializers.ModelSerializer): class Meta: model = Note fields = ("id", "title", "content") For register and logging in I am following the answer here - Answer Now, how do I connect my note object to the specific logged in user so a particular note is only visible to that user? This can be done with ForeignKey in django but how to do it in django_rest_framework? Please help. Thanks! -
Fast Search With Django + PostgreSQL
I am newbie working on Django with PostgreSQL database. I want to know that, what are the most efficient approaches for fast search on large data (millions of records). because I ran query on 300K records, it took too much time. Please kindly guide me that how can I do fast search in Django? Thank you so much. -
unable to get CSS to load on a Django html page
My css is not rendering on any of my HTML pages in a dJango project. I have followed a few Stack solutions to no avail, including adding <link rel="stylesheet" href="{% static "styles.css" %}" type="text/css" media="screen" /> as described here: Django static files (css) not working and also changing that to <link rel="stylesheet" href="{% static 'style.css' %}" />, suggested here: Unable to Apply CSS on my HTML file Django currently my HTML looks like: {% extends "mail/layout.html" %} {% load static %} <link rel="stylesheet" href="{% static 'styles.css' %}" /> {% block body %} <div id="inbox-view"> <h3>Inbox</h3> <button id="show-email-row" class="btn default"> email row </button> <button class="btn default">Default</button> </div> {% endblock %} {% block script %} <script src="{% static 'mail/inbox.js' %}"></script> {% endblock %} And my css file called styles.css, which is in a folder called '''static''' looks like this: textarea { min-height: 400px; } .btn { border: 2px solid black; background-color: white; color: black; padding: 14px 28px; font-size: 16px; cursor: pointer; } /* Gray */ .default { border-color: #e7e7e7; color: black; } .default:hover { background: #e7e7e7; } Ideally, the button will change color on hover, and have a dark background. Thank you -
Django.db.utils.DataError: value too long for type character varying(300) In django Models
I'm not sure what limit is this error django.db.utils.DataError: value too long for type character varying(300) is referring to, Can you tell me what I'm doing wrong and how to fix that problem. #models.py class Meetings(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, verbose_name = "Appointment Made By") reasonOfAppointment = models.TextField(null=True, blank=True, verbose_name = "Reason of Appointment") dateOfBirth = models.CharField(max_length=200, null=True, blank=True, verbose_name = "Patient Date Of Birth") gender = models.CharField(max_length=200, null=True, blank=True, verbose_name = "Gender") maritalStatus= models.CharField(max_length=200, null=True, blank=True, verbose_name = "Merital Status") phoneNumber=models.CharField(max_length=200, null=True, blank=True, verbose_name = "Phone Number") emergencyContactNo=models.CharField(max_length=200, null=True, blank=True, verbose_name = "Emergency Contact Number") medicalHistory= models.TextField(null=True, blank=True, verbose_name="Patient Medical History") previousTreatmentDetails=models.TextField(null=True, blank=True, verbose_name="Prevous Treatment Details") allergicTo= models.CharField(max_length=200, null=True, blank=True, verbose_name="Allergies") taxPrice = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) consultancyServiceFee = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) totalFee = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) isPaid = models.BooleanField(default=False, verbose_name= "Is Payment Recieved ") paidAt = models.DateTimeField(auto_now_add=False, null=True, blank=True, verbose_name= "Paid At") meetingWillBeConductedOn = models.CharField(max_length=200, null=True, blank=True, verbose_name ="Meeting Venue Zoom or etc") meetingSchedual = models.CharField(max_length=200, null=True, blank=True, verbose_name ="Give Tentative Time Of when Meeting will be conducted") meetingLink = models.CharField(max_length=2000, null=True, blank=True, verbose_name ="Enter Meeting Link") isMeetingConducted = models.BooleanField(default=False, verbose_name="Is Meeting Has been Held") meetingConductedAt = models.DateTimeField( auto_now_add=False, null=True, blank=True, verbose_name="Meeting … -
how can i deal with this problem "i want a button which shows when i click on radio button after that it will display "
enter image description here I want this button whenever i clicked on perfect address so please can any one help me -
How to serve dynamic sitemap.xml through nginx?
How to serve dynamic sitemap.xml file (generated from a CMS) through nginx? Is there any rules that have to be configured? Thanks -
send user to a link with data in that link
The main idea is I want to generate a Qrcode that going to have a URL, I want the URL to contain data {object}, and I want to collect that object in the other page(URL). I hope the Idea is clear, and can someone please help me with methodologies to achieve that result. -
__str__ returned non-string (type NoneType) ERROR when adding DATA
Right now I'm trying to get user-specific data in a website I'm using but I'm getting what seems to be a pretty basic error when I click submit on one of my forms. The error is: str returned non-string (type NoneType) my view looks like this: def adddata_asbestos(request): if not request.user.is_staff or not request.user.is_superuser: raise Http404 form = SheetForm_Asbestos(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() messages.success(request, "Successfully Created") return HttpResponseRedirect("/front_page/sheets/list_data_asbestos/") context = {"form": form,} return render(request, 'sheets/add_data/add_data_asbestos.html', context) And importantly this is the form that adds data: {% load static %} <!DOCTYPE html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static "css/add_data.css" %}"> <link rel="stylesheet" href="{% static "css/materialize2.css" %}"> <title>Ladder - Asbestos Add Data</title> </head> <div class="back_button_sheet"> <a style="background-color: #2f3d50; border-radius: 18px;" href="{% url 'list_asbestos' %}" class="btn btn-primary">< Back</a> </div> <div class="table_position_add container my-4"> <div class="card my-3"> <div class="card-body"> <h4 style="font-size: 30px; text-align: center;">Asbestos Testing</h4> <form class="table_add" method="POST" action=""> {% csrf_token %} <table class="table table-bordered"> <tr> <td style="font-weight: bold;">Date</td> <td> <input placeholder="MM/DD/YYYY"{{ form.date }} <div style="font-size: 15px;">{{ form.date.errors }}</div> </td> </tr> <tr> <td style="font-weight: bold;">Time</td> <td> <input placeholder="HH:MM am/pm"{{ form.time }} <div style="font-size: … -
Modify objects before making query in Django
I have a model like this: name price N1 950 $ N2 930 € N3 1200 $ N4 800 € I want to get objects that their price is lower than or equal 1000 $. But before that, I want to first convert the unit of all prices to dollars and secondly convert their data type to int. Some thing like this: for i in range(0, len(price)): if '€' in price[i]: price[i] = int([int(s) for s in price[i].split() if s.isdigit()][0] * 1.18) else: price[i] = int([int(s) for s in price[i].split() if s.isdigit()][0]) print(price) ############ Output ############ # [950, 1097, 1200, 967] and then make this query:(Entry.objects.price__lte=1000). (N1, N4 must be results)