Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting to LND Node through a local-running Django Rest API
I am trying to connect to my LND node running on AWS (I know it is not the best case scenario for an LND node but this time I had no other way of doing it) from my local running Django Rest Api. The issue is that it cannot find the admin.macaroon file even though the file is in the mentioned directory. Below I am giving some more detailed information: view.py `class GetInfo(APIView): def get(self, request): REST_HOST = "https://ec2-18-195-111-81.eu-central-1.compute.amazonaws.com" MACAROON_PATH = "/home/ubuntu/.lnd/data/chain/bitcoin/mainnet/admin.macaroon" # url = "https://ec2-18-195-111-81.eu-central-1.compute.amazonaws.com/v1/getinfo" TLS_PATH = "/home/ubuntu/.lnd/tls.cert" url = f"https//{REST_HOST}/v1/getinfo" macaroon = codecs.encode(open(MACAROON_PATH, "rb").read(), "hex") headers = {"Grpc-Metadata-macaroon": macaroon} r = requests.get(url, headers=headers, verify=TLS_PATH) return Response(json.loads(r.text))` The node is running with no problem on AWS. This is what I get when I run lncli getinfo: $ lncli getinfo: { "version": "0.15.5-beta commit=v0.15.5-beta", "commit_hash": "c0a09209782b1c62c3393fcea0844exxxxxxxxxx", "identity_pubkey": "mykey", "alias": "020d4da213770890e1c1", "color": "#3399ff", "num_pending_channels": 0, "num_active_channels": 0, "num_inactive_channels": 0, "uris": [ .... and the permissions are as below: $ ls -l total 138404 -rwxrwxr-x 1 ubuntu ubuntu 293 Feb 6 09:38 admin.macaroon drwxrwxr-x 2 ubuntu ubuntu 4096 Feb 5 14:48 bin drwxr-xr-x 6 ubuntu ubuntu 4096 Jan 27 20:17 bitcoin-22.0 drwxrwxr-x 4 ubuntu ubuntu 4096 Feb 1 16:39 go -rw-rw-r-- 1 … -
How to connect multiple chained dropdown with Django and HTMX
I have a form with counterparty, object and sections i connected them to each other with django-forms-dynamic package but object not connected to sections Counterparty connected to object form but sections are not connected to object how can i fix that? I guess that im wrong with 2 functions in forms.py: section_choices and initial_sections and they`re not connected to objects but dont know how to fix that forms.py class WorkLogForm(DynamicFormMixin, forms.ModelForm): def object_choices(form): contractor_counter = form['contractor_counter'].value() object_query = ObjectList.objects.filter(contractor_guid__in=[contractor_counter]) return object_query def initial_object(form): contractor_counter = form['contractor_counter'].value() object_query = ObjectList.objects.filter(contractor_guid__in=[contractor_counter]) return object_query.first() def section_choices(form): contractor_object = form['contractor_object'].value() section_query = SectionList.objects.filter(object=contractor_object) return section_query def initial_sections(form): contractor_object = form['contractor_object'].value() section_query = SectionList.objects.filter(object=contractor_object) return section_query.first() contractor_counter = forms.ModelChoiceField( label='Контрагент', queryset=CounterParty.objects.none(), initial=CounterParty.objects.first(), empty_label='', ) contractor_object = DynamicField( forms.ModelChoiceField, label='Объект', queryset=object_choices, initial=initial_object, ) contractor_section = DynamicField( forms.ModelMultipleChoiceField, label='Раздел', queryset=section_choices, initial=initial_sections, ) views.py @login_required def create_work_log(request): if request.method == 'POST': form = WorkLogForm(request.POST, user=request.user) if form.is_valid(): work_log = form.save(commit=False) work_log.author = request.user work_log = form.save() messages.success(request, 'Данные занесены успешно', {'work_log': work_log}) return redirect('create_worklog') else: messages.error(request, 'Ошибка валидации') return redirect('create_worklog') form = WorkLogForm(user=request.user, initial=initial) return render(request, 'contractor/create_work_log.html', {'form': form}) def contractor_object(request): form = WorkLogForm(request.GET, user=request.user) return HttpResponse(form['contractor_object']) def contractor_section(request): form = WorkLogForm(request.GET, user=request.user) return HttpResponse(form['contractor_section']) -
as_crispy_field cannot re-render the uploaded FileField data from return POST request of Django formset
I have a Django formset that receives the POST request data once submitted, and it saves it (including the uploading file) normally to my database, but if the form is invalid, the page renders again with the same values but missing the selected uploaded file. I am passing the data to the formset as: fs = MyFormset(request.POST, request.FILES, .......) and I am rendering the fields of each form one by one. So, the file field data is: <div class="col-md-10"> {{ form.included_documents|as_crispy_field }} </div> When I submit a new form but it fails in one of the validation criteria, it returns with no file chosen although there was a file chosen. But, if I have a saved form, it renders the uploaded file normally. Failed Tested Workaround: According to this Github issue answer, I tested it and it parsed the file input with a better look, but it still fails with parsing the TemporaryUploadedFile. To make sure that I have the value in my form, I added the below, and it showed the value correctly in the span element not the crispy field element: <div class="col-md-10"> {{ form.included_documents|as_crispy_field }} <span>{{ form.included_documents.value }}</span> </div> What am I missing here to render the … -
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.