Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create this model instance automatically after creating the User model instance
I want the UserProfile model object to be created automaticaly when User object is created. Models.py class UserManager(BaseUserManager): def create_user(self, email, username,password=None,passwordconfirm=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password=None): user = self.create_user( email, username=username, password=password ) user.is_admin = True user.is_staff=True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username=models.CharField(verbose_name='username', max_length=255, unique=True,) password=models.CharField(max_length=100) account_created=models.DateField(auto_now_add=True,blank=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username','password'] def __str__(self): return self.username def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin class UserProfile(User): joined_forums=ArrayField(models.CharField(max_length=100),default=None,blank=True) user_profile_picture=models.ImageField(upload_to="profile_pictures/",default='user-profile-icon.png') recent_interactions=ArrayField(ArrayField(models.CharField(max_length=200),size=2,blank=True),blank=True) Before I had the User instance as foreign key.Now i have removed that and inherited the User class in UserProfile as Multi-table inheritance.Now I am unable to migrate and its asking for default values for the pointer … -
Python django / flask deployment
What is a good way to daploy a django or a flask website, I have a website i want to deploy but don't know how to get a website or something that helps me solve my problem -
I need help installing python3 centos7
I need help installing python3 centos7.NumPy, Requests, BeautifulSoup, matplotlib, Speech Recognition, Scarpy Packages like this are required to be installed. What I want to do is an automatic installation where I can work first locally and then live by using these packages. Can those who have information on this subject contact me on the Whatsapp line at +905315425877? Actually, I tried to install Python3 and django, but I keep getting errors. -
'str' object has no attribute 'chunks'
I have this error when try to save image in folder and in mongo db how i can solve it # Save image file to the static/img folder image_path = save_image_to_folder(value) # Save image to MongoDB using GridFS image_id = fs.put(value, filename=value, content_type=value.content_type) # Return the image id and path for storage in MongoDB and Django folder return {'id': str(image_id), 'path': image_path} def save_image_to_folder(value): # Create the file path to save the image in the Django static/img folder image_name = value image_path = f'decapolis/static/img/{image_name}' # Open the image file and save it to the folder with open(image_path, 'wb+') as destination: for chunk in value.chunks(): destination.write(chunk) # Return the image path return image_path am try to solve it in many way but not working -
Django REST Framework JSON API show an empty object of relationships link when use relations.HyperRelatedField from rest_framework_json_api
I'm create the REST API for space conjunction report, I want the conjunction to be a child of each report. My models: from django.db import models from django.utils import timezone class Report(models.Model): class Meta: managed = False db_table = 'report' ordering = ['-id'] predict_start = models.DateTimeField(null=True) predict_end = models.DateTimeField(null=True) process_duration = models.IntegerField(default=0, null=True) create_conjunction_date = models.DateTimeField(null=True) ephe_filename = models.CharField(max_length=100, null=True) class Conjunction(models.Model): class Meta: managed = False db_table = 'conjunction' ordering = ['-conjunction_id'] conjunction_id = models.IntegerField(primary_key=True) tca = models.DateTimeField(max_length=3, null=True) missdt = models.FloatField(null=True) probability = models.FloatField(null=True) prob_method = models.CharField(max_length=45, null=True) norad = models.OneToOneField(SatelliteCategory, to_field='norad_cat_id', db_column='norad', null=True, on_delete=models.DO_NOTHING) doy = models.FloatField(null=True) ephe_id = models.IntegerField(null=True) pri_obj = models.IntegerField(null=True) sec_obj = models.IntegerField(null=True) report = models.ForeignKey(Report, related_name='conjunctions', null=True, on_delete=models.DO_NOTHING) probability_foster = models.FloatField(null=True) probability_patera = models.FloatField(null=True) probability_alfano = models.FloatField(null=True) probability_chan = models.FloatField(null=True) My serializers: class ConjunctionSerializer(serializers.ModelSerializer): class Meta: model = Conjunction fields = '__all__' class ReportSerializer(serializers.ModelSerializer): conjunctions = relations.ResourceRelatedField(many=True, read_only=True) class Meta: model = Report fields = '__all__' My views: from rest_framework import permissions from rest_framework_json_api.views import viewsets from .serializers import ReportSerializer, ConjunctionSerializer from .models import Report, Conjunction class ReportViewSet(viewsets.ModelViewSet): queryset = Report.objects.all() serializer_class = ReportSerializer permission_classes = [permissions.AllowAny] class ConjunctionViewSet(viewsets.ModelViewSet): queryset = Conjunction.objects.all() serializer_class = ConjunctionSerializer permission_classes = [permissions.AllowAny] My urls.py from django.contrib import … -
Extending django's core admindoc library
I want to add some more functionality to the Django admindoc, specifically this function - class ModelDetailView(BaseAdminDocsView): template_name = 'admin_doc/model_detail.html' def get_context_data(self, **kwargs): pass Should I copy the whole module and paste it over a separate app and then do the changes and then include it in my project? But with this approach, I am adding redundancy to my Django project as I already have all this by default and my usecase is to just extend this function and not everything else. -
Get only one filed from a nested serializer
Her it is my django serializer: class ShopSerializer(serializers.ModelSerializer): rest = RestSerializer(many=True) class Meta: model = RestaurantLike fields = ('id', 'created', 'updated', 'rest') This will wrap whole RestSerializer inside ShopSerializer on response. How can I get only one or two fields from RestSerializer instead of having all the fields inside ShopSerializer? Get only two field of RestSerializer instead of whole RestSerializer -
Nginx Error 413 Entity too large on AWS ELB
So,I am using Django for my backend application deployed on AWS Elastic Beanstalk (EC2 t2.micro, Amazon Linux 2). When I am trying to submit files (.mp4, pdf) that are obviously larger than 1MB, I get Nginx Error 413: Entity too large. The problem is that everything I have tried works for a few hours, before everything is getting reset to the default configurations. As far as I understood there is an auto-scaling functionality that resets everything after each new deploy and sometimes even without deploy.I know that a lot of people had faced this kind of problem, and for some of them actions described in other posts solved the problem. However, for me everything resets either immediately after deploy, or in a couple of hours. I have already tried, as suggested in other posts on Stackoverflow, changing the nginx file from the EC2 console, adding my own configuration file in source code (.ebextensions folder), applied some changes to my S3 bucket, and many other options. ***NOTE: I have also created a custom function for handling large files in Django itself, but I think it is irrelevant to the Nginx error that I get. Thanks. -
How to access value with in change_form file of django admin?
Hy there, I want to access value and apply position ordering on related field with in change_form file of django admin. I have two model from django.db import models from django.contrib.auth import get_user_model User = get_user_model() PRODUCT_TYPE_CHOICES=[(1,'New'),(2,'Old')] CURRENCY_TYPE_CHOICES=[(1,'USD'),(2,'INR')] class Product(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) product_category = models.ForeignKey( ProductCategory, on_delete=models.SET(get_default_category) ) product_type = models.IntegerField(choices=PRODUCT_TYPE_CHOICES,blank=True, null=True) currency_type=models.IntegerField(choices=CURRENCY_TYPE_CHOICES,blank=True, null=True) country = CountryField(max_length=10, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) state = models.CharField(max_length=255, blank=True, null=True) price = models.FloatField(max_length=255,blank=True, null=True) class Comment(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) forum = models.ForeignKey( Product, on_delete=models.CASCADE,related_name="product_comments") In admin panel I want to display comment of particular product under the user field as shown in below image. Can you guys help me how do i solve this scenario. -
Sitemaps not showing after git push
I have created a sitemaps for my django project but the sitemaps.py file doesn't reflect in the git repository even after i push. i tried creating the file from git but the changes are still not reflecting -
Can't I set the number with a decimal part to "MinMoneyValidator()" and "MaxMoneyValidator()" in "MoneyField()" with Django-money?
I use Django-money, then I set 0.00 and 999.99 to MinMoneyValidator() and MaxMoneyValidator() respectively in MoneyField() as shown below: # "models.py" from django.db import models from djmoney.models.fields import MoneyField from djmoney.models.validators import MinMoneyValidator, MaxMoneyValidator class Product(models.Model): name = models.CharField(max_length=50) price = MoneyField( # Here max_digits=5, decimal_places=2, default=0, default_currency='USD', validators=[ # Here # Here MinMoneyValidator(0.00), MaxMoneyValidator(999.99), ] ) Then, I added a product as shown below: But, I got the error below: TypeError: 'float' object is not subscriptable So, I set 0 and 999 to MinMoneyValidator() and MaxMoneyValidator() respectively in MoneyField() as shown below, then the error above is solved: # "models.py" from django.db import models from djmoney.models.fields import MoneyField from djmoney.models.validators import MinMoneyValidator, MaxMoneyValidator class Product(models.Model): name = models.CharField(max_length=50) price = MoneyField( max_digits=5, decimal_places=2, default=0, default_currency='USD', validators=[ # Here # Here MinMoneyValidator(0), MaxMoneyValidator(999), ] ) Actually, I can set 0.00 and 999.99 to MinValueValidator() and MaxValueValidator() respectively in models.DecimalField() without any errors as shown below: # "models.py" from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Product(models.Model): name = models.CharField(max_length=50) price = models.DecimalField( # Here max_digits=5, decimal_places=2, default=0, validators=[ # Here # Here MinValueValidator(0.00), MaxValueValidator(999.99) ], ) So, can't I set the number with the decimal part to MinMoneyValidator() … -
TemplateDoesNotExist at/ on Django
I have the project like this: ├── manage.py ├── myProjet │ ├── __init__.py │ ├── settings.py │ ├── templates │ ├── urls.py │ ├── wsgi.py │ └── wsgi.pyc ├── app1 ├── templates When I roun the project, I am always getting this error: TemplateDoesNotExist at/ I have tried everythin, but I can't fix it. My settings.py file is this: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app1', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I have tried in a lot of ways, but I am always ge3tting the error. The error is rased on the singUp function. The function is this: def SignupPage(request): if request.method=='POST': uname=request.POST.get('username') email=request.POST.get('email') pass1=request.POST.get('password1') pass2=request.POST.get('password2') if pass1!=pass2: return HttpResponse("Your password and confrom password are not Same!!") else: my_user=User.objects.create_user(uname,email,pass1) my_user.save() return redirect('login') return render (request,'signup.html') -
How to add 2 values in 1 hx-target Django
I have a form to select counterparty, object and section When im choosing counterparty which have object and this objects has section all`s good But when i change counterparty which have object and doesnt have sections i still has sections from previous object I want to clear with hx-target 2 fields: object and sections, but its working only with one How am i suppose to do that? counter.html <div class="mt-3"> {{ form.contractor_counter.label_tag }} {% render_field form.contractor_counter class='form-select mt-2' autocomplete='off' hx-get='/objects/' hx-target='#id_contractor_object' %} </div> <div class="mt-3"> {{ form.contractor_object.label_tag }} {% render_field form.contractor_object class='form-select mt-2' autocomplete='off' hx-get='/sections/' hx-target='#id_contractor_section' %} </div> <div class="mt-3"> {{ form.contractor_section.label_tag }} {% render_field form.contractor_section class='form-select mt-2' autocomplete='off' %} </div> -
Python 3.11.1. Getting error Failed to establish a new connection: [Errno -5] No address associated with hostname
I am using zeep 4.2.1 library to consume web services(RFC) from SAP. The API's are working in local server and getting the necessary response. However the API is not working in development environment(docker container). Getting error message as HTTPConnectionPool(host=' ', port=): Max retries exceeded with url. (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7ffa989589b0>: Failed to establish a new connection: [Errno -5] No address associated with hostname',))" After doing telnet from development environment response received It gets connected but after sometime(1 min approx) 408 "Request Time Out" Application Server Error - Traffic control Violation is raised and connection is closed. Note-('Have removed hostname from error message but hostname and port are correct `HTTPConnectionPool(host=' ', port=) Kindly help me does any additional setting required for SAP RFC in docker container -
can I use .h5 file in Django project?
I'm making AI web page using Django and tensor flow. and I wonder how I add .h5 file in Django project. writing whole code in views.py file but I want to use pre-trained model not online learning in webpage. -
Django return "internal" sign in form
I try to create my own session middleware and my uauth system using Django. I've got the following code: class CheckSessionsExistMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): ... response = self.get_response(request) ... response.status_code = 401 response.reason_phrase = 'Unauthorized' realm = 'some_app' response['WWW-Authenticate'] = f'Basic real={realm}' return response When i set to respone header 'WWW-Authenticate' the string that contains word 'Basic', django returns the following form and i do not understand why: Link to example of sign in form that django returns: https://psv4.userapi.com/c235131/u2000021998/docs/d23/bc9d828c3755/file.png?extra=0qo4COrPeQh3mwjuRs1WoYsB3GVW8WB-Xn01jjtQz7muPVFWRqKjsm0itRqJFhOqjoYoKQGpAqWbG4xNQlJD3_kcs1u0UNct_76s6b1jv0u9oW76cnH2bGBTWGd5hpSQY-OpgxtRj60rtUa0k8EX7ydRHQ Is there a way to disable this behavior? I expected that Django just return to client the header 'WWW-Authenticate' with value 'Basic realm=some_app' without sign in form. -
Extending django's core modules functionality
I want to add some little enhancement to one of the core Django modules. Can somebody guide me to some good resources as to how I can achieve that? A simple example of what I want to do is add an extra if-else condition. -
How do you incrementally add lexeme/s to an existing Django SearchVectorField document value through the ORM?
You can add to an existing Postgresql tsvector value using ||, for example: UPDATE acme_table SET _search = _search || to_tsvector('english', 'some new words to add to existing ones') WHERE id = 1234; Is there any way to access this functionality via the Django ORM? I.e. incrementally add to an existing SearchVectorField value rather than reconstruct from scratch? The issue I'm having is the SearchVectorField property returns the tsvector as a string. So when I use the | operator, eg: from django.contrib.postgres.search import SearchVector instance.my_tsvector_prop += SearchVector(["new", "words"], weight="A", config='english') I get the error: TypeError: SearchVector can only be combined with other SearchVector instances, got str. Because: type(instance.my_tsvector_prop) == str A fix to this open Django bug whereby a SearchVectorField property returns a SearchVector instance would probably enable this, if possible. This update will run asynchronously so performance is not too important. Another solution would be to run a raw SQL UPDATE, although I'd rather do it through the Django ORM if possible as our tsvector fields often reference values many joins away, so it'd be nice to find a sustainable solution. -
Django SQLAlchemy engine issue - data not transferred to db using Pandas
My use case is to take excel data and load it to database.. I am using SQLAlchemy (with Pandas df) to do that, but am not able to do.. When I try with ORM bulk_create, it works, suggesting to me that Django side of stuff (eg template, url, view, model connections) is working fine, and there could be some issue in defining the Alchemy engine?? I need help from you to debug and resolve this.. My code details are as below.. Please note I dont get any errors in vscode terminal, its just that when I click on Add/ replace button, the data does not transfer.. Appreciate your help.. many thanks.. SQLAlchemy engine details (saved in engine.py) from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from django.conf import settings engine = create_engine('postgresql://' + settings.DATABASES['default']['USER'] + ':' + settings.DATABASES['default']['PASSWORD'] + '@' + settings.DATABASES['default']['HOST'] + ':' + str(settings.DATABASES['default']['PORT']) + '/' + settings.DATABASES['default']['NAME']) Session = sessionmaker(bind=engine) session = Session() views.py from .models import Industry from .engine import engine, session import pandas as pd def industry_import_replace(request): df = pd.read_excel('Industry.xlsx') df.to_sql('Industry', engine, if_exists='replace', index=False) return render(request, 'portfolio/partials/imports/industry-import.html',{}) template (html) <form method="post"> <div class="row"> <div class="col col-md-4 col-lg-4"> <table class="table"> <thead> <tr> <th scope="col-md-4 col-lg-4">Imports</th> <th … -
Uncaught TypeError: e.indexOf is not a function while upgrading JQuery version
I got an error while upgrading jQuery version from 2.2.4 to 3.6.3 and Bootstrap from 3.3.6 to 3.3.7. When web page is loaded , it is taking too much time . Can anyone suggest a solution to solve this issue? -
Development on local machine vs VM
I have a project to develop on top of Django. The scrum master suggest developing on VM in order to have the same database with others developers. I suggest letting every developer develop in his local machine for development before going to the prod. Could you please advise me the best way to follow ? Otherwise, what will the characteristics of the VM (RAM, CPU, etc) ? -
Divide blogs according to year in list of queryset
I am building a blog app and I am trying to seperate blogs based on the year they were created. like :- 2022 First Blog Second Blog 2021 Third Blog Fifth Blog It can be in list dictionary like :- [ "2022": { "title": "First Blog", "title": "Second Blog", }, "2021": { "title": "Fifth Blog", "title": "Second Blog", } ] models.py class Blog(models.Model): title = models.CharField(max_length=100, default='') date = models.DateTimeField(auto_now_add=True) views.py def get_blogs(request): blogs_by_year = Blog.objects.annotate( year=TruncMonth('date')).annotate( blogs=Count('title')).values("year", "blogs") return blogs_by_year But it is showing seperate results like <QuerySet [{'year': datetime.datetime(2023, 1, 1, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='UTC')), 'blogs': 1}, {'year': datetime.datetime(2023, 1, 1, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='UTC')), 'blogs': 1}]> But I am trying to seperate based on year. Should I seperate blogs by year using for loop and then filter according to year and append in list of dictionary ? I have read the DateField truncation page but it didn't worked out. -
i am unable to access django rest api from outside the server [closed]
I am facing an issue while trying to access the django api from outside the server.It is working inside the server but unable to access it from outside, can anyone help how to resolve this issue? i have configured url for the django api as well, its giving 502 error, any other solution for the same. -
Next.js getServerSideProps give 404 on production only
I have reproduced the problem to the simplest form: let's start with the backend: #models.py from django.db import models from django.template.defaultfilters import slugify # new class Article(models.Model): slug = models.SlugField(primary_key=True,unique=True) title = models.CharField(max_length=200) description = models.TextField() def save(self,*args,**kwargs): if not self.slug: self.slug = slugify(self.title) super().save(*args,**kwargs) #views.py from django.shortcuts import render from rest_framework.viewsets import ModelViewSet from rest_framework.response import Response from app import models from app import serializer class ArticleView(ModelViewSet): serializer_class = serializer.ArticleSerializer def get_queryset(self): return models.Article.objects.all() def post(self,request): data = serializer.ArticleSerializer(data=request.data) if data.is_valid(): a = models.Article.objects.create(title=data['title'],description=data['description']) a.save() return Response("succes",status=200) return Response("fail",status=400) #serializer.py from rest_framework import serializers from app import models class ArticleSerializer(serializers.ModelSerializer): slug = serializers.SlugField(read_only=True) class Meta: fields = 'slug','title','description', model = models.Article #settings.py ALLOWED_HOSTS = ['localhost','127.0.0.1'] ACCESS_CONTROL_ALLOW_ORIGIN = '*' CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True ACCESS_CONTROL_ALLOW_CREDENTIALS = True ACCESS_CONTROL_ALLOW_METHODS = '*' ACCESS_CONTROL_ALLOW_HEADERS = '*' # Application definition INSTALLED_APPS = [ 'app', 'rest_framework', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', "corsheaders.middleware.CorsMiddleware", 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I have provided everything related to the backend Now on next js side: i got this (inside pages folder): and the code is like this inside [slug].js import axios from 'axios' export async function getServerSideProps({params}){ try{ let res … -
How to get default text input value from one html to other html form
I'm doing basic login. In one html file I have user input email id text box, once click on send otp button that will redirect to next html with email and otp fields, In email field what ever user gives input in first html page that should automatically get into second html email input field text box. Here is my first html page <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Employee Login </title> <link rel="stylesheet" href="{% static 'style.css' %}"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <center> <h1> </h1> <h2> </h2> <h3> Employee Feedback Login</h3> </center> <div class="wrapper"> <div class="title-text"> <div class="title login"> Login </div> </div> <div class="form-container"> <div class="form-inner"> <form action="" method="post" class="login"> {% csrf_token %} <div class="field"> <input id = "Employee_Mail" type="text" placeholder="Email Address" name="Employee_Mail" required> </div> <div class="field btn"> <div class="btn-layer"></div> <input type="submit" value="Send OTP" > </div> </form> </div> </div> </div> </body> </html> and my redirect(second html page) <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Employee Login </title> <link rel="stylesheet" href="{% static 'style.css' %}"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <center> <h1></h1> <h2> </h2> <h3> Employee Feedback Login</h3> </center> <div class="wrapper"> <div class="title-text"> <div class="title login"> Login </div> …