Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: unsupported operand type(s) for +: 'DateField' and 'datetime.timedelta'
In my model there are start_date_time, end_date_time, period and period_type fields, where end_date_time must be equal to sum of start_date_time and timedelta. And in my case timedelta's day is equal to period and period_type is one of days/months/years/. Here are my codes: models.py: class PeriodTypeEnum(models.IntegerChoices): Years = 'years' Months = 'months' Days = 'days' class Policy(models.Model): policy_type = models.ForeignKey('PolicyType', on_delete=models.CASCADE) blank = models.OneToOneField('blank_app.Blank', on_delete=models.CASCADE) period = models.IntegerField() period_type = models.IntegerField(choices=PeriodTypeEnum.choices) start_date_time = models.DateField(blank=True, null=True) end_date_time = models.DateField(default = start_date_time + timedelta(days=1), blank=True, null=True) P.S: in end_date_time field, timedelta(days + x) - x must be equal to period. -
Django slow load and PosgresSQL optimization
I have build in app in Django and upload it to Heruko. i am using SQLPostgres of amazon. and I have installed the Newrelic plugin and Django Debug Tool. my problem is slow loading pages all over my app: i will show you part of my code of a very slow loading page. can you please point me on what I am doing wrong with my queries ? new relic: Django ToolBug: Views.py @login_required(login_url='login') def students(request): form = StudentForm() form.fields['desc'].widget.attrs['class'] = "form-control" form.fields['firstname'].widget.attrs['class'] = "form-control" form.fields['lastname'].widget.attrs['class'] = "form-control" form.fields['sid'].widget.attrs['class'] = "form-control" form.fields['studentclass'].widget.attrs['class'] = "form-control" form.fields['email'].widget.attrs['class'] = "form-control" form.fields['phone'].widget.attrs['class'] = "form-control" form.fields['main'].widget.attrs['class'] = "form-control" form.fields['submain1'].widget.attrs['class'] = "form-control" students = Student.objects.all() if request.method == "POST": form = StudentForm(request.POST) if form.is_valid(): form.save() return redirect('students') return render(request, "studentform/students.html", {"form": form, "students": students}) templete.html {% extends 'studentform/controlpanel.html' %} {% load static %} {% block content %} <div class="container"> <h1> תלמידים<a style="float: left; padding-left: 20px" href="{% url 'export_csv'%}"><img style="height: 35px;width: 35px" src="https://d1yjjnpx0p53s8.cloudfront.net/styles/logo-thumbnail/s3/072015/excel_0_0.png?itok=tetyiA_8"></a></h1> <div class="card shadow p-3 mb-5 bg-white rounded"> <div class="card-body "> <form id="students-form" method="POST"> <div class="row"> {% csrf_token %} {% for field in form %} {% if forloop.counter|divisibleby:"3" %} </div> <div style="padding-top: 10px" class="row"> {% endif %} <div class=" col-md-4 col-sm-12 "> <label >{{ field.label … -
why the django urls rendering wrong path?
I am in a wired situation, I have a project on which I am working for sometime now. Lately, I have started getting issues while I click on the login button on my web page. Below is the whole URLs entry: urlpatterns = [ path('', home, name='home'), path('contact/', contact, name='contact'), path("login/", login_user, name='login'), path("logout/", logout_user, name='logout'), path("register/", register_user, name='register'), path("complete_registration/", userprofileview, name='complete_registration'), path('profile1/', profile_page, name='profile1'), path('thank_you/', thank_you, name='thank_you'), path('about/', about, name='about'), path('editUserProfile/', editUserProfile, name='editUserProfile'), path('pass_edit/', passwordChange, name='pass_edit'), path('reset-password/', auth_views.PasswordResetView.as_view(template_name='authenticate\\password_reset_form.html' ), name='reset-password'), path('reset-password/done/', auth_views.PasswordResetDoneView.as_view( template_name='authenticate\\password_reset_done.html'), name='pwd_reset_done'), path('reset-password-confirm/<uid64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='authenticate\\password_reset_confirm.html'), name='pwd_reset_confirm'), path('reset-password/complete/', auth_views.PasswordResetCompleteView.as_view()) ] So, the issue is when I click on the "login" button on the landing page, the url that I see is as below: http://127.0.0.1:8000/web/login/ Which if one see the "login" url endpoint, I haven't configured it that way, and the error that I get is as below: TemplateDoesNotExist at /web/login/ registration/login.html Request Method: GET Request URL: http://127.0.0.1:8000/web/login/ Django Version: 3.0.8 Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Exception Location: C:\Users\amitesh.sahay\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader.py in select_template, line 47 Python Executable: C:\Users\amitesh.sahay\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.0 So, if I see my "login" method the error confuses me, below is the method from views.py def login_user(request): # Login Page if request.method == 'POST': username = request.POST['username'] … -
Recursive Nested Fields In Django Elasticsearch
I am using django rest framework for my web app Suppose that I want to store family tree hierarchy in a model like this: class People(models.Model): parent = models.ForeignKey('self', on_delete=models.SET_NULL, blank=True, null=True, related_name='children') name = models.CharField(default="", max_length=100) I made an Index Like This: people = Index('people') people.settings( number_of_shards=1, number_of_replicas=0 ) @registry.register_document @people.document class PeopleDocument(Document): children = fields.NestedField(properties={ 'name': fields.TextField() }) class Django: model = People fields = [ 'id', 'name' ] related_models = [People] def get_instances_from_related(self, people_instance): return people_instance.parent And I got a good result that in my Elasticsearch, now i have every family members with their list of children. But the issue is that the depth is only 1 and i can't have grandchildren or even further of any user like a recursive nestedfield to the end of tree. Is there any solution for this? -
Explain why able to create any instance variable for TestCase (django.test) class
I am currently following a django tutorial and am writing up tests. This was one of the test. def setUp(self): self.board = Board.objects.create(name='Django', description = 'Django Board.') url = reverse('home') self.response = self.client.get(url) From my understanding, self.response refers to an instance variable contained in the TestCase class but what I'm confused about is that I can access any made up instance variable and it'll still work? For e.g. I created: self.trial = "Hello" self.random = "Hi" And it stores these variables and I'm able to access them. I was wondering if someone could explain why? -
Python, bad practice to have same name on classes
I have multiple files like this in a django app. django-app ----views -------app_one.py -------app_two.py -------app_three.py Inside app_one.py i have code similar to this class AppOne: ... some methods ... class Data(AppOne): def post(request): class History(AppOne): def get(request): In app_two.py I would like to name my classes like this (Note the sub_classes have the same names as in app_one): class AppTwo: ... some methods ... class Data(AppTwo): def post(request): class History(AppTwo): def get(request): So, my question is this: This works fine, I can run the server etc. But is this a bad practice? Could I run into unexpected results because of this? The reason I want these specific names is because I use them inside Django admin a permissions thing. -
Using if else to get element if it is available in javascript and django
I am working on a django project(basic ecommerce website). I have a javascript file as follows: for (i=0;i<updateBtns.length;i++){ updateBtns[i].addEventListener('click',function(){ var productId=this.dataset.product var action=this.dataset.action var sizebox = document.getElementById("sizebox"); var size = sizebox.options[sizebox.selectedIndex].value; updateUserOrder(productId, action, size) }) } function updateUserOrder(productId,action,size){ console.log('User is logged In , sending data....') var url = "/update_single/" fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId,'action':action,'size':size}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data:',data) location.reload() }) } I send the data fetched by the above to my views.py. My problem is that If a product is already in cart for someone then in my html I show a button instead of the sizebox but then when I want to remove the product from cart It gives me error because it doesnt get any value from sizebox. I wanted to know whether I can use if else to get size box data if it is present and pass if sizebox is not present. -
HyperlinkedRelatedField Doesn't Return URL
My hyperlinked serializer doesn't return userurl. My serializer: class TokenSerializer(serializers.HyperlinkedModelSerializer): userurl = serializers.HyperlinkedRelatedField(view_name='user-detail', many=False, read_only=True) class Meta: model = Token fields = ('key', 'userurl') My output: { "key": "891e388399f2fcae016fe6887107034239041478" } My app's urls.py urlpatterns = [ path('users/<int:id>/', views.UserView.as_view(), name='user-detail') ] I expect to get but for some reason userurl is not showing up at all in my output. Any thoughts why and how I can make it work? { "key": "891e388399f2fcae016fe6887107034239041478", "userul": "http://127.0.0.1/api/accounts/users/29" } Any help will be appreciated. -
Django Error: app.models.DoesNotExist: User matching query does not exist
I am creating my custom user model for my web application This is the code I wrote for model in model.py model.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. # Custom User Manager class UserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError("Valid Email Address required.") if not username: raise ValueError("Valid username is Required.") user = self.model( email = self.normalize_email(email), username = self.get_by_natural_key(username) ) user.set_password(password) user.save(using = self._db) return user def create_superuser(self, email, username, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email = self.normalize_email(email), password=password, username= self.get_by_natural_key(username), ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user # Custom User Model class User(AbstractBaseUser): _id = models.AutoField email = models.EmailField(verbose_name='email', max_length=255, unique=True) username = models.CharField(verbose_name='username', max_length = 100, unique=True) name = models.CharField(max_length = 100) date_joined = models.DateTimeField(verbose_name="date-joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last-login", auto_now=True) category = models.CharField(max_length=50, default= "teacher") is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] object = UserManager() def __str__(self): return self.email return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True I … -
Why does Chain Filtering return only the first filtered queryset?
Assume that I have a queryset nums: nums = [1,2,3,4,5,6,7,8] The creator of nums 1 and 2 is: user1 The creator of nums 4, 5, and 6 is: user2 Then I have this code: queryset = nums.objects.all() queryset = queryset.filter(creator=user1) queryset = queryset.filter(creator=user2) Why does it only return 1,2 ? If I understood the docs correctly, it should return 1,2,4,5,6 -
How to Run Tests for Installed Django Apps Using Pytest
Using the traditional unit test, I can run tests for an installed Django app using the command: python manage.py test <name_of_the_installed_app> But this is not the case when using pytest as the test runner How do I run the tests of a third-party app that is included in Django settings installed apps using pytest? -
How to deploy Django Rest Framework backend + React web app?
I currently have a backend server built with Django Rest Framework and a frontend app built in React. I am looking at 2 ways to deploy this to a ubuntu server: Serving them on different servers/origins, where the frontend would make cross-origin API requests to the backend Having the backend serve static files for the frontend. Django's url routing system points go React's index.html I'm recently new to webdev, so I don't know which is the best method. I vaguely know if I were to go with the 2nd method, I would need nginx and gunicorn (maybe Docker?). Can anyone give me some advice? -
How to create a popup card for user (html, css, django)?
I want to create a popup card for user so anyone on website can see user firstname, lastname and email. As they click on user name they get a popup card of user with described information. -
Representing different "types" of the same object in Django?
I am trying to model something in Django and wondering how to do so. At my company, we are building a line of Business App where customers can send their data to different "Integrations", such as Salesforce. To do so, they need to give us a set of keys. Each Integration has a different set of data. I was thinking of modeling it like the following: class Integration(db.Model): name = models.CharField(...) settings = models.JSONField(...) Then it got me wondering why am I even storing the "type" of Integration in the Database anyway? I also lose the "type safety" of defining each instance's settings by doing it in settings instead of as a column on its own object. I could have objects like: class SalesforceIntegration(Integration): salesforce_setting_one = models.CharField(...) salesforce_setting_two = models.BooleanField(...) And so on and so forth. I am wondering what are the pros and cons of the above approach? I read this article: Modeling Polymorphism in Python, but I only got more confused. It seems like my fundamental problem is I am trying to use a table where each row is a subtype of a big type, and I'm wondering if it's appropriate to have that in a table at … -
how to translate this block of code to javascript?
I am trying to port this code into javascript to support my backend validation. however, I am not sure if javascript has any or isdigit() or comprehension lists in order to achieve this def clean_password1(self): password1 = self.cleaned_data.get('password1') special_characters = "[~\!@#\$%\^&\*\(\)_\+{}\":;,'\[\]]" if not any(char.isdigit() for char in password1): raise forms.ValidationError( 'Password must contain at least %(min_length)d digit.' % {'min_length': 2}) if not any(char.isalpha() for char in password1): raise forms.ValidationError( 'Password must contain at least %(min_length)d letter.' % {'min_length': 6}) if not any(char in special_characters for char in password1): raise forms.ValidationError( 'Password must contain at least %(min_length)d special character.' % {'min_length': 1}) if len(password1) < 8: raise forms.ValidationError( 'Password must contain at least %(min_length)d characters.' % {'min_length': 8}) javascript if (password.length < 8){ addErrorTo('password', data['message']['password1']); } -
How can I have a PDF file on my local machine uploaded and viewed in a Django app?
I have a PDF file saved in my local machine. I'd like to have it on my Django app for others to view it and download it. How can I go about it? -
Django: how to use the keyword static in admin.py
In Django template, I could use the configured static path as: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> how to use the same static keyword correctly in admin.py, as show below inside the img src? class CustomerAdmin(admin.ModelAdmin): list_display = ['customer_id', 'download_pdf', 'first_name', 'last_name'] def download_pdf(self, obj): return format_html(f"<a href='{obj.pk}/pdf' target='_blank'>" f"<img alt='PDF' src='{static}svg/document.svg'>" # this {static} has error f"</a>") -
Is there something who can help me see the user who's enrty on my site for login verification, intranet app Django
So i need to see the user who entered my site, because i do not want to use login, it's intranet and only persons from the firm have access so i only need to know who entered by the windows user? Is this possible? I am using Django as a framework and Python. I want to add for some users access levels and i want to see the user without him inputting it.Is there any way of seeing the user id? from what i have seen when i create a super user for admin it reads my Windows account name and ask me if i want to use it, how can i see someone else windows account id. Thank you for the answer in advance -
Django: How can I render my formsets without having every single field in a <p> (or any other) element?
I'm rendering my model formset in the following way: <form method="POST" class="note-form"> {{ formset.management_data }} {% csrf_token %} {{ formset.as_p}} <input type="submit" value="Save"> </form> However, this renders every single field in every form in a <p> element, which I don't want. It's unpacked like this: <form method="POST" class="note-form"> <input type="hidden" name="csrfmiddlewaretoken"...> <input type="hidden" name="form-TOTAL-FORMS"...> <input type="hidden" name="form-INITIAL-FORMS"...> <input type="hidden" name="form-MIN-NUM-FORMS"...> <input type="hidden" name="form-MAX-NUM-FORMS"...> <p> <textarea ...></textarea> </p> <p> <input ...> </p> <p> <input ...> </p> <p> <textarea ...></textarea> </p> ...and so on... </form> Instead, I want something that would be rendered like this <form method="POST" class="note-form"> <input type="hidden" name="csrfmiddlewaretoken"...> <input type="hidden" name="form-TOTAL-FORMS"...> <input type="hidden" name="form-INITIAL-FORMS"...> <input type="hidden" name="form-MIN-NUM-FORMS"...> <input type="hidden" name="form-MAX-NUM-FORMS"...> <div ...> <textarea ...></textarea> <input ...> <input ...> </div> <div ...> <textarea ...></textarea> <input ...> <input ...> </div> ....and so on.... That is, each single form in a div element. Now, I tried doing the following <form method="POST" class="note-form"> {{ formset.management_data }} {% csrf_token %} {% for form in formset %} <div> {{ form }} </div> {% endfor %} <input type="submit" value="Save"> </form> This renders the formset the way I want it. The problem with this is that, when I do it, the management data disappears and I get … -
Allow additional attributes, like placeholder text or icon, on model
I use modelforms in several places in my app, and have written custom bootstrap form rendering. It's working well, but I'd like to be able to add addon_before to some of my fields (example, for twitter_username i'd set addon_before='https://twitter.com/. I'd also like to specify icon classes and placeholder text for some fields. I know I can do this in the form rendering, but I render the same fields in several different forms, and I dont want to repeat the form settings. using the twitter_username example, is there a way to globally set wherever that field is used in a modelform, to include a set of attributes and values {'addon_before': 'https://twitter.com/', 'placeholder': '@username', 'icon': 'fa-twitter'} Would love any suggestions! -
Answer if you are a high school django developer [closed]
I was wondering today how many django developers there are currently that are in high school. I was thinking of starting a nonprofit group that created websites for small companies and such. But mainly focusing on high school developers (no matter the experience, I myself am somewhat a beginner). So if you are a high school django website developer, please answer to this, I am just curious if my idea is possible. -
I can't get values from div inside the form tag in Django
I am passing a context dictionary from view to the HTML template its rendering the values on the web page fine. These values are render in the div which is inside the form, I also have a submit button. My main purpose is that when I click on the button it get the values that I pass before in div back to the views and print in the terminal but its showing None in the terminal. Following is my code. view.py django.contrib.auth.models import auth from django.http import HttpResponse # Create your views here. from django.shortcuts import render,redirect def main_view(request): if request.method=='POST': company_name=request.POST.get('company_name'] employ_name=request.POST.get('employ_name') print(company_name) print(employ_name) return redirect('/') else: context={ 'company':"Rapidev", 'name':"Usama" } return render(request,'main.html',context) main.html <!DOCTYPE html> <html> <head> <style> body { background-color: lightblue; } h1 { color: white; text-align: center; } p { font-family: verdana; font-size: 20px; } </style> </head> <body> <form id="my_form" action="" method="POST"> {% csrf_token %} <div id="main_div"> <h1 id="company_name" >{{company}}</h1> <p id="employ_name" >{{name}}</p> </div> <button type="submit">Get Values</button> </form> </body> </html> -
Django REST CRUD for User. How can I save, change and get the native fields of the User object through the Account API?
I have a problem of create, update, read the data of the User object through the API of the Account. When I add, it does not save the first_name, second_name and other fields of the User object. Saves only username . How to make a full CRUD? How can I save, change and get the native fields of the User object through the Account API? models.py class Account(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, related_name="profile") description=models.TextField(blank=True) date_joined=models.DateTimeField(auto_now_add=True) updated_on=models.DateTimeField(auto_now=True) is_creator=models.BooleanField(default=False) user_pic = models.ImageField(upload_to=user_directory_path, default='user_pic_male.png', blank=True) phone = models.CharField(max_length=15, blank=True) status = models.CharField(max_length=50, blank=True) role = models.CharField(max_length=10, blank=True) def __str__(self): return self.user.username views.py class UserProfileListCreateView(ListCreateAPIView): queryset=Account.objects.all().order_by('id').reverse() serializer_class=AccountSerializer #permission_classes=[IsAuthenticated] filter_backends = (SearchFilter, OrderingFilter, DjangoFilterBackend) parser_classes = (FileUploadParser, FormParser, MultiPartParser) ordering_fields = '__all__' search_fields = '__all__' #filter_class = AccountFilter def perform_create(self, serializer): user=self.request.user serializer.save(user=user) class AccountDetailView(RetrieveUpdateDestroyAPIView): queryset=Account.objects.all() serializer_class=AccountSerializer #permission_classes=[IsOwnerProfileOrReadOnly,IsAuthenticated] filter_backends = (SearchFilter, OrderingFilter, DjangoFilterBackend) parser_classes = (FileUploadParser, FormParser, MultiPartParser) -
How to create a cron job in Django to run a script that scrapes data from a website and updates a PostgreSQL database?
So I am currently implementing my very first Django-based web app. However, I figured that I only need Django to perform a backend cron job to scrape data from a website and then update existing data in a PostgreSQL database. Then I just use a React frontend to retrieve data from the database and visualize it on the webpage. My issue now is that I don't know how to conceptually tackle this challenge. Currently, I have a model in my models.py file that successfully created my empty table in PostgreSQL: from django.db import models # Create your models here. class rainAreas(models.Model): Country = models.CharField(max_length=100) HasRain= models.BooleanField() Since = models.DateField() class Meta: app_label = "rain_areas" I also filled the table manually with dummy data. Finally, I have a script in my admin.py file, which successfully creates the desired list of data scraped from a website. It looks like this: my_data = [{"country": "Germany", "HasRain": True, "Since": "2020-08-11"}, {"country": "France",.... But now I am stuck. What is the next move to make an SQL UPDATE on the table I created with the data I have in admin.py transform this script to a cron job which should run every hour -
Using django-phonenumber-field in Heroku
I was trying to deploy a Django project (django-phonenumber-field installed) in Heroku. The requirements.txt file contains the following asgiref==3.2.10 Babel==2.8.0 dj-database-url==0.5.0 Django==3.0.8 django-phonenumber-field==4.0.0 gunicorn==20.0.4 phonenumbers==8.12.7 psycopg2-binary==2.8.5 pytz==2020.1 sqlparse==0.3.1 The build is deployed successfully in Heroku. But Heroku was not able to identify the 'phonenumber_field', in the settings.py, and fails to run the build. Does this issue raise due to the name mismatch between the requirements and installed_apps? How can this be fixed? or Am I missing something? Note: 'phonenumber_field' was added in the installed_apps (settings.py) as said in the docs Thanks in advance