Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to change the alias of the username in rest_framework_simplejwt using TokenObtainPairSerializer class?
I'm working on a project where user can register using his mobile no and password( after verifying with otp) what i'm doing is inside username field i'm saving user's phone no. as username is a mandatory field. And I'm using simple_jwt to get access token and refresh token. Everything is working fine urls.py from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns =[ path('register', RegisterView.as_view() ), path('otp/send', SendOtpView.as_view() ), path('otp/verify', VerifyOtpView.as_view() ), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] instead of creating a loginSerializer i'm using rest_framework_simplejwt inbuild class TokenObtainPairView But when i go to the url auth/api/token/ it ask me for username and password, which is confusing as a user . how can i change the name of the username to phone. I don't have any idea how to do it as I'm new to the djangorestframework serializers.py from rest_framework_simplejwt.serializers import TokenObtainPairSerializer class LoginSerializer(TokenObtainPairSerializer): password = serializers.CharField(max_length=65, min_length=8, write_only=True) **phone = serializers.CharField(max_length=20, source='username')** class Meta: model = User fields = ['phone', 'password'] I tried doing this but then it add on another field with the name phone instead of replacing username. I even don't know whether it will work or not . -
Filtering by parameters using django-filters does not work
Why does django-filters stop working with this design? class Ads(generics.ListCreateAPIView): queryset = Ad.objects.all().order_by('id') serializer_class = AdSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = ProductFilter def list(self, request): queryset = self.get_queryset() serializer = AdSerializer(queryset, many=True) return Response({'info': serializer.data}) But if you change the Response, then everything works? return Response(serializer.data) -
Passing values from python to html with django in views.py does not work
Hello I am following a django tutorial and the tutorial (FreeCodeCamp btw, they deserve to be noticed more) showed how to make a simple word counter in django. Now the thing is: While rendering the html file he passes some data to it like this: def counter(request): words = request.GET['text'] numberOfWords = len(words.split()) return render(request, 'counter.html', {'amount_of_words': int(numberOfWords)}) (I noticed that after publishing it seems like there is not the right spacing for functions, there actually is) enter image description here For the youtuber it works really fine, but for me it seems there is no way to display the data. in the html file i put this: the number of words is {{amount_of_words}} Which is exactly the same thing the tutorial guy did. Even if I add proper html boilerplate it doesn't seem to work -
Can't find the file from views.py
I am stuck with a really weird problem. I have a file called: "test.txt". It is in the same directory with views.py. But I can't read it... FileNotFoundError. But if I create read_file.py in the same directory with views.py and test.txt, it works absolutely fine. What is wrong with views? Is this some sort of restriction by Django? This code works on read_file, doesn't work on views.py: fkey = open("test.txt", "rb") key = fkey.read() -
How to make bulk_updates in Django using Queryset
Here I am trying to do bulk updates in Django: Problem: In a model, there is a column name position whose value changes according to the drag and drop of the record position. so I am creating the Queryset for that, but not getting the required result, I can update the value of the particular id that got dragged but according to that need to update further makes little tricky using Queryset. Example: id name position 1 anil 1 2 ABC 2 3 XYZ 3 4 def 4 now if I drag id 1 to 4th place then I need to shift else by position - 1, Like: id name position 2 ABC 1 3 XYZ 2 4 def 3 1 anil 4 for this, I was using Queryset of bulk_update but not getting any correct way to do that, please let me know the best way to make update the positions. might be I elaborated on the question too long, but I posted this query thrice, in hope that now I will get the required result. Thanks in Advance -
error while redirecting one page to other in django
Basically, from and to both page have parameters so how can I redirect to page with parameters? if request.method == "POST": if request.POST.get('firstname') and request.POST.get('lastname') and request.POST.get('addln1') and request.POST.get('addln2') and request.POST.get('country') and request.POST.get('city') and request.POST.get('zip') and request.POST.get('smsno') and request.POST.get('whtspno') and request.POST.get('email') and request.POST.get('deptnm') and request.POST.get('brdctlst'): saverecord = AddContact() saverecord.f_name = request.POST.get('firstname') saverecord.l_name = request.POST.get('lastname') -
Unabe to load Dynamic images using loop counter in django
I am unable to load th image using loop counter. Its loading the page http://localhost:8000/static/images/png%7B%7Bforloop.counter%7D%7D.png instead of http://localhost:8000/static/images/png1.png http://localhost:8000/static/images/png2.png def html(request): # template = loader.get_template('index.html') # return HttpResponse(template.render()) params = {'movie':['Dr Strange','Shamsheera']} return render(request, 'index.html',params) <table style="width:100%"> {% for m in movie %} <tr> <td width="30%"><img src="{% static 'images/png{{forloop.counter}}.png' %}" alt="{{forloop.counter}}"></td> <td width="20%">{{m}}</td> <td width="50%">Lorem ipsum dolor sit amet consectetur adipisicing elit. Numquam explicabo asperiores est nostrum mollitia dignissimos unde sapiente quos deserunt eveniet placeat beatae neque incidunt quia nulla itaque voluptatum earum, repudiandae enim cum fugiat nisi magnam dolorem? Deserunt odit, repellat eius qui asperiores adipisci soluta blanditiis inventore dignissimos est et nesciunt porro, iusto, ex at consectetur obcaecati unde! Dolorem rerum veniam mollitia, provident, sunt officiis maxime maiores atque cumque consequatur quidem molestias amet ullam? Iure pariatur, tempora voluptatem sint, quidem eius vel nemo eveniet eaque unde doloremque. Adipisci, maiores corrupti, ut debitis, error odio omnis odit id ratione enim minima a!</td> </tr> {% endfor %} </table> -
Django csv upload to db works but throws error
I have created an app named customer within a project named Website using django. I have created a csv upload in the admin area which is connected to the Postgres db. An error occurs when I upload the CSV returning: Exception Type: IndexError Exception Value: list index out of range However the CSV file is still added to the db but the error screen is displayed. Even more strangely if I a notepad doc as csv containing the data and upload that I get no error until I try to upload a second data set. If I save an excel doc as csv I get the error. Where am I going wrong ? Models.py class customer(models.Model): name = models.CharField(max_length=50, blank=True) balance = models.CharField(max_length=120, blank=True) def __str__(self): return self.name Admin.py from django.contrib import admin from django.urls import path from django.shortcuts import render, redirect from .models import customer from django import forms from django.contrib import messages from django.http import HttpResponseRedirect from django.urls import reverse from import_export import resources class data(resources.ModelResource): class Meta: model = customer class CsvImportForm(forms.Form): csv_upload = forms.FileField() class CustomerAdmin(admin.ModelAdmin): list_display = ('name', 'balance',) def get_urls(self): urls = super().get_urls() new_urls = [path('upload-csv/', self.upload_csv), ] return new_urls + urls def upload_csv(self, … -
How to load sql dump in a containerized django docker which depends on postgres
I am running a Django container on docker which depends on Postgres. Now the issue is, when I try to load the postgresql docker-compose up cat /tmp/dump.sql | sudo docker exec -i <container_id> psql -U <user> -d <database_name> This imports the first few tables and gives me a lot of errors on the terminal An example constraint "table_id" for relation "table_name" already exists Another example null value in column "column_name" violates not-null constraint Another one insert or update on table "table_1" violates foreign key constraint "table_id" I wanted to know is this even the right way to import this data. Plus I cant seem to drop the database as it is already being used by django. Note: I tried with volumes where I imported the db with postgresql. But everytime I run django, the database gets reset. I am guessing it has something to do with the migrations, but I can't touch that part. -
Tests with DRF ApiClient and DummyCache backend fail with UpdateError when try to save session
I test my view, which returns data about the previous session. Test with request factory works well. def test_session_view(self, rf): """Retrieve user token. path: /auth/session/ request: None respond: {token: str} """ url = reverse('get_session') view = SessionView.as_view() user_id = '589d1bac-d935-4160-92ce-b18170f35188' token: str = 'cl5aml1wh0000bh022o5em2re' request = rf.get(url) session_key = None engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore(session_key) request.session.update({ 'token': token, 'user_id': user_id, 'tenant_id': None }) request.session.save() response = view(request).render() assert response.status_code == 200 assert UserSessionFetchResponse(**response.data) But if I use DRF ApiClient test fails with UpdateError: ...django/contrib/sessions/backends/cache.py:62: in save raise UpdateError E django.contrib.sessions.backends.base.UpdateError This is the failing test: def test_retrieve_saved_session(self, api_client): """Fetches token from db.""" endpoint = reverse('get_session') # настройка условий user_id = '589d1bac-d935-4160-92ce-b18170f35188' token: str = 'cl5aml1wh0000bh022o5em2re' tenant_id: str = 'a1bd988a-9c52-4f97-bfac-9478d58cb0c3' client = api_client() client = set_api_client_defaults( client=client, ) session = client.session session.update({ 'token': token, 'user_id': user_id, 'tenant_id': tenant_id }) session.save() response: 'Response' = client.get( path=endpoint, ) assert response.status_code == 200 assert response.data['token'] == token assert UserSessionFetchResponse(**response.data) "api_client" is a fixture: @pytest.fixture() def api_client() -> Type[APIClient]: return APIClient Relevant settings: SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_CACHE_ALIAS = 'default' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } Manual tests and tests with request factory work vell. I do something wrong with ApiClient. Django … -
Double authentication in rest api
I am trying to get the rest API data in python using the request module. I am using double authentication in my API. When I run the code, I got error 401 but this is working perfectly on postman import requests response = requests.get('http://localhost:8285/x/1/mindie?C=dfghdh&SDate=01-05-2022&EDate=02-05-2022', headers={'Authorization': 'Basic dweeytdvgccsbj','Authorization': 'Basic fhgvecdjfvnhi'}) s = response.json() print(response) -
How to add SVG object in HTML?
I am following some examples of d3.js to plot graphs. For reference here is the link. Following is the code where I've used the LineChart function to build the plot. With Django as backend. {% load static %} <html> <script src="https://d3js.org/d3.v6.js"></script> <body> <h1> Hello! </h1> <div id="chart"></div> </body> <script> // set the dimensions and margins of the graph const margin = {top: 10, right: 30, bottom: 30, left: 60}, width = 460 - margin.left - margin.right, height = 400 - margin.top - margin.bottom; // append the svg object to the body of the page const svg = d3.select("#chart") .append("chart") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", `translate(${margin.left},${margin.top})`); // Copyright 2021 Observable, Inc. // Released under the ISC license. // https://observablehq.com/@d3/line-chart function LineChart(data, { x = ([x]) => x, // given d in data, returns the (temporal) x-value y = ([, y]) => y, // given d in data, returns the (quantitative) y-value defined, // for gaps in data curve = d3.curveLinear, // method of interpolation between points marginTop = 20, // top margin, in pixels marginRight = 30, // right margin, in pixels marginBottom = 30, // bottom margin, in pixels marginLeft = … -
Long running tasks is cancelled - Celery5.2.6
I have a project hosted in Digital Ocean in a Basic Droplet with 2 GB Ram. In my local machine, the long-running task runs between 8-10 minutes and is still successful.However in Digital Ocean droplets, often times the celery will not succeed in the long-running task. Current celery - celery 5.2.6 I have two configurations in supervisor Running the celery worker celery -A myproject worker -l info Running the celery beat celery -A myproject beat -l info This is the message from celeryd.log CPendingDeprecationWarning: In Celery 5.1 we introduced an optional breaking change which on connection, loss cancels all currently executed tasks with late acknowledgment enabled. These tasks cannot be acknowledged as the connection is gone, and the tasks are automatically redelivered back to the queue. You can enable this behavior using the worker_cancel_long_running_tasks_on_connection_loss setting. In Celery 5.1 it is set to False by default. The setting will be set to True by default in Celery 6.0. warnings.warn(CANCEL_TASKS_BY_DEFAULT, CPendingDeprecationWarning) [2022-07-07 04:25:36,998: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 2.00 seconds... (1/100) [2022-07-07 04:25:39,066: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 4.00 seconds... … -
Celery redis result backend type conversion
We have been using redis as a celery backend for a lot of time. Recently, we decided to store some json data in it . So here comes the problem: after retrieving result from celery data through AsyncResult(task_id) data such as {True:10,False:1} becomes {1:10,0:1}. Probably because redis has no boolean type in it's core. Keeping results with boolean keys is crucial for our system. I've tried to add CELERY_RESULT_SERIALIZER = 'json' into config with no effect. Is there any solution for this? -
How do i get the ID of the current form in Django Admin
i'm using admin.py in django and i want to know how can i get my current id from the form just for customize the page. Anyone can help me please? -
Django 403 Error while using POST method through Front end ( Angular Js )
views.py class ExtendUserSession(MiddlewareMixin): """ Extend authenticated user's sessions so they don't have to log back in next 15 minutes (set by Django's default `SESSION_COOKIE_AGE` setting). """ def process_request(self, request): # Only extend the session for auth'd users if request.user.is_authenticated: reason = CsrfViewMiddleware('get_response').process_view(request, None, (), {}) if reason: # process_view returns HTTPException pass else: # process_view returns None - No error on HTTP request from CSRF middleware verification request.session.set_expiry(86400) settings.py CORS_ORIGIN_WHITELIST = [ 'http://localhost:8000', #I have changed the localhost as in my local ip. so 8000 is backend and 8080 is frontend port 'http://localhost:8080', ] # A list of origins that are allowed to make cross-site HTTP requests to your Django application. CSRF_TRUSTED_ORIGINS = [ 'http://localhost:8000', 'http://localhost:8080', ] CSRF_WHITELIST_ORIGINS = ['localhost:8000','localhost:8080'] # SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' # SESSION_COOKIE_NAME='sessionid' SESSION_COOKIE_PATH='/' #default / # SESSION_COOKIE_SECURE=True#default False SESSION_COOKIE_SECURE=False # SESSION_COOKIE_DOMAIN='localhost:8080' #default None SESSION_COOKIE_DOMAIN= None SESSION_COOKIE_HTTPONLY=False # default is True SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_COOKIE_AGE = 86400 CSRF_COOKIE_NAME='X-CSRFToken' CSRF_COOKIE_AGE=86400 CSRF_COOKIE_DOMAIN=None CSRF_COOKIE_HTTPONLY=False CSRF_COOKIE_PATH='/' CSRF_COOKIE_SECURE=False I'm able to get post method from POSTMAN for eg: But while trying through Front-end this is the error I'll be getting Is there any settings I have to change for making it accepting request through FrontEnd -
Having trouble updating data in CRUD using Serializers
I am having trouble updating my data in CRUD operation while using Serializers in the sub category model.Category and sub category are connected using foreign keys.I have been trying see where I am going wrong in terms of my code but I am unable to figure it out Update function def edit_sub_categories(request,id): if request.method == 'GET': print('GET',id) editsubcategories = SUBCategories.objects.filter(id=id).first() s= SUBCategoriesSerializer(editsubcategories) category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict, many=True) hm = {"SUBCategories":s.data,"context": category.data} # print(category.data) return render(request,'polls/edit_sub_categories.html',hm) else: print('POST',id) editsubcategories = {} d = SUBCategories.objects.filter(id=id).first() if d: editsubcategories['sub_categories_name']=request.POST.get('sub_categories_name') editsubcategories['sub_categories_description']=request.POST.get('sub_categories_description') # print(editsubcategories) form = SUBCategoriesSerializer(d,data=editsubcategories) if form.is_valid(): form.save() print('form error',form.errors) messages.success(request,'Record Updated Successfully...!:)') return redirect('sub_categories:show_sub_categories') else: return redirect("sub_categories:show_sub_categories") below is the html code <form method="POST" > {% csrf_token %} <table> <thead> <tr> <td>Categories Name</td> <td> <select name="category_name" id=""> {% for c in context %} <option value="{{c.category_name}}">{{c.category_name}}</option> {% endfor %} </select> </td> </tr> <tr> <td>Sub Categories Name</td> <td><input type="text" name="sub_categories_name" value="{{SUBCategories.sub_categories_name}}"></td> </tr> <tr> <td>Sub Categories Description</td> <td><input type="text" name="sub_categories_description" value="{{SUBCategories.sub_categories_description}}"></td> </tr> <tr> <td> <a href="{% url 'sub_categories:show_sub_categories' %}"> <button type="submit" class="btn btn-success" value="update record"> <i class="fa-solid fa-database"> Update Value</i> </button> </a> </td> <td> {% if messages %} {% for mess in messages %} <b style="color:green;"> {{mess}} </b> {% endfor %} {% endif … -
How would I disable a button with the context value
How would I use the context value to check if the currently logged in user has the same team and it's not null and the is_edit field is true. {% if request.user.is_edit and team==request.user.team%} produces Could not parse the remainder: '==request.user.team' from 'team==request.user.team' edit.html {% extends 'base.html' %} {% block title %}Add{% endblock %} {% block content %} <h1 class="cardHeader">Edit Page</h1> <div class="card"> <div class="container"> <h1>Edit team member</h1> <p>Edit contact info,location and role</p> </div> <form method = "POST" action="" enctype="multipart/form-data"> {% csrf_token %} {{ editProfileForm.as_p }} <input type="submit" name="editProfileForm" value="Save"> <!-- Check if the user who can delete the team member is the same team and had admin role? --> {% if request.user.is_edit and team==request.user.team%} <input type="submit" name="deleteProfileForm" value="Delete"> {% endif %} </form> </div> {% endblock %} views.py def edit(request,user_id): context={} try: user = Profile.objects.get(id=user_id) print(user,user_id) except Exception as e: print(str(e)) return redirect('home') context['team']=user.team #Currently logged in user has to have is_edit? and be the same team #if request.user.team != user.team and request.user.is_edit: #return redirect('home') if request.method=="POST": if "editProfileForm" in request.POST: print('Editing') edit_profile_form = UserProfileForm(request.POST or None,instance=user) if edit_profile_form.is_valid(): edit_profile_form.save() print(edit_profile_form) return redirect('home') else: context['editProfileForm'] = edit_profile_form return render(request,'edit.html',context) if "deleteProfileForm" in request.POST: print('Deleting') try: user.delete() #messages.success(request, "The user is … -
Django- Retrieving and normalising data from mongodb
In django project, I have connected with mongodb without creating models. I just writing data directly into collection using python code. All the collections are working independently. For example, I have employee and employment collection(one employee has multiple employment). There is no foreignkey relationship between employee and employment. # employee response {{"emp_id": "S101", "emp_name": "Kim", "dob": "1995-12-30"} {"emp_id": "S102", "emp_name": "Sasi", "dob": "2000-12-01"} {"emp_id": "S103", "emp_name": "Shakthi", "dob": "2001-01-01"}} # employment response {{"emp_id": "S101", "employment_type": "contract", "status": "terminated", "date": "2017-04-05"}, {"emp_id": "S101", "employment_type": "contract", "status": "pending", "date": "2018-07-09"}, {"emp_id": "S102", "employment_type": "Permanent", "status": "active","date": "2017-04-05"}, {"emp_id": "S103", "employment_type": "Permanent", "status": "active", "date": "2017-04-05"}} when I retrieve employee details I would like to get response like below, { {{"emp_id": "S101", "emp_name": "Kim", "dob": "1995-12-30", "employment_status": {{"emp_id": "S101", "employment_type": "contract", "status": "terminated", "date": "2017-04-05"}, {"emp_id": "S101", "employment_type": "contract", "status": "pending", "date": "2018-07-09"}} {{"emp_id": "S102", "emp_name": "Sasi", "dob": "2000-12-01", "employment_status":{"emp_id": "S102", "employment_type": "Permanent", "status": "active","date": "2017-04-05"}}} } How can i achieve this? Thanks in advance. -
Unknow field by switching default login to email
Unknown field(s) (username) specified for Profile. Check fields/fieldsets/exclude attributes of class CustomUserAdmin. I have the above error I think it's due to how I switched email to the default login so username isn't viable anymore. I used readonly_fields=('username',) in admin.py it worked but I am not sure why it works. admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import UserProfileForm from .models import Profile class CustomUserAdmin(UserAdmin): add_form = UserProfileForm model = Profile list_display=('id','email','password','first_name','last_name','phone_number','is_edit','team') ordering = ('email',) pass admin.site.register(Profile, CustomUserAdmin) ##Maybe rework this later for better inclusion of all models. from django.apps import apps from django.contrib import admin class ListAdminMixin(object): def __init__(self, model, admin_site): self.list_display = [field.name for field in model._meta.fields] super(ListAdminMixin, self).__init__(model, admin_site) models = apps.get_models() for model in models: admin_class = type('AdminClass', (ListAdminMixin, admin.ModelAdmin), {}) try: admin.site.register(model, admin_class) except admin.sites.AlreadyRegistered: pass model.py from django.db import models from django.contrib.auth.models import AbstractUser from phonenumber_field.modelfields import PhoneNumberField import uuid from .managers import CustomUserManager class Team(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Profile(AbstractUser): username = None email = models.EmailField('email address', unique=True) # Here first_name = models.TextField(max_length=100, blank=True,null=True) last_name = models.TextField(max_length=100, blank=True,null=True) phone_number = PhoneNumberField(max_length=25, region='US') is_edit = models.BooleanField(default=False) team = models.ForeignKey(Team,on_delete=models.CASCADE,null=True, blank=True, default = None) USERNAME_FIELD = 'email' REQUIRED_FIELDS = … -
Data not getting updated in shopping CRUD operations
I am currently writing a shopping CRUD operation where Categories and SUB categories are connected via foreignkey and I am using serializers. I have written update function to edit the data ,however,the data in not getting updated despite writing the update function below is the edit and insert function of the sub_categories def edit_sub_categories(request,id): if request.method == 'GET': editsubcategories = SUBCategories.objects.filter(id=id).first() s= SUBCategoriesSerializer(editsubcategories) category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict, many=True) hm = {"SUBCategories":s.data,"context": category.data} # print(category.data) return render(request,'polls/edit_sub_categories.html',hm) else: editsubcategories = {} d = SUBCategories.objects.filter(id=id).first() if d: editsubcategories['sub_categories_name']=request.POST.get('sub_categories_name') editsubcategories['sub_categories_description']=request.POST.get('sub_categories_description') # print(editsubcategories) form = SUBCategoriesSerializer(d,data=editsubcategories) if form.is_valid(): form.save() # print("hkjk",form.data) print('form error',form.errors) messages.success(request,'Record Updated Successfully...!:)') return redirect('sub_categories:show_sub_categories') else: return redirect("sub_categories:show_sub_categories") def insert_sub_categories(request): if request.method == "POST": form = SUBCategoriesSerializer(data=request.POST) if form.is_valid(): form.save() messages.success(request, "Record Updated Successfully...!:)") return redirect("sub_categories:show_sub_categories") category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict, many=True) hm = {"context": category.data} return render(request, "polls/insert_sub_categories.html", hm) html code of edit page <form method="POST" > {% csrf_token %} <table> <!--content-table--> <thead> <tr> <td>Sub Categories ID</td> <td><input type="text" name="id" value="{{SUBCategories.id}}" readonly></td> </tr> <tr> <td>Categories Name</td> <td> <!-- <input type="text" name="category_name" value="{{SUBCategories.category_name}}"> --> <select name="category_name" id=""> {% for c in context %} <option value="{{c.id}}">{{c.category_name}}</option> {% endfor %} </select> </td> </tr> <tr> <td>Sub Categories Name</td> <td><input type="text" name="sub_categories_name" … -
How to convert raw sql to Django ORM?
I have two models wp_8_posts and wp_8_postmeta and I have sql query to run on this model. sql_query = "SELECT a.ID, a.post_title, a.post_name, a.post_date, b.meta_value, c.meta_value, f.guid FROM wp_8_posts a, wp_8_postmeta b, wp_8_postmeta c, wp_8_postmeta d, wp_8_postmeta e, wp_8_posts f WHERE a.post_type = 'book' AND a.ID = b.post_id AND b.meta_key='book_pub' AND a.ID = c.post_id AND c.meta_key='book_url' AND a.ID = d.post_id AND d.meta_key='ex_category' AND d.meta_value LIKE '%"var1"%' AND a.ID = e.post_id AND e.meta_key='book_img' AND e.meta_value = f.ID ORDER BY a.post_date DESC LIMIT var2;" There is no relation(foreign key etc.) defined in both the models. I want to use Django ORM, How can I convert this? -
My k8s liveness probe isn't setting the Host
I'm trying to deploy a Django app with startup and liveness probes configured. As it's a Django app, I need the Host header on the probes to match something permitted in my ALLOWED_HOSTS. As my probes are both httpGet checks, the simplest solution seems like it would be to use the httpHeaders field as suggested in the kubernetes docs. This seems to work for the startupProbe, however it's not working for the livenessProbe. Sanitized version of my probes: livenessProbe: httpGet: httpHeaders: - name: Host value: k8s-probes path: /health/liveness port: http scheme: HTTP startupProbe: httpGet: httpHeaders: - name: Host value: k8s-probes path: /health/ port: http scheme: HTTP When the pod startups up, I see 200 responses to the initial startup probes, then once the liveness probe starts, I get 400 responses with the error that the pod IP address isn't in ALLOWED_HOSTS, indicating k8s isn't setting the Host header I've defined for the liveness probe. -
Django destroy and keep newly created testing database
I know we could use --keepdb when running manage.py test to keep the test databases, but when i have a new migration, the old DB need to be destroyed to create new one. Is there any way to destroy the old DB AND keep it after test completed ? -
Cannot assign "'": "" must be a "" instance. ModelChoiceField
I have a form where a user can select the title of an object and then save it but when I do hit save, I get an error. I am very certain that this problem is because I am using ModelChoiceField which returns ids of objects instead of the instances of that object. So, I have two models: InvoiceModel class Invoice(models.Model): line_one = models.ForeignKey(Inventory, on_delete=models.CASCADE, related_name='+', verbose_name="Line 1", blank=True, null=True, default='') line_one_quantity = models.IntegerField('Quantity', default=0, blank=True, null=True) line_one_unit_price = models.IntegerField('Unit Price(₹)', default=0, blank=True, null=True) line_one_total_price = models.IntegerField('Line Total(₹)', default=0, blank=True, null=True) Invoice.line_one is referenced to Inventory.product_number. InventoryModel: class Inventory(models.Model): product_number = models.IntegerField(primary_key=True) product = models.TextField(max_length=3000, default='', blank=True, null=True) title = models.CharField('Title', max_length=120, default='', blank=True, null=True, unique=True) amount = models.IntegerField('Unit Price', default=0, blank=True, null=True) def __str__(self): return self.title InvoiceForm: class InvoiceForm(forms.ModelForm): line_one = forms.ModelChoiceField(queryset=Inventory.objects.values_list('title', flat=True), label="Line 1") line_one_unit_price = forms.CharField(widget=forms.Select, label="Unit Price(₹)") class Meta: model = Invoice fields = ['line_one',#...] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['line_one_unit_price'].widget.choices = [(i.amount, i.amount) for i in Inventory.objects.all()] I actually have 10 lines, [i.e., line_two, etc..] but I am just pasting the code for line_one here for simplicity. I also want only the amount of the object selected in line_one to be displayed in line_one_unit_price. …