Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pagination data in vuejs by vue-pagination-2
I want to paginate data that comes from django api server. my problem is I don't know how to change api next page in vue-pagination-2 package. This html template: <tr v-for="(item, key) in users" :key="key"> <td>{{ item.username }}</td> </tr> <pagination v-model="page" :perPage="perPage" :records="count" @paginate="users"/> and my script section: export default { data() { return { page: 1, count: 0, perPage: 10, users: [], } }, methods: { fetchData() { Api.get(USERS).then((resp) => { this.count = resp.data.count; return this.users = resp.data.results; }).catch(() => { loginRedirect(this.$router) }); } }, mounted() { this.fetchData(); } } and response I got: count: 11 next: "http://192.168.1.10:8000/api/v1/users/?page=2" previous: null results: (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} -
How to gracefully exit and remove docker-compose services after issuing CTRL-C?
I have a docker-compose service that runs django using gunicorn in an entrypoint shell script. When I issue CTRL-C after the docker-compose stack has been started, the web and nginx services do not gracefully exit and are not deleted. How do I configure the docker environment so that the services are removed when a CTRL-C is issued? I have tried using stop_signal: SIGINT but the result is the same. Any ideas? docker-compose log after CTRL-C issued ^CGracefully stopping... (press Ctrl+C again to force) Killing nginx ... done Killing web ... done docker containers after CTRL-C is issued CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 4b2f7db95c90 nginx:alpine "/docker-entrypoint.…" 5 minutes ago Exited (137) 5 minutes ago nginx cdf3084a8382 myimage "./docker-entrypoint…" 5 minutes ago Exited (137) 5 minutes ago web Dockerfile # # Use poetry to build wheel and install dependencies into a virtual environment. # This will store the dependencies during compile docker stage. # In run stage copy the virtual environment to the final image. This will reduce the # image size. # # Install poetry using pip, to allow version pinning. Use --ignore-installed to avoid # dependency conflicts with poetry. # # --------------------------------------------------------------------------------------- ## # base: Configure python … -
django not switching to Postres when deploying to Heroku
I deployed my django app with Heroku and I am having troubles with connecting to Postgres. If I run python manage.py createsuperuser after running heroku ps:exec --app produceit (so I am inside the Heroku instance's terminal), it says that I successfully created a superuser but nothing is written into Heroku Postgress DB...so I can't login into neither /admin nor my app. I therefore run heroku ps:exec --app produceit python manage.py shell from mywebsite.settings import DATABASES and it seems like the settings.py has the variable DATABASE still connected to sqlite (see pic) Funny enough, if I hardcode an admin into Heroku's Postgres DB, loging and then create an instance of one of my models from the app itself (like I create a blog's post)...it actually writes into Postgres and I see it on the Front End. So basically it's like the app is working on Postgress BUT the terminal is running on SQLite. What can I do? My settings are below """ Django settings for mywebsite project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # … -
Django RF and Gunicorn - extrange behavior in response time
SETUP: Azure cloud Virtual M. nº1: (Debian 8 cores) Docker with application (API) Django Rest with Gunicorn (17 sync workers) Virtual M nº2: (Debian 4 cores) DB MySQL Note: The APi receives a user call from a user, makes 4 django ORM queries to MySQL (Only selects) and returns OK or error. We are launching 220 requests per second from an Apache JMeter for an unlimited time. These calls are 100% successful and take an average of 1200 ms, We control the workload of the 8 CPUs and they work at + -50% Until here everything is perfect, according to our requirements. Trouble: After an X Time and suddenly, the response time almost triples reaching 4000 ms on average. and the CPUs go to 100% (htop showing half of each bar red) (Calls are still 100% successful) Our analysis after hundreds of structured tests: Time X usually depends on the time that has elapsed since the last time it failed(triplication of time), normally it is half that time. Example 1: If at this moment it is failing (that is, it takes 4000 ms) and I stop the test for 2 minutes, the test starts well and fails again after a … -
django drf variations for products ecommerce
i am building an eCommerce Website, and i stuck on productvariations. and i need help. serializers.py """ def get_variations(self, obj): data = [] bar = Barcode.objects.select_related('product').filter(product_id=obj.pk) for b in bar.iterator(): main_variation = b.product_variation.first() rest_variations = b.product_variation.exclude(pk=main_variation.pk) dic = {main_variation.headline:[{i.headline:{"code":i.barcode_set.first().code}} for i in rest_variations]} data.append(dic) return data """ i get data like this: all i want to do is for green create variation with code: janika128green and for 5inch code:janika1285inch and for both code: janika128green5inch is there any way to do it? -
Django session. sum with conditions return 0
this is a data: product1:{ 'quantity': 1, 'regular_price': Decimal('1200.00'), 'shipping_cost': '300.00', 'shop': 'ca097a5b-4ca6-420a-955a-71a417afed5a', } product2:{ 'quantity': 2, 'regular_price': Decimal('200.00'), 'shipping_cost': '300.00', 'shop': 'ca097a5b-4ca6-420a-955a-71a417afed5a', } product3:{ 'quantity': 1, 'regular_price': Decimal('550.00'), 'shipping_cost': '300.00', 'shop': 'ca097c5b-4ba6-520a-955a-71a417afse2b', } this is a function: def get_shipping_price(self): return sum(Decimal(item['shipping_cost']) for item in self.cart.values() if item['shop'] not in item.values()) I want to sum the shipping price of the product, only if the shop does not exist in the cart, if instead there is already a product of this shop, consider it 0 -
Is the server running on host "localhost" (127.0.0.1) - Reposting
Please do not close my question again if you are not sure that the answer provide to others fit my case. I am deploying a django app for the first time to Heroku. I used the following: heroku run python manage.py migrate and it returns : Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? In my settings.py i have : DATABASES = { 'default': dj_database_url.config( default=config('DATABASE_URL') ) } and at the bottom : try: from .local_settings import * except ImportError: pass in the local_settings.py I have : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'newapp_development', 'USER': 'postgres', 'PASSWORD': '#####', 'HOST': 'localhost', 'PORT': '5432', } } Do you know why is the error message please ? Also, note that local_settings is added to . gitignore. I did a few search on search engine and the responses that i found did not work for me … -
how to display error message in django formset with ajax
i'm trying to submitting django formset using ajax call , but the problem is i cant iterate the error fields and give each error to its form and field ! class Vistor(models.Model): admin = models.ForeignKey(User,on_delete=models.PROTECT) full_name = models.CharField(max_length=150) dob = models.DateField(max_length=14) city = models.ForeignKey(City,on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint(fields=['full_name','dob','city'],name='full_information') ] and also i've used ModelForm class VistorForm(forms.ModelForm): city = forms.ModelChoiceField( queryset=City.objects.all()) class Meta: model = Vistor fields = [ 'full_name','dob','city' ] VistorFormSet = modelformset_factory(Vistor,form=VistorForm,extra=1,can_delete=True) non_fields_error defined as __all__ in ajax call error messages @login_required def add_vistor(request): formset = VistorFormSet(queryset=Vistor.objects.none()) if request.is_ajax() and request.method == 'POST': formset = VistorFormSet(request.POST) if formset.is_valid(): for form in formset: obj = form.save(commit=False) if form.cleaned_data !={}: obj.admin = request.user obj.save() formset = VistorFormSet(queryset=City.objects.none()) return JsonResponse({'success':'success'}) else: return JsonResponse({'success':False,'error_msg':formset.errors,'error_code':'invalid'}) return render(request,'vistors/add_vistor.html',{'formset':formset}) my html + js //for adding new form $('#addButton').click(function() { var form_dex1 = $('#id_form-TOTAL_FORMS').val(); $('#form').append($('#formset').html().replace(/__prefix__/g,form_dex1)); $('#id_form-TOTAL_FORMS').val(parseInt(form_dex1) + 1); }); //ajax submit form const form = document.getElementById('post-form') form.addEventListener("submit",submitHandler); function submitHandler(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url 'vistors:add_vistor' %}', data : $('#post-form').serialize(), dataType: 'json', success: successFunction, }); } function successFunction(data) { console.log(data.success=='success') if (data.success=='success') { alertify.success("added") form.reset(); } else if(data.error_code=='invalid'){ console.log(data.error_msg.length) for(var i=0; i < data.error_msg.length;i++){ console.log(data.error_msg) if(key == 'full_name'){ document.getElementById('full_name_error').removeAttribute('hidden') document.getElementById('full_name_error').innerHTML = data.error_msg[key][0] } … -
How to use binding in Django Raw SQL
How can I use a single variable to binding in more than one filter in Django SQL? What I want: I defined the variable: date I want to use the same information in the SQL WHERE Clausures: CUR_DATE, ACHIEVED_DATE def kpiMonitoring(self): with connections['db'].cursor()as cursor: import time date = time.strftime('%Y%m%d') cursor.execute(""" SELECT * FROM TABLE1 WHERE CUR_DATE = date AND ACHIEVED_DATE = date """,[date]) row = dictfetchall(cursor) cursor.close() return row I can do it by this way, but this solution is not scalable: def kpiMonitoring(self): with connections['db'].cursor()as cursor: import time date = time.strftime('%Y%m%d') date2 = date cursor.execute(""" SELECT * FROM TABLE1 WHERE CUR_DATE = %s AND ACHIEVED_DATE = %s """,[date, date2]) row = dictfetchall(cursor) cursor.close() return row Is there another way to do it? -
wsgi directory in gunicorn service file not recognised
I want some help to fix this issue. myproject.wsgi in gunicorn is not recognised. Content of gunicorn file is: -
How i put empty file in database using django rest framework
Hi everyone my filefield posted successfully and successfully save in database but i want to put my filefield empty in database. How i can do this in Django Rest framework. My models.py file: This my model file class Blog(models.Model): id = models.AutoField(primary_key=True) title = models.TextField(max_length = 50) author = models.TextField(max_length = 50) description = models.TextField() date = models.DateField(auto_now=True) time = models.TimeField(default=timezone.now) image = models.FileField(null=True, verbose_name="", validators=[validate_allfile_extension]) # time = models.DateTimeField(default=datetime.now) # image = models.ImageField(null=True, verbose_name="", validators=[validate_allfile_extension]) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title MY serializers.py file: THis is my serializers file include with model Blog class UpdateBlogSerializer(serializers.ModelSerializer): title = serializers.CharField(max_length=128, required=True, error_messages={'blank': "Please provide title"} ) author = serializers.CharField(max_length=128, required=True, error_messages={'blank': "Please provide author"}) description = serializers.CharField(max_length=128, required=True, error_messages={'blank': "Please provide description"}) image = serializers.FileField(required=False) # user_id = serializers.SerializerMethodField('get_user_id') id = serializers.SerializerMethodField('get_id') date = serializers.SerializerMethodField('get_date') time = serializers.SerializerMethodField('get_time') class Meta: model = Blog # fields = ["id","title","author","description","image","date","time","user_id",] fields = ["id","title","author","description","image","date","time",] # Adding additional fields to a modelserializer using SerializerMethodField def get_user_id(self, user_id): user_id = self.context['request'].user.id return user_id def get_id(self, blog): id = blog.id return id def get_date(self, blog): date = blog.date return date def get_time(self, blog): time = blog.time return time My views.py file: THis is my views file … -
Page not found (404) Request Method
i have created 2 apps under tubers, tubers is my project , my apps are travello and register, i have index.html file in travello where when user click it need to navigate to register form but unforunately i getting path error, i tried my to fix but i'm unable to understand it please help me out :) note: when i'm trying to go to register page through my html it is throwing me error but when i try it directly with /register it is showing me the form , i don't understand how to fix it :( -
After successful login , dashboard gives error user is null (cannot read property of null) , when I refresh the page it fetches the user information
Project is based on React-Django . I am new to react and I created login functionality and fetch user details functionality using react-redux, Here is the code for login here is the constant file export const USER_LOGIN_REQUEST = 'USER_LOGIN_REQUEST' export const USER_LOGIN_SUCCESS = 'USER_LOGIN_SUCCESS' export const USER_LOGIN_FAIL = 'USER_LOGIN_FAIL' export const USER_LOGOUT = 'USER_LOGOUT' Here is the reducer file import { USER_LOGIN_REQUEST, USER_LOGIN_SUCCESS, USER_LOGIN_FAIL, USER_LOGOUT, } from "../constants/userConstants"; export const userLoginReducer = (state = {}, action) => { switch(action.type){ case USER_LOGIN_REQUEST: return {loading:true} case USER_LOGIN_SUCCESS: return {loading:false, userInfo: action.payload} case USER_LOGIN_FAIL: return {loading:false, error: action.payload} case USER_LOGOUT: return {} default: return state } } Here is user action file import { USER_LOGIN_REQUEST, USER_LOGIN_SUCCESS, USER_LOGIN_FAIL, USER_LOGOUT, } from "../constants/userConstants"; import axios from 'axios' export const login = (username, password) => async (dispatch) => { try{ dispatch({ type:USER_LOGIN_REQUEST }) const config = { headers : { 'Content-type':'application/json' } } const { data } = await axios.post( '/api/user/login/', {'username':username, 'password':password}, config ) dispatch({ type :USER_LOGIN_SUCCESS, payload: data }) localStorage.setItem('userInfo', JSON.stringify(data)) }catch(error){ dispatch({ type : USER_LOGIN_FAIL, payload : error.response && error.response.data.detail? error.response.data.detail: error.message, }) } } export const logout = () => (dispatch) => { localStorage.removeItem('userInfo') dispatch({type:USER_LOGOUT}) } now the login interface import React, … -
Can't pass Aray from react to django
I m trying to get an array from react frontend (stored in local storage) to my view class in django but i'm getting this error: In console: GET http://127.0.0.1:8000/api/quiz/multiple/ 500 (Internal Server Error) Django LOGS: for quiz in quizzes: TypeError: 'NoneType' object is not iterable ERROR:django.server:"GET /api/quiz/multiple/ HTTP/1.1" 500 20064 Here's how i store the data in the LocalStorage: localStorage.setItem('quizzes', JSON.stringify(quizList)); history.push('/start') And here's how i get it from local storage and pass it to the django using axios: export default function QuizPage() { const [DataState,setDataState] = useState([]); const storedQuizzes = JSON.parse(localStorage.getItem("quizzes")) useEffect(() => { axiosInstance .get(`quiz/multiple/`, { quizzes: storedQuizzes }).then((res) => { setDataState(res.data); }) .catch((function (error) { console.log(error) })); }, [setDataState]); and, finally, that's my django view: class MultipleQuizView(APIView): permission_classes = [IsAuthenticated] def get(self,request): questionsList = [] quizzes = request.data.get('quizzes') for quiz in quizzes: currentQuiz = Quiz.objects.get(url=quiz) quizSerializer = QuizSerializerForMultipleQuizzes(currentQuiz) question = Question.objects.filter(quiz__url=quiz) questionSerializer = QuestionSerializer(question, many=True) quizSerializerData = quizSerializer.data.copy() quizSerializerData["questions"]=questionSerializer.data questionsList.append(quizSerializerData) if questionsList: return Response(questionsList) else: return Response(status=status.HTTP_400_BAD_REQUEST) I'm pretty sure the problem isn't from my view class because i tested it using Postman and it works without any problem. -
Image is rotated when reading from byte in Django InMemoryUploadedFile
I'm using Django ImageField for user to upload image. I want to read the image directly from InMemoryUploadedFile byte to ndarray for processing. However, some of the images that appeared upright in my folder will be rotated. My images are all mobile phone camera photos. I suspect it is because of the exif info that cause the rotation. I checked the exif info and it shows <Orientation.LEFT_BOTTOM: 8>. This is same as what I get as the image is rotated 270 degree counter-clockwise. Is there anyway I can read the image from byte to ndarray in upright orientation as per what I see in file explorer? Below is how I read the image in view.py upload_file_1 = request.FILES.get('image1', None) image_1 = cv2.imdecode(np.frombuffer(upload_file_1.file.read(), np.uint8), cv2.IMREAD_UNCHANGED) p/s: I don't want to save the raw upload image to media folder before postprocessing. -
List view data class based VIEW confuse
class CoursesListView(View): template_name = 'courses/courses_list.html' queryset = CoursersModels.objects.all() # def get_queryset(self): # return self.queryset def get(self,request, *args, **kwargs): queryset = CoursersModels.objects.all() context = { #"object_list": self.queryset #If self.queryset is called, the page will not be updated after refresh "object_list": queryset#Refresh normally after calling } return render(request,self.template_name,context) I am very confused about this code,When I insert a piece of data into the database,If "object_list": self.queryset is called, the page will not be updated after refresh,You must restart django to update the display normally,but when I run "object_list": queryset everything is normal . Thanks in advance. -
Can't count PostgeSQL requests in django
I know how to do it in db shell, but I need to do it in the code in which file and where should I place print(len(connection)). Maybe I need to do smth else? (I am using postgreSQL) -
How to use action decorator to update many to one entries from initial model?
Disclaimer: I am fairly new to DRF. With that being said, I am trying to update a model object (the simple part), then update several entries from another model belonging to the first model object. Basically, I have three models stock, stock entry and inventory. Where stock entry looks like this: class StockEntry(models.Model): stock = models.ForeignKey(Stock, related_name='entries', on_delete=models.CASCADE, null=True, blank=True) item = models.ForeignKey(Inventory, on_delete=models.PROTECT) amount = models.IntegerField(default=0) # if 0 will assume does not apply So I am trying to update two columns on Stock and when the update succeeds, it should update all stock-entries tied to the Stock. So I tried using viewsets, which I couldn't figure out how to override. Then I decided to use action decorators. Here is my attempt: @action(detail=True, methods=['patch'], url_path='serial-update') def serial_update(self, request, pk=None): try: queryset = models.Stock.objects.all() stock = get_object_or_404(queryset, pk=pk) stock.invoice = request.data['invoice'] stock.confirmed = request.data['confirmed'] for a in stock.entries.all(): item = models.Inventory.objects.filter(pk=a.item.id)[0] item.amount += a.amount item.save() stock.save() return Response(status=status.HTTP_200_OK) except Exception as e: return Response(status=status.HTTP_400_BAD_REQUEST) While I was trying with the viewset, I successfully updated the stock but not the entries, while here is the vice versa. The entries update, but not the stock. The issue seems to be coming from … -
Django forms, html tags are showing up as text on front end
<div class="form-group"> <span class="form-label">First Name</span> <input class="form-control" type="{{ form.firstname }}" placeholder="Enter Employees First Name"> </div> How do I fix this? All the placeholder values and the ">" are being shown as text. What am I doing wrong? -
Directory indexes are not allowed here. How to fix this?
I am using VueJS for fronend and Django for backend. I changed the conf of Vuejs such that when we run npm run build the compiled files goes to static/dist directory of Django. I also added the urls in urls.py as shown from django.contrib import admin from django.urls import path from django.conf.urls import url, include from django.views.generic import TemplateView from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('users/',include('users.urls')), path('accounts/',include('django.contrib.auth.urls')), path('',TemplateView.as_view(template_name='index.html')), ] urlpatterns = urlpatterns + staticfiles_urlpatterns() when I go to http://127.0.0.1:8000 index .js is returned which contains the VueJS index file. So the above url goes to http://127.0.0.1:8000/static/dist and the server runs normally. But when I reload the page I am getting the below error. Page not found (404) Directory indexes are not allowed here. Request Method: GET Request URL: http://127.0.0.1:8000/static/ Raised by: django.contrib.staticfiles.views.serve Any idea on how to resolve this error? settings.py: """ Django settings for e_cell_server project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - … -
Image передается некорректно при request put django
Картинка получена через форму: class CustomUploadFileForm(forms.Form): file = forms.FileField()) Помимо картинок через эту же форму загружаются и файлы любых других форматов. Я пытаюсь загрузить картинку, полученную из формы, через API OpenstackSwift Swift, картинка загружается, но при просмотре этой же картинки после загрузки вместо картинки я вижу черный фон с небольшим белым квадратом, файлы остальных форматов (pdf, text и тд) загружаются и просматриваются нормально. В чем может быть ошибка? Прилагаю сам джанговский запрос. class CustomUploadView(FormView): ... form_class = ObjectStorageCreateObjectForm def form_valid(self, form): ... file: InMemoryUploadedFile = self.request.FILES['file'] headers = {'Content-Type': file.content_type, 'X-Auth-Token': ...} requests.request( method='PUT', url=..., headers=headers, verify=..., files={'file': file} ) return super().form_valid(form) -
How to retrieve model fields in Django ModelForm?
I'm trying to retrieve 'category' and 'EN_name' fields as a ChoiceField into my ModelForm, but I'm not getting the choices that I put in my model, it's showing me empty select field with no choices. What I want is to create a form that takes: 'category', 'EN_route' and 'EN_name' from Medicine model, 'notes' from Prescription model, 'dose', 'dose_unit', 'frequency' and 'duration' from MedicinePrescription model These are my model.py classes: This is Medicine model class: class Medicine(models.Model): CATEGORY = ( ('All', 'All'), ('Vitamins', 'Vitamins'), ('Analgesics', 'Analgesics'), ('Antacids', 'Antacids'), ('Antianxiety', 'Antianxiety'), ('Antifungals', 'Antifungals'), ('Antihypertensives', 'Antihypertensives'), ('Antipyretics', 'Antipyretics'), ) category = models.CharField(max_length=100, null=True, choices=CATEGORY) stock = models.PositiveIntegerField(null=True) dose = models.FloatField(null=True) EN_name = models.CharField(max_length=100, null=True) EN_brand = models.CharField(max_length=100, null=True) EN_formula = models.CharField(max_length=100, null=True) EN_doseUnit = models.CharField(max_length=50, null=True) EN_route = models.CharField(max_length=50, null=True) AR_name = models.CharField(max_length=100, null=True) AR_brand = models.CharField(max_length=100, null=True) AR_formula = models.CharField(max_length=100, null=True) AR_doseUnit = models.CharField(max_length=50, null=True) AR_route = models.CharField(max_length=50, null=True) def __str__(self): return self.EN_name Prescription model class: class Prescription(models.Model): STATUS = ( ('Active', 'Active'), ('Inactive', 'Inactive'), ) visit = models.ForeignKey(Visit, null=True, on_delete=models.SET_NULL) status = models.CharField(max_length=100, choices=STATUS) expiration_date = models.DateTimeField(auto_now_add=True, null=True) notes = models.CharField(max_length=1000, null=True) def __str__(self): return self.status This is MedicinePrescription model class: class MedicinePrescription(models.Model): medicine = models.ForeignKey(Medicine, null=True, on_delete=SET_NULL) prescription = models.ForeignKey( … -
Django : How to mock queryset chain filter method call?
I am new to python and Django, I have the following method def sample(self, queryset, key_list, row): if(key1 in key_list) queryset = queryset.filter(key1=row.key1) if(key2 in key_list) queryset = queryset.filter(key2=row.key2) if(key3 in key_list) queryset = queryset.filter(key3=row.key3) return queryset I have to write Unit test for this method, I want to mock queryset.filter chain. I initially thought of returning the mocked method when filter is called @patch(mypro.models.objects) def test_sample(self, mock_obj): sample = Mock() sample.key1 = 'Test' sample.key2 = 'Test' mock_obj.filter.return_value = sample actual_output = self.samplepro.sample(mock_obj, key_list, row) self.assertequal(sample.key1, mock_obj.key1) self.assertequal(sample.key2, mock_obj.key2) But I get assertion error, is there any way to mock queryset filter chain ? This is not the actual source code, but a simplified version. -
Django Radio buttons
I was trying to understand how to apply forms.ChoiceField to a html Radio button. Ive managed to create a form to show either yes or no as an answer but I dont know how to apply it to my exhisting HTML radio buttons: And so I want to attach the form to that HTML page, and when i select yes or no i want it to update the model. So far this is what i get in my page: But I cant even click on it. So my model is the following: Model: class datas(models.Model): country = models.CharField(_('country'), max_length=200, default='') qs_login = models.CharField(_('qs_login'), max_length=200, default='') Status = models.CharField(_('Status'), max_length=200, default='') seller_id = models.CharField(_('seller_id'), max_length=200, default='') Task_ID = models.CharField(_('Task_ID'), max_length=200, default='', primary_key=True) associate_queue = models.CharField(_('associate_queue'), max_length=200, default='') associate = models.CharField(_('associate'), max_length=200, default='') metric_wk_no = models.CharField(_('associate'), max_length=200, default='') associate_action = models.CharField(_('associate_action'), max_length=200, default='') correct_associate_action = models.CharField(_('correct associate action'), max_length=200, default='') Associate_Key_Driver = models.CharField(_('Associate_Key_Driver'), max_length=200, default='') Sub_Key_driver = models.CharField(_('country'), max_length=200, default='') Defect_Area_Associate = models.CharField(_('Defect Area Associate'), max_length=200, default='') QA_Comments_on_Associate_Action = models.CharField(_('country'), max_length=400, default='') Metric_name = models.CharField(_('Metric name'), max_length=200, default='') # SIV investigator_task = models.CharField(_('investigator_task'), max_length=200, default='') investigator_queue = models.CharField(_('investigator_queue'), max_length=200, default='') investigator = models.CharField(_('investigator'), max_length=200, default='') verification_action = models.CharField(_('verification_action'), max_length=200, default='') correct_investigator_action = … -
request.session in different views using curl
I have a backend built with Django. Problem:- I am sending phone number via POST and storing in session via request.session['phone_number'] in one view and trying to get the same in another view but facing Key Error What could be the issue? Also via Postman its working fine but via curl or axios I'm getting this error.