Django and Python "Questions and answers", page 1620

11.08.2021
Why is this (Django) 'filter' function not working?

I need help to figure out why the filtering doesn't work. It worked until I decided to add pagination using Django official docs and code comes from here.) I tested the query results in …

11.08.2021
The price should change well when adjusting the quantity, but it doesn't change when it's one

The price should change well when adjusting the quantity, but it doesn't change when it's one. What's the problem? It works correctly from two. I want to modify this code and sleep comfortably. Great developers, please help me. script …

11.08.2021
Invalid block tag on line 30: 'update_variable', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?

I want to declare a variable and update its value inside a template in django.How can I do that?

11.08.2021
Convert mysql query to django orm with requires same table

I am trying to convert sql code to django orm code. I don't want to use python raw function SELECT u.`user_id` as 'dp_id', cp.`email` as 'dp_email', cp.`name` as 'dp_name', u2.`user_id` as 'cm_id', cp2.`email` as 'cm_email', cp2.`name` as 'cm_name' FROM `user` …

11.08.2021
Cannot assign "'1'": "Groups.profile" must be a "Profile" instance

I have Profile Model that have instance model user.. I am trying to create group using form. that group model have Profile model as instance, so how do I select authenticated user automatic to create group, I getting confused... This …

11.08.2021
How to auto-check Google approved scopes on OAuth page?

I've been fully verified for the Google Calendar API as shown in the image below... ...but when users hit my OAuth consent screen on the webflow, the box is …

11.08.2021
How can I do to exclude some null values using queryset django?

I have a queryset B and I want to exclude null values so I did that : B.exclude(mycolumn__in[0, {"total": 0}]) because sometimes I can have JSON Field with null values. But I noticed that I can have that cases …

11.08.2021
How to fetch data from AWS S3 bucket using Django Rest API

I'm trying to fetch my media files from a django rest api using a jquery async function, this function worked fine in development but now I've deployed the app to Heroku and my media files are being served by an …

11.08.2021
How to show UpdateView form below field to be updated

I trying to learn web-dev with django. As an exercise I am trying to build something where you have a document and within each document you have blocks of text that you can update (like a wiki but much more …

11.08.2021
AWS Beanstalk Django Cannot Connect to RDS Instance Because Wrong Private IP Resolved from RDS Endpoint

My setup: AWS RDS MySQL Instance located in a custom VPC (Private Subnet) AWS Beanstalk Django app located in the same custom VPC (Public Subnet) Beanstalk EC2 Private IP: 10.0.2.37 RDS Endpoint: stockpeektestdbcachekafka-trading-db.cxapiv8ipcaj.ap-southeast-1.rds.amazonaws.com RDS Private IP after using telnet …

11.08.2021
Python Django init.py

Here is the errors I am facing for the last 2 days. I try many things but not work. Kindly help me out. First the project was run, after that it is not running.enter image description here …

11.08.2021
Django - Why I got Boolean result when I try to get data from the DB?

My view: def add_word(request): current_date = timezone.now() english = request.POST.get("the_word_in_english", False) hebrew = request.POST.get("the_word_in_hebrew", False) context = request.POST.get("How_To_Remember", False) name = request.POST.get("your_name", False) Words.objects.create(pub_date=current_date, English_word=english, Hebrew_word=hebrew,How_To_Remember=context, Name=name) return HttpResponseRedirect("/polls/") {% if search %} {% for item in word %} <p> …

11.08.2021
How to perform periodic tasks within Django?

I have a web app on Django platform. I have a method within views.py: def task(): print("my task") how can I run it every day once? I need a very simple solution and it should be independent of other …

11.08.2021
How to Foreign_Key value instead of id in django rest framework without read_only=True

I working on project with drf where I'm getting serializer data as follows which is absolutely fine: { "message": "Updated Successfully", "status": 200, "errors": {}, "data": { "id": 8, "user": 2, "item": 1, "quantity": 4, "created_at": "2021-08-11T13:49:27.391939Z", "updated_at": "2021-08-11T13:51:07.229794Z" } …

11.08.2021
How to represent text in the JavaScript input box?

How do I print text in the input box? No matter how hard I try, there is no change. I want to put the JavaScript I wrote in the input box. html " <div class=\"total_p\" style='margin-top:30px; margin-left: -2px;'>\n" + …

11.08.2021
TypeError: issubclass() arg 1 must be a class, strartapp

I have been working on a Django project. And when I try to use python3 manage.py startapp newletters I have such an error: File "/home/evgenia/PycharmProjects/CarDealer/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/evgenia/PycharmProjects/CarDealer/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/evgenia/PycharmProjects/CarDealer/venv/lib/python3.8/site-packages/django/apps/registry.py", …

11.08.2021
Django SQL query to ORM implementation involving Joins and Group By

This query should return the total sum of (quantity - qty_fulfilled) grouped by product_id. I'm stuck trying to convert this postgres sql query into an ORM query. This sql query works, but get_queryset() method in the Admin models does not …

11.08.2021
DRF - APIView and Serializing a model with multiple foreign Keys(User)

How to save multiple foreign keys(User) data? models class HireProfessional(models.Model): hireBy = models.ForeignKey(User, related_name='owner', on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") hire_start_date_time = models.DateTimeField(default=timezone.now) hire_end_date_time = models.DateTimeField(default=timezone.now) seriliazer class HireProfessionalSerializer(serializers.ModelSerializer): class Meta: model = HireProfessional fields = '__all__' views …

11.08.2021
Django filters icontains with __in lookup

Similar to this question: django icontains with __in lookup I am attempting to filter a single field with multiple values using the django-filters package. For example, I have a model Content with field paragraph. I want to return the …

11.08.2021
Nginx is rendering the wrong website. Does anyone know why?

My website 1 Nginx .conf file is rendering website 2 on my server. So both websites render website 2. I want website 1 to render a Django website. Website 2 is just a normal HTML website. The files for both …

11.08.2021
How to change color help text using crispy tags

I am trying to use cripsy forms for a django website, everything works fine but as you can see my background isn’t white,but blue so the help text doesn’t stand out How can I change the color of the helper …

11.08.2021
Unable to make correct migrations in Django

I cannot make correct migrations with one specific fields image_two in my Django Project. I have also configured Django-Rest and all this is connected to AWS. Endpoint is looking alright and I am getting correct url from image_one and image_two. …

11.08.2021
Отправка форма с сайта на django в telegram

Html <form action="form.py"> <h3>ОСТАВИТЬ ФОРМУ</h3> <input type="text" name="uname" value="как вас зовут" onblur="if(this.value.length == 0) this.value = 'как вас зовут'" onfocus="if(this.value == 'как вас зовут') this.value = '' "/><br> <input type="text" name="conta"value="контакт" onblur="if(this.value.length == 0) this.value = 'контакт'" onfocus="if(this.value == 'контакт') …

11.08.2021
Django filtering models in Foreign Key

Models.py class AdmissionStudent(models.Model): studentlabel = models.CharField(max_length = 100, null = False, blank = False) def __str__(self): return self.studentlabel class AdmissionRequirement(models.Model): requirementstudent = models.ForeignKey(AdmissionStudent, on_delete = models.CASCADE, null = False, blank = False) requirementparagraph = models.TextField(null = False, blank = False) …

11.08.2021
Convert QuerySet into List in Django for ModelMultipleChoiceField

TIMESLOT_LIST = ( (5, '09:00 – 09:30'), (9, '09:30 – 10:00'), (2, '10:00 – 10:30'), ) class AvailabilitiesForm(forms.Form): time_slot = forms.ModelMultipleChoiceField(queryset = None, widget=forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): date = kwargs.pop('date') super(AvailabilitiesForm, self).__init__(*args, **kwargs) #choices = getChoices(letter) self.fields['time_slot'].queryset = Appointment.objects.filter(date …

11.08.2021
How to update item quantity on django ecommerce project

I am trying to update the quantity of my cart when I use click the add to cart button. I have been trying to figure out the logic behind it but cannot seem to get it. I believe under my …

11.08.2021
После активации виртуального окружения название самого окружения не появилось перед дерикторией в консоли. Python Django

После активации виртуального окружения название самого окружения не появилось перед дерикторией в консоли VS CODE хотя должно было. Сначала я ввел в консоль python -m venv SHOP. Потом SHOP\Scripts\activate.bat . Никаких ошибок не последовало, но виртуальное окружение (SHOP) не появилось. …

11.08.2021
How to float text in the input box in javascript?

I want to text the code I wrote in JavaScript into the input box. However, there is a problem that the input box is not outputting text. The input box I want to print is in html. The content is …

11.08.2021
Is there a way to prevent Django from trimming leading white space in a text field?

Is there a way to prevent Django from trimming leading white space in models.TextField? I've been scouring the docs and haven't found anything. The database I'm using is PSQL. Any guidance would be appreciated. An answer made me aware there …

11.08.2021
Is there a better way to get the created object?

I have this code and I want to store this created user and question in a variable in one line instead of doing it this weird way, is this even possible?: if UserProfile.objects.filter(discord_id=request.data['author_id']).exists(): profile = UserProfile.objects.get(discord_id=request.data['author_id']) else: x = …

11.08.2021
Django как сохранить изменения в БД сделанные в ходе запуска тестов?

Имею несколько моделей и тест. class MetricTestCase(TestCase): def setUp(self) -> None: pass def test_creation(self) -> None: f1 = File(study_uid='1.2.34354545.565767.78787878', path="/s3/ext/ds/123.dcm", side='L', projection='CC') f1.save() ds1 = Dataset(name="ds1") ds1.save() ds1.file_list.add(f1) m1 = Metric(calc_type='b3m', metric_type='rsm', auc=1, recall=1, specificity=1, accuracy=1, npr=1, npv=1, ppr=np.nan, ppv=1, …

11.08.2021
Django duplicated query causing slow loading

I'm having trouble finding a solution for duplicated queries, I tried doing this. Code: for c in coupons: fname = Users.objects.filter( id=c['WhoReviewed']).values('first_name') lname = Users.objects.filter( id=c['WhoReviewed']).values('last_name') for f in fname: first = f['first_name'] for l in lname: last = l['last_name'] …

11.08.2021
How to fix NoReverseMatch error in Django for the getting and displaying user specific data in ListView

Hey I have a video sharing webapp project with basic CRUD operations in it. Any user after successful login can post any number of videos and after login the user is redirected to home page of another app inside the …

11.08.2021
How to display list of LANGUAGES in django template

I'm trying to show languages label list in my template , but it only shows the original name of the language my settings.py LANGUAGES = ( ('en', _('english uk')), ('ar', _('arabic uae')), ('fa', _('Persian')), ) my template <div class="snippet" …

11.08.2021
Dynamic form in django using choiceField

I'm building my first web app with django and am having a hard time figuring out how to use dynamic form in order to have diffent output for different selected choice. for example for my mesure choice qualitative, I want …

11.08.2021
How to get users back after deploying Django App to Heroku [duplicate]

I've deployed a React/Django app on Heroku and when I tried to login, I found out none of the users I had locally were present on the deployed App. I thought it could be that it didn't migrate so I …

11.08.2021
Filter objects of a manytomanyfield inside another model

I am a beginner programming learning django. I'm trying to build a contacts app much like google contacts. users have to log in to create contact groups and contacts. problem: when a user creates a group, it shows up in …

11.08.2021
How to change permission in Django view sub-class?

I have the following setup right now: class MyView(MyPermission1, MyPermission2, FormView): ... class MyChildView(MyView): ... The child view is inheriting from the parent, but I want to remove MyPermission1 and MyPermission2 from it and apply another class called MyPermissionChild. …

11.08.2021
How to get the value of the foreign key field and count or other aggregation operations?

I have two models. How can i count and show results like below: Male 235 Female 240 Other 10 My models.py class Student(models.Model): name = models.CharField(max_length = 200) gender = models.ForeignKey(gender, on_delete = models.SET_NULL, null = True, blank=True) def __str__(self): …

11.08.2021
Django render field json in template

I'm doing a project using the Django 3.1.2, this project needs a register logs. I created a model for logs: class Log(models.Model): Usuario = models.CharField('Usuário que fez a ação', max_length=100) Perfil = models.SmallIntegerField( 'Quem está sofrendo a ação', choices=PERFIL_CHOICE) Acao …