Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting User DNS Domain - Django/Angular app
Good morning! I have currently a django/angular application where my users use LDAP auth with multiple domains. I would like to get (via server-side or via frontend) the user dns domain, by meaning the equivalent to the environmental variable %USERDNSDOMAIN% in Windows so I can use dinamically this variable inside the server-side instead of having multiple url for each domain so I can have a global LDAP auth. For now I have the user IP, which is obtained directly from the request via django request: request.META.get('REMOTE_ADDR') So far I have tried getting the DNS from the given ip by using python dns library: dns.reversename.from_address("REQUEST_IP") and also using the python sockets library socket.gethostbyaddr('REQUEST_IP') The first one works but does not give the result I am looking for, and the second one does not work properly: ---> 10 socket.gethostbyaddr('REQUEST_IP') herror: [Errno 1] Unknown host Have a good day! -
Login,register and verify OTP API project with Django rest framework
I want to make an API project in which a person can Login, register with a phone number and OTP. What we need to do in this project Login and Register from the same page. Verify OTP from verify image. When user gets register for the first time mobile number, otp, a random username,a random picture from a folder,a random profile id, a name whic is the same as mobile number gets alloted in the database. Here's my code modals.py class User(models.Model): mobile = models.CharField(max_length=20) otp = models.CharField(max_length=6) name = models.CharField(max_length=200) username = models.CharField(max_length=200) logo = models.FileField(upload_to ='profile/') profile_id = models.CharField(max_length=200) serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['mobile'] def create(self, validated_data): instance = self.Meta.model(**validated_data) global totp secret = pyotp.random_base32() totp = pyotp.TOTP(secret, interval=300) otp = totp.now() instance = self.Meta.model.objects.update_or_create(**validated_data, defaults=dict(otp=str(random.randint(1000 , 9999))))[0] instance.save() return instance class VerifyOTPSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['mobile','otp'] def create(self,validated_data): instance = self.Meta.model(**validated_data) mywords = "123456789" res = "expert@" + str(''.join(random.choices(mywords,k = 6))) path = os.path.join(BASE_DIR, 'static') dir_list = os.listdir(path) random_logo = random.choice(dir_list) instance = self.Meta.model.objects.update_or_create(**validated_data, defaults = dict(username = res,name = instance.mobile ,logo = random_logo, profile_id = res))[0] instance.save() return instance views.py def send_otp(mobile,otp): url = "https://www.fast2sms.com/dev/bulkV2" authkey … -
API design to avoid multiple model serializers (DRF)
I'm coding my backend with Django and my API with DjangoRestFramework. The thing is I'm wondering how to handle serializers in order not to have tons of them for a single model. Considering a model that represents, let's say, an InventoryItem (such as a computer). This computer can be linked to a category, a supplier, a company, a contact within that company... That makes relations to be serialized and it brings nested data into the returned Item. While I may need all these fields in a list view, I may not in the form view or in a kanban view. And if I want to, for instance, in the form view of a helpdesk ticket, have an autocomplete input component to link the ticket to that inventory item, I want only to have, let's say, the name of the Inventory Item, so returning a list of items with all the nested data would be a bit overkill since I need only its name. And you could say : Just make different serializers for the scenarios you need. I'd end up with something like : InventoryItemFormSerializer InventoryItemListSerializer InventoryItemInputSerializer (to be used for input components) Also for listing Items i'd use a … -
Same results consecutif
I have a table : output _df (image in the question) . Ienter image description here repetition of the same value for "PCR POS/Neg" consecutive in my "output_df". If i have 3 results identiques consecutifs , more than 3 times in the output_df so i need to give an error message "WARNING" in my index.html How i can do it ? views.py from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pandas as pd import datetime from datetime import datetime as td import os from collections import defaultdict from django.contrib import messages import re import numpy as np def home(request): #upload file and save it in media folder if request.method == 'POST': uploaded_file = request.FILES['document'] uploaded_file2 = request.FILES['document2'] if uploaded_file.name.endswith('.xls') and uploaded_file2.name.endswith('.txt'): savefile = FileSystemStorage() #save files name = savefile.save(uploaded_file.name, uploaded_file) name2 = savefile.save(uploaded_file2.name, uploaded_file2) d = os.getcwd() file_directory = d+'/media/'+name file_directory2 = d+'/media/'+name2 cwd = os.getcwd() print("Current working directory:", cwd) results,output_df,new =results1(file_directory,file_directory2) return render(request,"results.html",{"results":results,"output_df":output_df,"new":new}) else: messages.warning(request, ' File was not uploaded. Please use the correct type of file') return render(request, "index.html") #read file def readfile(uploaded_file): data = pd.read_excel(uploaded_file, index_col=None) return data def results1(file1,file2): results_list = defaultdict(list) names_loc = file2 listing_file = pd.read_excel(file1, index_col=None) headers = ['Vector Name', 'Date and … -
Downside of logging with Email using AbstractUser Not AbstractBaseUser
I am entirely happy with Django default user model and I would like to extend it, AbstractUser seems to describe my situation, If you’re entirely happy with Django’s User model, but you want to add some additional profile information, you could subclass django.contrib.auth.models.AbstractUser and add your custom profile fields But I also learned If you wish to login with Email you should go with AbstractBaseUser, If you want to use an email address as your authentication instead of a username, then it is better to extend AbstractBaseUser My current model uses AbstractUser and not AbstractBaseUser, I can login with email just fine, What is the potential downside of this in the long run? I have plans to allow User login with either Email or Phone In the future, Now just Email, But it seems has something to do with AUTHENTICATION_BACKENDS regardless of which you use, What could potentially go wrong if I go ahead with AbstractUser or Should I be cautious go with AbstractBaseUser? According to Django Docs, It is very troublesome to change default user model to custom user model in mid project, Then how troublesome would it be to change AbstractUser to AbstractBaseUser? from django.db import models from … -
Reverse for 'delete_note' with arguments '('',)' not found. 1 pattern(s) tried: ['delete_note/(?P<id>[0-9]+)/$']
I am facing this error while adding this in my html file <a href="{% url 'delete_note' i.id %}"class="btn btn-outline-danger">Delete</a> -
The admin login form does not allow the superuser to log in
When I try to login to the Django admin panel, I get an error: "This account has been disabled." However, the user status is active. I tried to register a new user through the console, but the error remained. You can enter the administration panel only by logging in to the site itself through the authorization form. I am using a custom user model. Here is my code: settings.py: AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'users.backends.AuthBackend', ) users.backends class AuthBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) if username is None or password is None: return try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password): return user def get_user(self, user_id): try: user = UserModel._default_manager.get(pk=user_id) except UserModel.DoesNotExist: return None return user users.models class CustomAccountManager(BaseUserManager): def create_user(self, email, full_name, password, **other_fields): if not email: raise ValueError('Enter email') email = self.normalize_email(email) if not full_name: full_name = email.split('@')[0] user = self.model( email=email, full_name=full_name, **other_fields ) user.set_password(password) # other_fields.setdefault('is_active', True) user.save() return user def create_superuser(self, email, full_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) # other_fields.setdefault('is_author', True) other_fields.setdefault('is_active', True) if … -
Django -> ListView -> get_context_data() -> Model.objects.filter(self.object)
How do I grab each model object from a ListView? I have a blog and I'm trying to order each post's comments by the number of comment likes views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 def get_context_data(self, *args, **kwargs): com = Comment.objects.filter(post=self.object?) #<--- WHAT TO INPUT HERE? comment_list = com.annotate(like_count=Count('liked')).order_by('-like_count') #BELOW DOESN'T WORK. EVERY POST HAS THE SAME COMMENT LIST AS THE LATEST POST.. SEE PICTURE BELOW # posts = Post.objects.all() # for post in posts: # com = Comment.objects.filter(post=post) #<--- what to input here # comment_list = com.annotate(like_count=Count('liked')).order_by('-like_count') #BELOW DOESN'T WORK. EVERY POST HAS THE SAME COMMENT LIST AS THE LATEST POST.. SEE PICTURE BELOW # posts = Post.objects.all() # #for post in posts: #comment_list = post.comment_set.all().annotate(like_count=Count('liked')).order_by('-like_count') context = super(PostListView, self).get_context_data(*args, **kwargs) context['cats_menu'] = cats_menu context['c_form'] = c_form context['comment_list'] = comment_list return context img link - latest post img link - all other posts copy the comments on the latest post models.py class Comment(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField(max_length=300) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) liked = models.ManyToManyField(Profile, blank=True, related_name='com_likes') def __str__(self): return f"Comment:{self.user}-{self.post}-{self.id}" def post_id(self): return self.post.id def num_likes(self): return self.liked.all().count() … -
how to set disabled=false to all element in the Select>options , before the Ajax call which set disabled=true
Html <!DOCTYPE html> <html> <div class="wrapper"> {%if messages %} {% for message in messages %} <div class="alert {{ message.tags }} alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> {{ message }} </div> {% endfor %} {% endif %} <div class="register-page"> <div class="register-container"> <form id="appointment-form" role="form" method="post" enctype='multipart/form-data'> <!-- SECTION TITLE --> <div class="section-title wow fadeInUp" data-wow-delay="0.4s"> <h2>Book Appointment</h2> </div> {% csrf_token %} <input name="patient_name" value="{{request.user}}" hidden> <div class="wow fadeInUp" data-wow-delay="0.8s"> <div class="col-md-6 col-sm-6"> <label for="name">Clinic name</label> {{ form.clinic_name }} </div> <div class="col-md-6 col-sm-6"> <label for="qualification">Doctor Name</label> {{ form.doctor_name }} </div> <!-- try --> <p id="p-text">foo bar</p> <div class="col-md-6 col-sm-6"> <label for="specialist"> Date</label> {{ form.date }} </div> <!-- try --> <p id="d-text">foo bar</p> <div class="col-md-6 col-sm-6"> <label for="location">Time slot </label> <!-- {{ form.time_slot }} --> <select name="time_slot" required="" id="id_time_slot"> <option value="" selected="">---------</option> <option value="09:00 - 10:00" id="op0">09:00 - 10:00</option> <option value="10:00 - 11:00" id="op1">10:00 - 11:00</option> <option value="11:00 - 12:00" id="op2">11:00 - 12:00</option> <option value="12:00 - 13:00" id="op3">12:00 - 13:00</option> <option value="13:00 - 14:00" id="op4">13:00 - 14:00</option> <option value="14:00 - 15:00" id="op5">14:00 - 15:00</option> <option value="15:00 - 16:00" id="op6">15:00 - 16:00</option> <option value="16:00 - 17:00" id="op7">16:00 - 17:00</option> <option value="17:00 - 18:00" id="op8">17:00 - 18:00</option> </select> </div> <div class="col-md-12 … -
Separate Model classes into Separate Files Django
ku-polls/ manage.py polls/ init.py apps.py forms.py tests.py views.py models/ init.py question.py choice.py How to run 'python manage.py makemigrations' folder models? -
How to add Yahoo Finance API with flask or django
My question is we can see in app.py as a (default="AMZN") i need to get an user input (or) a user can click on the company name to see more info and proceed further for each companys. I'm trying to learn flask and built a small app that contains a list of companies with some general info for each of them. The home page shows a list of all companies and then a user can click on the company name to see more info. I'm now trying figure out how APIs are consumed in flask by using Yahoo Finance to get some stock data about the company and display it on the page. It is fine flask or django web frame work. Also, I need a guidance from scratch. I am beginner. import yfinance as yahooFinance # Here We are getting Facebook financial information # We need to pass FB as argument for that GetInformation = yahooFinance.Ticker(input("enter iput here: " )) #GetInformation = yahooFinance.Ticker("FB") # whole python dictionary is printed here print(GetInformation.info) My code app.py from flask import Flask, redirect, url_for, render_template, request import yfinance as yf app = Flask(__name__) @app.route('/') def hello(): return 'Hello, World!' @app.route("/login", methods=["POST", "GET"]) def … -
How to implement multiple fields search in Django?
The problem is implementing a search across multiple fields. There is a sqllite database, there is a table and one search button on the page, the user enters a value into the fields (it is not necessary to fill in all the fields, it is filled in randomly). I'm just starting to learn django, don't judge strictly) Thanks! models # Год class Year(models.Model): title = models.CharField(max_length=4, verbose_name='Год') slug = models.SlugField(max_length=4, verbose_name='Slug Год', unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('year', kwargs={"pk": self.pk}) class Meta: verbose_name = 'Год' verbose_name_plural = 'Год' ordering = ['title'] # Наименвоание объекта class Subject(models.Model): title = models.CharField(max_length=100, verbose_name='Наименование объекта') slug = models.SlugField(max_length=100, verbose_name='Slug Наименование объекта', unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('subject', kwargs={"pk": self.pk}) class Meta: verbose_name = 'Наименвоание объекта' verbose_name_plural = 'Наименвоание объекта' ordering = ['title'] # Вид обследования class Surveys(models.Model): title = models.CharField(max_length=200, verbose_name='Вид обследования') slug = models.SlugField(max_length=200, verbose_name='Slug Вид обследования', unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('surveys', kwargs={"pk": self.pk}) class Meta: verbose_name = 'Вид обследования' verbose_name_plural = 'Вид обследования' ordering = ['title'] # Пост class Post(models.Model): title = models.CharField(max_length=100, verbose_name='Пост', blank=False, null=True, ) slug = models.SlugField(max_length=100, verbose_name='Slug Пост', unique=True) content = models.TextField(blank=True, verbose_name='Контент') created_at = models.DateTimeField(auto_now_add=True, verbose_name='Опубликовано') document … -
Problem with "import" when trying to create a Django project in virtual environment with VS code
This is the problem i have, including another one (the solution on this link didn't solve it): How to resolve 'Import "django.contrib" could not be resolved from source' in VS Code? As a bachelors project we are supposed to do an website with django and React. Our university wants us to do it with a lniux-based virtual environment. I followed this tutorial: https://www.digitalocean.com/community/tutorials/build-a-to-do-application-using-django-and-react I can run the server with "python manage.py runserver" at first and it works, but when i try to import from for example ".model" errors arise and i can't run the server. I'm running windows and have installed "wsl" to get into a Linux virtual machine first. Then i install a virtual environment in the linux machine. I have set the python interpreter as the one i'm using in my VENV and it sticks. What can i try? Please help i've been stuck on this all day. I tried setting python interpreter as the one in the virtual environment, update python in the virtual environment, tried install the virtual environment in windows instead (a lot of other errors came up, won't be trying that again), tried follow differend tutorials which did it in different ways. The same … -
Form UpdateView and DeleteView and 3 hierarchical models
I am trying to create an 'Expense Tracker'. I have query regarding UpdateView and DeleteView and Models with 3 hierarchical levels. I was able to create the CreateView for the 'Expense' model, but the update and delete view are throwing a lot of errors. Can you please tell how to write the code for update and deleteview (for 'Expense' model). Models.py class Year(models.Model): year = models.IntegerField(choices=year_choices() ,validators=[MinValueValidator(1984), max_value_current_year], name='year', unique = True) def __str__(self): return str(self.year) class Meta(): ordering = ('-year','-year') class Month(models.Model): month = models.CharField(choices=month_choices(), max_length=264) month_year = models.ForeignKey(Year,related_name = 'month',on_delete=models.CASCADE) def __str__(self): return str(self.month) + ' ' + str(self.month_year) def get_absolute_url(self): return reverse("Expense_App:Year") class Meta(): unique_together = [['month','month_year']] class Expense(models.Model): Home_Expense = models.PositiveIntegerField() Groceries = models.PositiveIntegerField() Electronics = models.PositiveIntegerField() Snacks = models.PositiveIntegerField() Other = models.PositiveIntegerField() total = models.PositiveIntegerField() expense_month = models.ForeignKey(Month,related_name = 'expense', on_delete=models.CASCADE) def __str__(self): return str(self.expense_month) + ' ' + str(self.total) def get_absolute_url(self): return reverse("Expense_App:Year") Forms.py #forms.py class ExpensesForm(forms.ModelForm): class Meta(): model = Expenses fields = ('expenses','expense_month') def __init__(self, *args, **kwargs): month_year_id = kwargs.pop('month_year_id') super(ExpensesForm, self).__init__(*args, **kwargs) self.fields['expense_month'].queryset = ExpenseMonth.objects.filter(month_year_id=month_year_id) Views.py #createview for 'expense' model class ExpenseCreateView(CreateView): model = models.Expense form_class = ExpenseForm def get_form_kwargs(self): kwargs = super(ExpenseCreateView, self).get_form_kwargs() kwargs.update({'month_year_id': self.kwargs.get('pk')}) return kwargs Urls.py Update and … -
Django - unique_together with nested field in M2M
I have two model like A and B that have many-to-many relation on ids. B has a field like "type" and it maybe have many record with similar "type". i want manage this relation on every A related to one "type" no more. class throughModel(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) b = models.ForeignKey(B, on_delete=models.CASCADE) class Meta: unique_together = ['a', 'b__type'] but dosen't work and i have no idea for implementation this. -
PGsql delete fields on a table and related on anoter in one command
In my django project i have two models: class Results(models.Model): device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL) proj_code = models.CharField(max_length=400) res_key = models.SlugField(max_length=80, verbose_name="Message unique key", primary_key=True, unique=True) read_date = models.DateTimeField(verbose_name="Datetime of vals readings") unit = models.ForeignKey(ModbusDevice, null=True, on_delete=models.SET_NULL) and class VarsResults(models.Model): id = models.AutoField(primary_key=True) on_delete=models.CASCADE) key_res = models.ForeignKey(Results, related_name="keyres", on_delete=models.CASCADE) var_id = models.ForeignKey(ModbusVariable, null=True, on_delete=models.SET_NULL) var_val = models.CharField(max_length=400, blank=True) var_val_conv = models.CharField(max_length=100, blank=True, null=True) var_hash = models.CharField(max_length=400) has_error = models.BooleanField(default=False) so VarsResults has a key_res ForeignKey to table Results. I would, using PGSql create a query for delete ALL data starting from Results from a certain data and automatically delete the related rows in VarsResults like thisone: DELETE FROM Results WHERE read_date < "2022-01-01" (and delete also the related VarsResults rows) So many thanks in advance Manuel -
i have tried email validations and it was successfull but, I wantnthis error as popup alert
i have tried email validations and it was successfull but, I want this error as popup alert. forms.py class RegisterForm(forms.Form): MailID = forms.CharField(max_length=50, widget=forms.EmailInput(attrs={'class': 'form-control','placeholder': 'Enter Mail_ID'})) validation: def clean_MailID(self): mail = self.cleaned_data.get("MailID") rows = StudData.objects.filter(MailID=mail) if rows.count(): msg="mail already exits" raise ValidationError(msg) return mail i want to change error msg with email already exists to alert popup in window. -
CSRF cookie not set when calling POST request API view
I have encountered a weird behavior as it works with one view but does not with another. Django 3.2 and rest framework 3.13.1 are currently installed within the venv. When I call the view I get the error message: CSRF validation failed, reason CSRF cookie not set. This view uses an own authentication class that extends TokenAuthentication. class APIKeyAuthentication(authentication.TokenAuthentication): logger = logging.getLogger(__name__) def authenticate(self, request): # try to get api key via X-API_KEY api_key = request.META.get("HTTP_X_API_KEY") # try to get api key via Authorization if not api_key: api_key = request.META.get("HTTP_AUTHORIZATION") if not api_key: return None platform_id, api_user = self.validate_api_token(api_key) return api_user, None That class is used as default within rest framework: REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "api.authentification.APIKeyAuthentication", "rest_framework.authentication.BasicAuthentication", ), "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ], Endpoints are: path("v1/combinedEntries", VerifyV1OrderView.as_view()), path("order/verify/", VerifyOrderView.as_view()), Classes: class VerifyV1OrderView(GenericAPIView): serializer_class = CombinedEntryV1Serializer authentication_classes = (APIKeyAuthentication,) and class VerifyOrderView(GenericAPIView): serializer_class = CombinedEntrySerializer authentication_classes = (APIKeyAuthentication,) so I do not understand the error I even removed the session authentication from the config but without any change. Has someone an idea what the problem could be? Thanks and regards. Matt -
Django Rest Framework - "You do not have permission to perform this action" in tests
I have Profile model which is custom user model. When I try to change it (sending patch request) via postman, all is ok. But when I try to do it in tests in returns "You do not have permission to perform this action" in response with ststus code 403. Here is code: # models.py class Profile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) user_name = models.CharField(max_length=50, unique=True) first_name = models.CharField(max_length=50) surname = models.CharField(max_length=50) start_date = models.DateTimeField(default=timezone.now) image = models.ImageField(upload_to=photo_upload, default = 'profile_pics/default_avatar.jpg', null=True, blank = True) about = models.TextField(max_length=1024, blank = True, null = True) is_staff = models.BooleanField(default = True) is_active = models.BooleanField(default = True) objects = ProfileManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name', 'first_name'] objects = ProfileManager() def get_absolute_url(self): return reverse('user', kwargs = {'pk': self.pk}) def __str__(self): return f'{self.user_name}' def save(self, *args, **kwargs): super().save(*args, **kwargs) if not self.image: self.image = f"{os.path.join(MEDIA_ROOT, 'profile_pics')}/default_avatar.jpg" else: img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path)` # serializer class class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['email', 'user_name', 'first_name', 'surname', 'start_date', 'image', 'about', 'contacts'] read_only_fields = ['start_date', 'user_name'] # views.py class DetailUpdateDestroyUserAPI(RetrieveUpdateDestroyAPIView): Profile = apps.get_model('account', 'Profile') serializer_class = ProfileSerializer permisson_classes = [UserIsHimselfOrRO] lookup_field = 'user_name' def … -
Best practice using key stored in secret managers in django
I have db key stored in the aws secrets manager. My password is automatically generated and stored. const rdsCredentials: rds.Credentials = rds.Credentials.fromGeneratedSecret(dbInfos['user'],{secretName:`cdk-${targetEnv}-db-secret`}); const dbCluster = new rds.DatabaseCluster(this, 'Database', { engine: rds.DatabaseClusterEngine.auroraMysql({ version: rds.AuroraMysqlEngineVersion.VER_2_08_1 }), credentials: rdsCredentials, removalPolicy: cdk.RemovalPolicy.DESTROY, clusterIdentifier: dbInfos['cluster'], defaultDatabaseName :dbInfos['database'], instanceProps: { instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.SMALL), vpcSubnets: { subnetType: ec2.SubnetType.PRIVATE_ISOLATED, }, vpc, securityGroups:[mySecurityGroup], }, }); Now I can see the key in secrets manager and paste user/password in settings.config however it doesn't make use of secret manager. How can I use secret manager key in django ? -
When I trying to use *python* command in terminal it writes just 'Python' every time
When I trying to use python command in terminal it writes just 'Python' every time example: PS C:\Users\THE WORLD\Desktop\avtobot>python --version Python #Or PS C:\Users\THE WORLD\Desktop\avtobot>python manage.py makemigrations Python :Just like this how can I use this command But it is working when PS C:\Users\THE WORLD\Desktop\avtobot>py --version Python 3.10.4 But :) PS C:\Users\THE WORLD\Desktop\avtobot>py manage.py makemigrations Python and it is writing like this (and i tried to use python3 too) -
How to join 3 or more than 3 models in one single query ORM?
I am having 4 models linked with a foreign key, username = None email = models.EmailField(('email address'), unique=True) phone_no = models.CharField(max_length=255, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class personal_profile(models.Model): custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) picture = models.ImageField(default='profile_image/pro.png', upload_to='profile_image', blank=True) role = models.CharField(max_length=255, blank=True, null=True) gender = models.CharField(max_length=255, blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) def __str__(self): return str(self.pk) class academia_profile(models.Model): custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) education_or_certificate = models.CharField(max_length=255, blank=True, null=True) university = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return str(self.pk) class contact_profile(models.Model): custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) country = models.CharField(max_length=255, blank=True, null=True) state = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return str(self.pk) For extracting the data of those four models, I need to extract it by querying 4 times differently and then by passsing for different variables to HTML templates it something a hectic plus would be reducing the performance speed (I am sure!) My current queries be like user_base = CustomUser.objects.get(id=user_id) user_personal = personal_profile.objects.get(custom_user=user_id) academia = academia_profile.objects.get(custom_user=user_id) contact = contact_profile.objects.get(custom_user=user_id) Is it possible to get all of the four queries values in a single variable by hitting a single join query in ORM ? also, I want to extract just the country … -
failed to convert DJPADDLE_PUBLIC_KEY original message RSA key format is not supported
i'm trying to use Paddle as my payment subscription into my django website but its give me an error when i do /manage.py runserver failed to convert 'DJPADDLE_PUBLIC_KEY'; original message: RSA key format is not supported is anybody who can help me please. the settings.py file: DJPADDLE_PUBLIC_KEY '' DJPADDLE_API_KEY = '' DJPADDLE_VENDOR_ID = '' DJPADDLE_SANDBOX = False -
Add json response to a list
I am new in learning python requests and I am using GET METHOD and I am trying to insert returned json content in list, But it is showing TypeError: Object of type bytes is not JSON serializable I have tried many times and I also tried by adding into dictionary. views.py def request_get(request): url = "http://127.0.0.1:8000/api/items/" response = requests.get(url) results = [] results.append(response.content) return redirect('home') But it is showing TypeError: Object of type bytes is not JSON serializable I have also tried by using :- results = [] results.append({ 'response' : response.content }) Full Traceback Traceback (most recent call last): File "D:\apps - app\app\env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\apps - app\app\env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\app - app - app\env\lib\site-packages\django\http\response.py", line 653, in __init__ data = json.dumps(data, cls=encoder, **json_dumps_params) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 238, in dumps **kw).encode(obj) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "D:\app - app - app\env\lib\site-packages\django\core\serializers\json.py", line 106, in default return super().default(o) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type bytes is not JSON serializable But it … -
how to make spaces paid for ads in my django website
" I have created Django app for e-commerce for multiple vendors but i need to make the same idea for selling spaces for ads which can client login and ask for specific space to post his ads after accepting from admin and paying his ads will be publish I am trying to make image field with description but I am confused when he can pay?"