Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to download a dynamic file in django?
I have created a django application that converts txt to csv files. Now, I want to create a view function to download the newly converted csv files. Any suggestions will be highly appreciated. How to read the path object in download view? views.py def submit(request): # this function uploads txt files. # this function converts txt to csv files. For example abcd.txt is converted into abcd0000.csv and abcd0000.csv is stored in /main/temp/ folder. path = 'main/temp/converted_file.csv' #(Example)This file is dynamic # context is also present return render(request,'submit.html',context) Now I want to create a download function. For example: def download(request): data = open(path,'r').read() resp = HttpResponse(data, mimetype='application/x-download') resp['Content-Disposition'] = 'attachment;filename=path.csv' return resp submit.html <html> <head> <title> </title> </head> <body> <p>You have successfully converted the file. </p> <p><a href ="{% url 'download' %} ">Download (Filename)</a></p> </body> </html> -
Django Admin site not showing add permission option for a user
Actually i was learning permissions in django and also learning about groups. At first i have not inherited the PermissionMixin class when i have created my models. After finding i find my mistake why there is no option for the permission and groups for the custom user model. After that i updated my models and inherited the permissionmixin and finally it showed the permissions and groups option for a user in my model. But...............there is no such option to add a user to a group or to give permission to a user. As i have seen in some youtube videos there are some arrow keys to add permission or to remove them. Please help me to find out what i'm missing. I'm still a learner and learning django. My models from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser,PermissionsMixin ) # ///////////////User Manager///////////////////// # Create your models here. # overriding the create and superuser funciton class MyAccountManager(BaseUserManager): def create_user(self,email,username,password=None): if not email: raise ValueError("Users Must Have email Address") if not username: raise ValueError("Users Must Have username") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,username,password): user = self.create_user( email = self.normalize_email(email), username=username, … -
How to 'select distinct on' as a subquery using django filters
I'm creating a search function for my django project and was wondering how I can group rows while ordering them by the amount of points the players have scored. I want to be able to group them and when it finds values with the same name, it just takes the first value The solution I found on postgresql select * from (select distinct on (name) * from database_manager_player) t order by pts desc; I wanted to know if there was a way to code something similar in django. in views.py: def get_queryset(self): qs = Player.objects.all().order_by('-pts') sort_by = self.request.GET.get("sort") if sort_by is not None and sort_by != str(0) sort_by = "-" + sort_by with 'qs' how could I do something in the if statement so that it does the same as in postgresql. -
403 csrf token error with paytm in django
I am trying to integrate the paytm payment gateway to my django web app. While most the process works properly and the payment is successful, the callback URL is not being called. Instead, I get the following error message Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests. When I spoke to the technical team at paytm they told me that I had to accept the callback URL in POST. The person I spoke to, had little experience in django and could not help me further. I am not really sure what accepting the response in POST means. Here is my code views.py def donate(request): if request.method == "POST": form = DonateForm(request.POST) name = request.POST.get('firstName') phone = request.POST.get('phone') email = request.POST.get('email') amount = float("{0:.2f}".format(int(request.POST.get('amount')))) ord_id = OrdID() cust_id = CustID() paytm_params = { "MID" : MERCHANTID, "WEBSITE" : "DEFAULT", "INDUSTRY_TYPE_ID" : "Retail", "CHANNEL_ID" : "WEB", "ORDER_ID" : … -
Django,how to filter multiple JSONField data?
Im using django with postgres i was able to add multiple filters in my views but mu question here is is there any possibility that i can filter multiple same jsonfield with different values: ex i can filter localhost:127.0.0.1:products?areaOfUse=residential so is there any possibilty that i can get the result of /products?areaOfUse=residential&areaOfUse=test So from here i need to query two different json objects. -Here are my views class SubcategoriesProductsAPI(APIView): # @cache_control(must_revalidate=True, max_age=3600) def get (self, request, subCategoryId = None, pk = None): try: ''' Missing filters for PVC: 1.Colour Range 2.Pattern 3.Design Type ''' filters = {} design = self.request.query_params.get('design', None) dimension = self.request.query_params.get('dimension', None) collectionName = self.request.query_params.get('collectionName', None) material = self.request.query_params.get('material',None) min_price = self.request.query_params.get('min_price',None) max_price = self.request.query_params.get('max_price',None) page = self.request.query_params.get('page', None) wearLayer = self.request.query_params.get('wearLayer',None) areaOfUse = self.request.query_params.getlist('areaOfUse',None) productType = self.request.query_params.get('type', None) installationMethod = self.request.query_params.get('installationMethod',None) format_type = self.request.query_params.get('format_type',None) wearLayer = self.request.query_params.get('wearLayer',None) levelOfUse = self.request.query_params.get('levelOfUse',None) if design is not None: filters['product_options__options__data__design'] = design if productType is not None: filters['product_options__options__data__type'] = productType if dimension is not None: filters['product_options__options__data__dimensions__contains'] = [{'dimension': dimension}] if collectionName is not None: filters['product_options__options__data__collectionName'] = collectionName if material is not None: filters['product_options__options__data__material'] = material if wearLayer is not None: filters['product_options__options__data__wearLayer'] = wearLayer if installationMethod is not None: filters['product_options__options__data__installationMethod'] =installationMethod … -
not able to upload and display django form
1.views.py from django.shortcuts import render from . models import User from .forms import Userform def Home(request): if request.method == "POST": form = Userform(request.POST or None,request.FILES or None) if form.is_valid(): form.save() else: form = Userform() return render(request,"home.html",{"form":form}) def read(request): read = User.objects.all() return render(request,"read.html",{"read":read}) 2.models.py from django.db import models class User(models.Model): name = models.CharField(max_length=12) rollno = models.IntegerField() # files = models.FileField() 3.form.py from django import forms from .models import User class Userform(forms.ModelForm): class Meta: model = User fields = ('name','rollno') urls.py from django.contrib import admin from django.urls import path from app import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path("",views.Home,name="Home"), path("read/",views.read, name="read"), ] urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) 4.home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form method="POST" action="read/" enctype="multipart/form-data"> {%csrf_token%} {{form}} <button type=submit>click to submit</button> </form> </body> </html> read.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {%block containt%} {%for i in read%} {{i.name}} {{i.rollno}} {%endfor%} {%endblock%} </body> </html> i want to add data to django admin using a form but data is not uploading at django admin Not able to upload data into django admin hence cant read it please help i want … -
How to define a model class variable to keep track of temporary data without saving to database
I am trying to design a checkout process where the tax information needs to go through a lookup table to get the appropriate tax rate based on parameters like buyer_address, product_price, etc. I am trying to avoid storing the tax rate as a property of the cart as a model field in the database because this value changes on the fly as the checkout form values change (cart line items change or shipping address changes). It's not solely a property of the cart or cart line item but depends on other paramters. I tried using a local variable in the class, and during the checkout process, once the customer clicks on PlaceOrder (POST to PaymentDetailsView), on the backend, a tax lookup will be done and added to the cart accordingly by setting that property. I am having a hard time understanding why the variable value remains None even after setting it. The lookup right now returns an example number of 0.8 as but I would have a more detailed method for the lookup that later. MODELS class BagLine(models.Model): _unitTax = None bag = models.ForeignKey(Bag, on_delete=models.CASCADE, related_name='lines') product = models.ForeignKey(ProductDesign, on_delete=models.CASCADE, related_name='bagLines') quantity = models.PositiveIntegerField(default=1) @property def unitTax(self): return self._unitTax @unitTax.setter … -
Django remote user not available in middleware - only in view
I`m using the django remote user middleware, and an own middleware mysupermiddleware: MIDDLEWARE = [ ..., 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', 'my_project.middleware.mysupermiddleware', ] When a remote user authenticates, it is available in the view. request.user shows the username. But in my middleware, it is not available def mysupermiddleware(get_response): def middleware(request): print (request.user) request.user returns AnonymousUser When I print request.user in my view, it returns the remote authenticated user. When I authenticate with ModelBackend instead RemoteUserBackend, the user is available in middleware and view. Is this intended? How do I make the remote user available in the middleware? Django version is 3.1.1 -
Django translation.activate doesn't change the language
I have a two-language Django website and when I want to change the language, it doesn't work. Here is the links in the template to change the language: <a href="{% url 'change_lang' %}?lang=en&next={{ request.path }}">EN</a> <a href="{% url 'change_lang' %}?lang=fa&next={{ request.path }}">FA</a> I send the language that I want and the current path as parameters for the view. This is the urls.py: from .views import change_language urlpatterns = [ path('change_lang', change_language, name='change_lang'), ] And this is the views.py: from django.utils.translation import activate def home(request): # My commands # activate('fa') context = { # Some key and values } return render(request, 'home.html', context) def change_language(request): activate(request.GET.get('lang')) return redirect(request.GET.get('next')) And I found that activate(request.GET.get('lang')) doesn't work. But when I uncomment the activate('fa') in the home view, It does work. But this command doesn't work in the change_language method. Is it because of the redirect function in the change_language view? What did I do wrong? Thanks for your help. -
Creating custom Django Rest Framework permision
I have created a django rest custom permision and for testing purposes I made sure has_object_permission and has_permission retrun False. from rest_framework import permissions class IsWorker(permissions.BasePermission): message = "Login with Supplier Account" def has_object_permission(self, request, view, obj): return False def has_permission(self, request, view): return False How comes this view doesn't work as expected? from packages.models import Package from .serializers import WorkerPackageSerializer from rest_framework.permissions import IsAuthenticated from api.permissions import IsWorker class WorkerPackageDetailViewSet(generics.RetrieveUpdateDestroyAPIView): serializer_class = WorkerPackageSerializer permission_classes = (IsAuthenticated, IsWorker) lookup_field = "id" def get_queryset(self): return Package.objects.all() Expectations: I thought it would return a forbidden error with the message Login with Supplier Account but if the user is not authenticated it returns a not authenticated error and if the user is authenticated it returns the data without any error. -
HTML checkbox value is only return 'on' in django
html <FORM NAME="myForm" method="GET" action="{%url 'search_result'%}"> <label for="F">Female</label><INPUT TYPE="checkbox" NAME="gender" ONCLICK="toggleShow(this)" value="F" id="0"> <DIV ID="subCats0" CLASS="subCats"> <INPUT TYPE="checkbox" NAME="age" ONCLICK="toggleShow2(this)" vaule='10' id='10'> gender=10 <div id="sub10" Class="sub"> <INPUT TYPE="checkbox" NAME="category_name[]" value="c"> 1.c <INPUT TYPE="checkbox" NAME="category_name[]" value="a"> 2.a <INPUT TYPE="checkbox" NAME="category_name[]" value="d"> 3.d </div> </DIV> <BR> <label for="M">Male</label><INPUT TYPE="checkbox" NAME="gender" ONCLICK="toggleShow(this)" id='1' value='M'> <BR> <DIV ID="subCats1" CLASS="subCats"> <INPUT TYPE="checkbox" NAME="10"> gender=10 </DIV> <input type="submit" value="search" id="search_button"> </FORM> css .subCats { display: none; margin-left: 20px; } .sub { display: none; margin-left: 20px; } javascript function toggleShow(checkbox) { var id = 'subCats' + checkbox.id; var subCats = document.all ? document.all[id] : document.getElementById ? document.getElementById(id) : null; if (subCats) { if (subCats.style.display == '' || subCats.style.display == 'none') subCats.style.display = 'block'; else subCats.style.display = 'none'; } } function toggleShow2(checkbox) { var id = 'sub' + checkbox.id; var sub = document.all ? document.all[id] : document.getElementById ? document.getElementById(id) : null; if (sub) { if (sub.style.display == '' || sub.style.display == 'none') sub.style.display = 'block'; else sub.style.display = 'none'; } } when click the submit, gender and category_name[] return correct value. for example, gender=F&age=on&category_name=b But age value is only return 'on'. Even though set the value of the check box, only return 'on'. what is problem..? Is the … -
Import Excel/csv and save data to new DB table
I am trying to develop a web application for Import any type of data like Excel/CSV and to insert the data to new table of connected DB without django model. While Inserting table column name as excel column and excel file name is table name. I wrote the code for Excel import using HTML screen its working fine. but I am stucking with Insert imported data to new DB table. Request your suggestion. def index(request): if "GET" == request.method: return render(request, 'index.html', {}) else: excel_file = request.FILES["excel_file"] wb = openpyxl.load_workbook(excel_file) worksheet = wb["PolicyData"] print(worksheet) excel_data = list() for row in worksheet.iter_rows(): row_data = list() for cell in row: row_data.append(str(cell.value)) excel_data.append(row_data) return render(request, 'index.html' {"excel_data":excel_data}) HTML code: <html> <head> <title>Import File</title> </head> <body style="margin-top: 30px;margin-left: 30px;"> <form action="{% url "test:index" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" title="Upload excel file" name="excel_file" style="border: 1px solid black; padding: 5px;" required="required"> <p> <input type="submit" value="Upload" style="border: 1px solid green; padding:5px; border-radius: 2px; cursor: pointer;"> </form> <p></p> <hr> {% for row in excel_data %} {% for cell in row %} {{ cell }}&nbsp;&nbsp; {% endfor %} <br> {% endfor %} </body> </html> -
Is there a way to perform accent-insensitive lookups using Django and MariaDB?
I would like to make an accent-insensitive lookup in a french database (with words containing accents): >>> User.objects.filter(first_name="Jeremy") ['<User: Jéremy>', '<User: Jérémy>', '<User: Jeremy>'] After lots of research, I found that Django has an Unaccent lookup for PostgreSQL but nothing for other databases (like MariaDB) Is there a way to make this happen without changing the database to PostgreSQL? -
How to get user email id through username by using csv file
By using csv/xls file we will upload usernames then in download we have to get user email_id to that specific user. How can I do? any help -
How to Save Received dictionary Data into Django DataBase?
views.py file I'm using paytm payment gateway here, I want to save data into database in response view but Im getting data in dict form how do I access individual and pass into user.email field def payment(request): user = request.user order_id = Checksum.__id_generator__() bill_amount = request.GET['money'] data_dict = { 'MID': settings.PAYTM_MERCHANT_ID, 'INDUSTRY_TYPE_ID': settings.PAYTM_INDUSTRY_TYPE_ID, 'WEBSITE': settings.PAYTM_WEBSITE, 'CHANNEL_ID': settings.PAYTM_CHANNEL_ID, 'CALLBACK_URL': settings.PAYTM_CALLBACK_URL, 'CUST_ID': user.email, 'ORDER_ID':order_id, 'TXN_AMOUNT': bill_amount, } # This data should ideally come from database data_dict['CHECKSUMHASH'] = Checksum.generate_checksum(data_dict, settings.PAYTM_MERCHANT_KEY) context = { 'payment_url': settings.PAYTM_PAYMENT_GATEWAY_URL, 'comany_name': settings.PAYTM_COMPANY_NAME, 'data_dict': data_dict, } return render(request, 'payment.html', context) def response(request): if request.method == "POST": MERCHANT_KEY = settings.PAYTM_MERCHANT_KEY CUST_ID = request.POST['CUST_ID'] data_dict = {} for key in request.POST: data_dict[key] = request.POST[key] if data_dict.get('CHECKSUMHASH', False): verify = Checksum.verify_checksum(data_dict, MERCHANT_KEY, data_dict['CHECKSUMHASH']) else: verify = False if verify: for key in request.POST: if key == "BANKTXNID" or key == "RESPCODE": if request.POST[key]: data_dict[key] = int(request.POST[key]) else: data_dict[key] = 0 elif key == "TXNAMOUNT": data_dict[key] = float(request.POST[key]) PaytmHistory.objects.create(user = User.objects.only('user_id').get('user.email' == CUST_ID).user_id, **data_dict) return render(request, "callback1.html", {"paytm": data_dict}) else: return HttpResponse("checksum verify failed") else: return HttpResponse("Method \"GET\" not allowed") return HttpResponse(status=200) waiting for help -
What I am missing in the setup of nginx with gunicorn which leads to 502 error?
I am setting up django + gunicorn + nginx on my local (mac os) to test some nginx reverse proxy configuration. I have gone through few tutorials about the setup of these. I have a doubt: Everywhere in tutorials they run gunicorn as daemon or service. Why is it necessary? cant we just run gunicorn in a shell binding it to a port (which will be listened by nginx) My gunicorn.conf.py file: import os bind = '0.0.0.0:8080' errorlog = '-' worker_class = 'gthread' workers = 2 threads = 3 timeout = 60 max_requests = 25 max_requests_jitter = 3 preload_app = True worker_connections = 5 keepalive = 65 running gunicorn using : gunicorn --conf gunicorn.conf.py my-project.wsgi:application nginx nginx.conf: upstream test { server localhost:8080; keepalive 32; keepalive_timeout 65s; } server { listen 80; proxy_http_version 1.1; proxy_connect_timeout 5s; proxy_send_timeout 10s; proxy_read_timeout 20s; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; location / { proxy_pass http://test; } } then I run this nginx conf using nginx docker creating image from DockerFile: FROM nginx:alpine COPY nginx.conf /etc/nginx/conf.d/default.conf Then running the image by: docker run --rm -p 3030:80 --name test-server <image-name> after these localhost:8080 serves my django project through unicorn but localhost:3030 (nginx … -
Pandas 1.2 Update - pd .read_excel no longer imports file from form - Path Error
I am using Django to select an Excel (xlsx) file from a form. (This is a Foundation html.) <form action="{% url "edit:add_trades" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="FileUpload" class="button">Upload File</label> <input type="file" id="excel_file" class="show-for-sr"> </form> Before using Pandas 1.10 and xlrd 1.2 all worked well with this code: This is the view code: if request.method == 'POST': file = request.FILES [ 'excel_file' ] file_name, file_type = os.path.splitext ( file.name ) // check for xlsx file type if str ( file_type ) != '.xlsx': msg = "Sorry, not a .xlsx file." messages.warning ( request, msg ) return redirect ( '/edit/index' ) # get the excel data df = pd.read_excel ( file, sheet_name = 'orders', index_col = None, header = None ) When I update to pandas 1.2 I get a file error: FileNotFoundError at /edit/add_trades/ [Errno 2] No such file or directory: '63P-11955.xlsx' Request Method: POST Django Version: 2.2.16 Exception Type: FileNotFoundError I also get this error when updating the xlrd. What changed in this Pandas update and the path from a Django form? Using python 2.8 and Django 2.2.16. Thank you. -
Issue When Running Django Migrations on MariaDB 10.5.8
I have been trying to migrate from a mysql database (version 5.7.26-29-31.37-log - output from SELECT VERSION()) to a mariadb (version 10.5.8-MariaDB-log - output from SELECT VERSION()) Also, I saw and updated django from version 2.2 to version 3.1.5, as mariadb is officially supported from version 3.0. With this, I also updated the mysqlclient library to 2.0.3. But when on the server the "migrate" command is run, it fails with this error when doing it with the new DB: decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>] Here is the stack-trace: DEBUG (0.008) SELECT @@SQL_AUTO_IS_NULL; args=None DEBUG (0.007) SHOW FULL TABLES; args=None DEBUG (0.007) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None DEBUG (0.008) SHOW FULL TABLES; args=None OUT Operations to perform: OUT Apply all migrations: admin, auth, contenttypes, my_auth, essay, multichoice, quiz, sessions, sites, social_django, true_false OUT Running pre-migrate handlers for application auth OUT Running pre-migrate handlers for application contenttypes OUT Running pre-migrate handlers for application sessions OUT Running pre-migrate handlers for application sites OUT Running pre-migrate handlers for application admin OUT Running pre-migrate handlers for application quiz OUT Running pre-migrate handlers for application multichoice OUT Running pre-migrate handlers for application true_false OUT Running pre-migrate handlers for application essay OUT Running pre-migrate handlers for … -
I am trying to search the student result using registration# ? Help appricated
need help to search the data, when I enter the registration number it is not giving me the details which I have typed in the admin page. need help ??? home.html I don't know how to place data for display and also in other stuff. moodle.py from django.db import models from django.utils.encoding import smart_text class ResultQuery(models.Model): name=models.CharField(max_length=150) dept_name=models.CharField(max_length=200) cgpa=models.CharField(max_length=50) reg_number=models.CharField(max_length=100) def __str__(self): return smart_text(self.name) app==> url.py from django.urls import path from . import views urlpatterns = [ path('', views.home), ] forms.py from django import forms class ResultForm(forms.Form): Reg_No =forms.CharField(label="Registration Number") views.py from django.shortcuts import render # Create your views here. from django.shortcuts import render from .forms import ResultForm from .models import ResultQuery def home(request): form=ResultForm(request.POST or None) template_name = "home.html" context = {"form": form} if form.is_valid(): objects = ResultQuery.objects.filter(reg_number=form.cleaned_data['Reg_No']) context['objects'] = objects return render(request, template_name, context) admin.py from django.contrib import admin from .models import ResultQuery # Register your models here. admin.site.register(ResultQuery), home.html <h1>Search Your Result</h1> <form method="POST" action=" "> {% csrf_token %} {{ form }} <input type="submit" value="Submit"/> </form> Note: I would like to do the search and display the data, help me in HTML page also. screenshots for reference. -
Django : Why is my submit interest form not submitted. Did I write my view or template wrongly?
Django : Why is my submit interest form not submitted. Did I write my view or template wrongly? Based on the view I wrote, I dont even get redirected after I click on submit. And when i return to the home page, i Receive a message from here messages.warning(request, 'Something went wrong. Please try again..', extra_tags='wronginterest') which is why I believe it is because the form is not valid thats why it is not submitting. but wth why is it not valid?? Thanks views.py def submit_interest_view(request, slug): user = request.user blog_post = BlogPost.objects.get(slug=slug) num_blogpost = BlogPost.objects.filter(author=request.user).count() if not user.is_authenticated: return redirect('must_authenticate') elif blog_post.author == request.user: return HttpResponse('You cannot submit interest to your own post.') interest_requests = Interest.objects.filter(interestsender=request.user, interestreceiver=blog_post.author) for interest_request in interest_requests: if interest_request.is_active: return HttpResponse('You have already submitted your interest to this post.') if request.method == 'POST': # use request.method == 'POST' to submit POST request (like submitting a form) form = SubmitInterestForm(request.POST, request.FILES) if form.is_valid(): obj = form.save(commit=False) author = Account.objects.get(email=user.email) # use get if you aim to get a single object not a queryset obj.author = author obj.blog_post = blog_post obj.save() messages.success(request, 'Your interests have been submitted', extra_tags='submittedinterest') context['success_message'] = "Updated" if request.META.get('HTTP_REFERER') == request.build_absolute_uri(reverse("HomeFeed:main")): return redirect(reverse("HomeFeed:main")) … -
Django DjangoFilterBackend filter with OR condition in url params?
I have following class. class PersonListView(generics.ListAPIView): serializer_class = PersonSerializer permission_class = permissions.IsAuthenticatedOrReadOnly filter_backends = (DjangoFilterBackend,) filterset_fields = { 'city': ['exact'], 'age': ['gte', 'lte', 'exact', 'gt', 'lt'], 'param_1': ['exact'], 'param_2': ['exact'], 'param_3': ['exact'], 'param_4': ['exact'], 'param_5': ['exact'], } How to perfom filter with OR condition in ulr params? For example following url http://127.0.0.1:8000/api/persons/all?city=Novosibirsk&param_1=25 searches records with city Novosibirsk AND param_1 = 25. But i want to filter with OR condition. -
How do I capture the state of an object in Django?
I have developed a web app in Django to record sales in a retail store. I have the following two models in my project: class Product(models.Model): code = models.CharField(max_length=256) name = models.CharField(max_length=256) description = models.CharField(max_length=2048) cost_price = models.DecimalField(max_digits=8, decimal_places=2) retail_price = models.DecimalField(max_digits=8, decimal_places=2) class Sale(models.Model): date = models.DateTimeField(default=timezone.now) product = models.ForeignKey(Product, on_delete=models.CASCADE) The problem I'm having is that when I edit the price on the product, it will also affect past sales of that product. This is because the product is a foreign key on the sale model. What is the best method to ensure that all sales are not affected by any edits on the product? I thought about adding a price field on the sale model to ensure that the price remains static, like so: class Sale(models.Model): date = models.DateTimeField(default=timezone.now) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=8, decimal_places=2) However, I'm not sure if this is the best solution, it seems hard coded in a way. I would appreciate any advice. -
Is react or any front end needed with good django project?
I had started making a social webapp using django...and ofcourse i did it but when i look back at my code its very lengthy i have used ajax everyehere i dont have to reload the page like (like,comment,rating)... is there any good option in django rather than writing too much of javascript or do i need to use react...(What about django async ?) or the only way is using (django rest framework and react) please let me know because i am thinking like it will be more tool than tecnique if i learn both -
Django Celery create task with JS microservice
Hello I have a Django app running celery, and I'm trying to add tasks to the queue using a microservice in JS. When I add the task though Django everything works fine, but when I use JS i get this error: [2021-01-05 19:39:55,982: WARNING/MainProcess] Received and deleted unknown message. Wrong destination?!? The full contents of the message body was: body: '{"expires":null,"utc":true,"args":[5456,2878],"chord":null,"callbacks":null,"errbacks":null,"taskset":null,"id":"1a361c85-2209-4ffa-95c2-ee2e4855155e","retries":0,"task":"config.celery.debug_task","timelimit":[null,null],"eta":null,"kwargs":{}}' (244b) {content_type:None content_encoding:None delivery_info:{'sqs_message': {'MessageId': '7b7d2948-c069-4f8b-9fdc-9c068d52f463', 'ReceiptHandle': 'AQEBxhqW2sRWf+Z851fw7nqRX6MQFVcTfjH5xqiIgYIiMa3AN3R235VxhM8pM7mcByw3eOZ3Y7kH5oZ+noFVzfjSllgnoh8idB/V7WWY2urNHKJrQadRT5cf4NcUVkFmB8+d2rLiAXuuyqpGbEMvmx1Dn49/5C3Fx8Eq+eUyB1oeilIrCqfMvIkG/yX5TdedxM9B2VBThZ/XtHqrgYCkJvEt9ozssM0f+INRHUrpVQMYCmUX9aTWeWljrTOapMTg27M6aie6HaDQxLK0FJvZUNr2d0uJhZ4C2qRGWrSo2VpD7QK7pslltZ12PVHKPw9X+cBGdWwJrdh5I0fBITuoy+CUUnybDekz668jJnsf1gcmpx8cBoVrMLocPi753g2klGf++mbFeL7yjENzb1YqZrrfvg==', 'MD5OfBody': '9bb39da667d1e840f8532a74a8dcecaa', 'Body': 'eyJleHBpcmVzIjpudWxsLCJ1dGMiOnRydWUsImFyZ3MiOls1NDU2LDI4NzhdLCJjaG9yZCI6bnVsbCwiY2FsbGJhY2tzIjpudWxsLCJlcnJiYWNrcyI6bnVsbCwidGFza3NldCI6bnVsbCwiaWQiOiIxYTM2MWM4NS0yMjA5LTRmZmEtOTVjMi1lZTJlNDg1NTE1NWUiLCJyZXRyaWVzIjowLCJ0YXNrIjoiY29uZmlnLmNlbGVyeS5kZWJ1Z190YXNrIiwidGltZWxpbWl0IjpbbnVsbCxudWxsXSwiZXRhIjpudWxsLCJrd2FyZ3MiOnt9fQ=='}, 'sqs_queue': 'SQS_QUEUE_URL_HERE'} headers={}} I am using this code to send the msg: let taskId = uuidv4(); let result = { "expires": null, "utc": true, "args": [5456, 2878], "chord": null, "callbacks": null, "errbacks": null, "taskset": null, "id": taskId, "retries": 0, "task": "config.celery.debug_task", "timelimit": [null, null], "eta": null, "kwargs": {} } const client = new SQSClient({ region: "eu-west-3", credentialDefaultProvider: myCredentialProvider }); const send = new SendMessageCommand({ // use wrangler secrets to provide this global variable QueueUrl: "SQS_QUEUE_URL_HERE", MessageBody: Buffer.from(JSON.stringify(result)).toString("base64") }); let resultSQS = client.send(send); I debugged the django task payload to copy it, so I'm sending the same data it needs, but getting this error. Anyone knows if I'm missing something? Thanks -
how to store google signin details into database dbsqlite3 in python django, details includes token id,name,maild
It is not able to store details i get from google signin into db sqlite table.how to insert google signin datas this into dbsqlite in python django,details include token id,name,email id.please help me to do this. 0 const fillValues = () => { const welcome = document.getElementById("welcome"); let url_string = window.location.href; // to get current window location path let url = new URL(url_string); // convert the string as a new url let details = url.searchParams.get("details"); // for getting parameters from url details = JSON.parse(details); // convert string to object let image = document.getElementById("userImg").src = details.imgUrl; welcome.textContent = "Heyy "+details.name + ",login is successfull. Your Email is :" + details.email + ". And your Id is " + details.id; }; window.onload = fillValues; <head> <meta name="google-signin-scope" content="profile email"> <meta name="google-signin-client_id" content="119401361204-mvi8rs8iv0kpff5c731v5ie2m7go00lr.apps.googleusercontent.com"> <script src="https://apis.google.com/js/platform.js" async defer></script> </head> <body> <div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div> <script> function onSignIn(googleUser) { // Useful data for your client-side scripts: var profile = googleUser.getBasicProfile(); console.log("ID: " + profile.getId()); // Don't send this directly to your server! console.log('Full Name: ' + profile.getName()); console.log('Given Name: ' + profile.getGivenName()); console.log('Family Name: ' + profile.getFamilyName()); console.log("Image URL: " + profile.getImageUrl()); console.log("Email: " + profile.getEmail()); // The ID token you need to pass to …