Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest sending response without complete func
Good afternoon, unfortunately I could not formulate my question for Google. How to make sure that my response is returned to the user without waiting for the telegram api to complete the request? -
name 'field_name' is not defined error while querying the db
I am trying to query a foreign key attribute i am getting error as name 'field_name' is not defined Mymodel.objects.filter(field_name) -
django admin search by foreign key in add form
In the form to add new objects in Django admin, sometimes there are linked foreign keys that are selectable in a dropdown. Is there a way to include a searchbox for the foreign keys within the form? For example, let's say I have a Book model with a foreign key to Author object. Instead of scrolling through all the author ids when I create a new Book object, can I search for Author "James" specifically? -
How can I solve application error on heroku?
I am trying to create an app on django and I am trying to host it on heroku. Everything runs perfectly locally. I get an error while trying to migrate the database onto the heroku app by running command - heroku run python manage.py migrate This is the error I am getting - Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/base.py", line 230, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/base.py", line 211, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 199, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.9/site-packages/psycopg2/__init__.py", line 121, in connect dsn = _ext.make_dsn(dsn, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/psycopg2/extensions.py", line 167, in make_dsn parse_dsn(dsn) psycopg2.ProgrammingError: invalid dsn: invalid connection option "init_command" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 90, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line … -
delete using queryset in django is not working
i have one model in my django application, which i used as a foreign key in other models. Below is the screenshot of my model. When i use .delete it is generating an error. Please check below screenshot. I am not able to find why this generating an error. -
How to send a file to a specific directory with FTP?
I want to upload a file to the server. I created a function for that but it saves the main directory. I want to save it a specific directory. My address is api.myaddress.com and I want to upload it to api.myaddress.com/uploads/arms. How can I do it? file_address = ("C:/user/otc/"+pdf.pdf.name) session = ftplib.FTP('api.myaddress.com', ftp_username, ftp_password) file = open(file_address, 'rb') # file to send session.storbinary('STOR '+pdf.pdf.name, file) # send the file file.close() # close file and FTP session.quit() -
Django database queries
I want to change this code to a faster query, response = [] for player in Player.objects.all(): total_earn = Credit.objects.filter(player=player).aggregate(Sum('amount')).get('amount__sum', 0) total_earn += Purchase.objects.filter(player=player).aggregate(Sum('amount')).get('amount__sum', 0) reponse.append([player.id, player.email, player.phone, total_earn]) -
Boto3 AWS python
Need a little help with the boto3 client, I would like to send message to AWS sqs. The flow is, that I will have one parent class with the default settings and two child classes, with unique parameters. (this is because the message is different for two child classes and context as well). I don't understand what need to be include in base class and how to inherit it in child with separate parameters. The message will be sent in JSON. Cant find any answer or similar topics on WEB What I have right now: import boto3 import logging import json from abc import ABC, abstractmethod from rest_framework.renderers import JSONRenderer logger = logging.getLogger(__name__) class BaseQueueController(ABC): """" Base controller for Amazon SQS """ def __init__(self): sqs = boto3.client('sqs', region_name=region, aws_access_key_id=access, aws_secret_access_key=ssecret, endpoint_url=endpoint, ) @abstractmethod def send(self, sqs, body: str, attributes: Dict): try: sqs.send_message( QueueUrl=url, MessageBody=body, MessageAttributes=message_attributes, ) except Exception as e: logger.error(f"Error {e} on trying to send message {sqs}") class TwitterSqs(BaseQueueController): """" SQS child first """ pass class YoutubeSqs(BaseQueueController): """" SQS child second """ pass -
I am try too write to register a user in Django with username where no special character include in the username
here is my forms.py from django import forms from django.forms import fields, models from numpy import not_equal from .models import TextToAudio from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class TextForm(forms.ModelForm): class Meta: model=TextToAudio fields="all" class SignUpForm(UserCreationForm): username = forms.CharField(required=True , widget=forms.TextInput(attrs={'placeholder': 'username'}),not_equal) first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.' , widget=forms.TextInput(attrs={'placeholder': 'xyz@gmail.com'})) password1 = forms.CharField(required=True , widget=forms.PasswordInput(attrs={'placeholder': 'password'})) password2 = forms.CharField(required=True , widget=forms.PasswordInput(attrs={'placeholder': 'confirm password'})) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) -
can I grab some specific third api data as an additional property to my django api view?
I have an api view which fetches data from its model. I want this api view to have an additional value from third party api. Here is views.py which grabs all of its model properties. @api_view( ["GET"], ) def bussiness_asset_risk_details(request): res = models.BusinessImpact.objects.all().values( "hierarchy", "business_assets", "asset_name", "vendors", "product", "version", "cpe", "asset_type", "asset_categorization", "_regulations", "asset_risk", ) return Response({"business_impact_details": res}) Here is third party api view fetching a specific values of it's own. @api_view( ["GET"], ) def cve_summery(request, key): r = requests.get( "https://services.nvd.nist.gov/rest/json/cves/1.0?cpeMatchString={}".format( key) ) if r.status_code == 200: result = [] res = r.json().get("result").get("CVE_Items") for rs in res: data = { "VulnID": rs.get("cve").get("CVE_data_meta").get("ID"), "Summery": rs.get("cve").get("description").get("description_data"), "exploitabilityScore": rs.get("impact") .get("baseMetricV2") .get("exploitabilityScore"), "severity": rs.get("impact").get("baseMetricV2").get("severity"), "impactScore": rs.get("impact").get("baseMetricV2").get("impactScore"), } result.append(data) return Response(result) return Response("error happend", r.status_code) The logic here is, I want bussiness_asset_risk_details view to return "severity": rs.get("impact").get("baseMetricV2").get("severity"), from cve_summery view. NB: THE KEY parameter in cve_summery view IS cpe of bussiness_asset_risk_details Thanks. -
How to deploy django app using bitbucket pipelines
I want to deploy my Django app which is dockerized using BitBucket pipelines to AWS EC2 instance. How can I deploy to EC2 using BitBucket pipelines? -
Django : Max retries exceeded with url: /o/token/ [Errno 11001] getaddrinfo failed
Hey guys I'm creating a multi-tenant app using DJANGO TENANTS and DRF I'm trying to create a login api using the following function login api-view @api_view(['POST']) @permission_classes([permissions.AllowAny]) def login(request): restaurant_name = request.POST.get('restaurant_name') email = request.POST.get('email') password = request.POST.get('password') restaurant_schema = restaurant_name if not restaurant_name: restaurant_schema = 'public' domain_name = 'http://localhost:8000/o/token/' else: domain_name = 'http://' + restaurant_name + '.localhost:8000/o/token/' with schema_context(restaurant_schema): # c = Client.objects.get(name='BFC') # return Response(c.reverse(request,'test')) app = Application.objects.first() r = requests.post(domain_name, data={ 'grant_type': 'password', 'username': email, 'password': password, 'client_id': app.client_id, # 'scope': 'read', 'client_secret': app.client_secret, },) return Response(r.json()) But I'm getting this error: HTTPConnectionPool(host='bfc.localhost', port=8000): Max retries exceeded with url: /o/token/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001E24200D600>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')) I have tried to check the connection using: socket.create_connection(('localhost',8000),timeout=2) and socket.create_connection(('bfc.localhost',8000),timeout=2) bfc.localhost cant create a connection yet localhost and also I can access the domain from my browser Additional info: In Postman OAuth 2 section I can get a response with the same fields enter image description here -
Got a `TypeError` when calling `WordsTable.objects.create()`
I am trying to save some data in the database using serializer. I have created a model and a serializer but I get this error when I try to save the data. I have seen many answers but haven't come up with the solution. I get this error:Got a TypeError when calling WordsTable.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to WordsTable.objects.create(). You may need to make the field read-only, or override the WordsTableSerializer.create() method to handle this correctly. models.py: class WordsTable(models.Model): session_id = models.IntegerField(db_column='session_ID', blank=True, null=True) # Field name made lowercase. user_id = models.IntegerField(db_column='user_ID', blank=True, null=True) # Field name made lowercase. date = models.DateField(blank=True, null=True, default=datetime.date.today) hour = models.TimeField(blank=True, null=True, default=datetime.date.today) run_label = models.IntegerField(blank=True, null=True) status = models.IntegerField(blank=True, null=True) word1 = models.CharField(max_length=45, blank=True, null=True) word2 = models.CharField(max_length=45, blank=True, null=True) word3 = models.CharField(max_length=45, blank=True, null=True) word4 = models.CharField(max_length=45, blank=True, null=True) word5 = models.CharField(max_length=45, blank=True, null=True) class Meta: db_table = 'words_table' The serializer: class WordsTableSerializer(serializers.ModelSerializer): class Meta: model = WordsTable fields = "__all__" Views.py: #API @api_view(['POST']) def save_words(request): if request.method=="POST": saveserialize=WordsTableSerializer(data=request.data) if saveserialize.is_valid(): saveserialize.save() return Response(saveserialize.data, status=status.HTTP_201_CREATED) return Response(saveserialize.data, status=status.HTTP_400_BAD_REQUEST) What do I have to add? it's the first … -
Migrating from SQLite to MySQL error: django.db.utils.OperationalError: Problem installing fixture
I've migrated to MySQL from SQLite in my Django project. I've changed the DB settings in settings.py, I've exported my data to a JSON file and I've ran migrations to change to the MYSQL DB. I am at the stage to load the data into the new MYSQL DB I used: python manage.py loaddata datadump.json but it came up with the following error: django.db.utils.OperationalError: Problem installing fixture '/home/myuser/djangoproject/djangoproject/datadump.json': Could not load userfiles.File(pk=61): (1054, "Unknown column 'data' in 'field list'") Any ideas on how I can resolve this? -
How to add google analytics to a Django website dashboard?
I have linked my website hosted on heroku to google analytics. I want to display all the analytics on the dashboard of my website. I tried every stack overflow answer but nothing seemed to work for me. Can anyone please help? -
Context has no dynamic value while sending email with send_mail() in django
I am trying to send mail with dynamic valued templates in django, But the parameter context sends nothing to the template tasks.py def send_verification_mail(username,mail): msg_html = render_to_string('templates/email.html', {'context':"value","context2":"value2"}) html=strip_tags(msg_html) send_mail( 'From online store', 'Welcome '+username, 'praveenkumarstream@gmail.com', [mail], html_message=html, fail_silently=False, ) email_template.html <html> <body>To verify click below<br> <button> Verify your account</button> {{context}} {{context2}} </body> </html> -
Strange behaviour when deleting items using Django and React stack applications
I work on a full stack application that is composed of: Django (Django Rest Framework) React PostgreSQL database Redis Celery It is deployed through docker. Whole application works well and has no bugs that cannot be traced. However, when I try to delete Project item from database (this is domain specific), I get error 500 and no specific trace. I figured this bug out on deployed application. While inspecting Networking tab in Developer Tools I found the request and saw 500 return code. However, nothing was returned in returned in Response. However, I think something should have been returned. Code is as such: class ProjectCRUD(GenericAPIView): # [...] def delete(self, request, pk): try: # [...] code that deletes all referenced values and current project except ProtectedError as e: return JsonResponse({ "error": "Project still referenced", "details": str(e) }, status=400) except Exception as e: return JsonResponse({"error": "Wrong project id"}, status=status.HTTP_400_BAD_REQUEST) return JsonResponse({ 'message': f'Project with id {project_id} was deleted successfully!' }, status=status.HTTP_204_NO_CONTENT) # [...] This "Wrong project id" assumption is by all means bad and this will be refactored as soon as this bug is also found. This code makes sure that if exception is raised, it is caught, something is returned with … -
Operation of standard Django view, form and template code to update a model
I am trying to understand how a very regularly used code-form in Django views.py actually works. I see the following (or a variation) used a lot, but I can’t find a line-by-line explanation of how the code works – which I need if I am to use it confidently and modify when needed. I will start with the model then introduce urls.py the view and the form. I will go through the relevant parts of the code. I will consider: The model: #models.py class CC_Questions(models.Model): # defining choices in Model : https://docs.djangoproject.com/en/4.0/ref/models/fields/ personality = [ ('IF','IF'), ('IT','IT'), ('EF','EF'), ('ET','ET'), ] q_text = models.CharField('Question text', max_length=200) #C1_Type = models.CharField('Choice 1 Type', max_length=2) C1_Type = models.CharField(choices=personality, max_length=2) Choice1_text = models.CharField('Choice 1 text', max_length=100) #C2_Type = models.CharField('Choice 2 Type', max_length=2) C2_Type = models.CharField(choices=personality, max_length=2) Choice2_text = models.CharField('Choice 2 text', max_length=100) # def __str__(self): return self.q_text[:20] The url # #urls.py app_name = ‘polls’ urlpatterns = [ ….. # ex: /polls/p2create path('p2create/', p2_views.p2create, name='p2create'), … The view: #views.py from.forms import Anyform # def p2create(request): if request.method == 'POST': form = AnyForm(request.POST) if form.is_valid(): form.save() return redirect('/polls/p2') else: form = AnyForm() context = {'form' : form} return render(request, 'pollapp2/create.html', context) # The form: #forms.py # …. … -
How to show foreign key strings related value in Django Rest Framework
I get responses in foreign key values as shown below image Image is here but I want the response of values in string which Is returned from str method in models file. my models is given below from django.db import models from django.contrib.auth.models import AbstractUser,AbstractBaseUser from .Manager import Custom_Manager # Create your models here. class user_profile(AbstractUser): username = None first_name = models.CharField(max_length=250,blank=True,default='') last_name = models.CharField(max_length=250,blank=True,null=True,default='') email = models.EmailField(verbose_name='email_address', max_length=255, unique=True) address=models.CharField(max_length=250) profile_picture=models.ImageField(upload_to='Profile Pictures', blank=True) objects = Custom_Manager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email; class Category(models.Model): name=models.CharField(max_length=250,null=True,blank=True) def __str__(self): return self.name; class Services(models.Model): s_name=models.CharField(max_length=255) provider_user=models.ForeignKey('digi_khidmat.user_profile',on_delete=models.CASCADE) category=models.ForeignKey(to='digi_khidmat.Category',on_delete=models.CASCADE ,blank=True,null=True) Services_image=models.ImageField(upload_to='Services', blank=True,null=True) description=models.CharField(max_length=1000,blank=True) services_rate_per_hour=models.IntegerField() def __str__(self): return self.s_name class request_services(models.Model): services = models.ForeignKey(to='digi_khidmat.Services', on_delete=models.CASCADE,related_name="Services") provider_user = models.ForeignKey(to='digi_khidmat.user_profile', on_delete=models.CASCADE,related_name="service_provider") category = models.ForeignKey(to='digi_khidmat.Category', on_delete=models.CASCADE, blank=True, null=True ) request_user = models.ForeignKey(to='digi_khidmat.user_profile', on_delete=models.CASCADE,related_name="request_user") status=models.ForeignKey(to='digi_khidmat.services_status', on_delete=models.CASCADE,related_name="request_user") class services_status(models.Model): status=models.CharField(max_length=10,default='Pending') def __str__(self): return self.status; my Serializer class is below class user_profile_serializer(serializers.ModelSerializer): class Meta: model=user_profile fields='__all__' class Category_serializer(serializers.ModelSerializer): class Meta: model=Category fields='__all__' class Services_serializer(serializers.ModelSerializer): class Meta: model=Services fields='__all__' class Services_status(serializers.ModelSerializer): class Meta: model=services_status fields='__all__' class request_services_serializer(serializers.ModelSerializer): serviese_name=serializers.StringRelatedField(read_only=True) class Meta: model=request_services fields='__all__' when i convert serviese_name=serializers.StringRelatedField(read_only=True) to serviese_name=serializers.StringRelatedField(read_only=True, many=True) it throws the following error ceback (most recent call last): File "C:\Users\Muhammad Arshad\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = … -
How to write class based testview for Django Channels using unittest module
I am trying to write unittests for my web sockets. I haven't wrote any previously so I am struggling understanding how to write using module unittest python package. This is my consumer: class DepartmentInfoConsumer(JsonWebsocketConsumer): def connect(self): if not self.scope["user"]: raise DenyConnection() self.accept() self.group_name = "test" async_to_sync(self.channel_layer.group_add)(f"department{self.scope['company'].id}", self.channel_name) departmentobject = Department.objects.get(company=self.scope["company"]) self.send_json({"used_id": departmentobject.my_id}) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)(f"department{self.scope['company'].id}", self.channel_name) raise StopConsumer() def used_id_info(self, event): self.send_json({"used_id": event["used_id"]}) MY URL: websocket_urlpatterns = [ re_path("bill/", consumers. DepartmentInfoConsumer.as_asgi(), name="billing-ws"), ] -
django error with postgresql database on real host
this is my first python programe to run on server and i have error in database connection. when i add this line to setting file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'rahepooy_afsoone_db', 'USER': 'rahepooy_afsoone', 'PASSWORD': '****************', } } and migrate the code i have error : psycopg2.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? if i add "hoset':'IP' to setting.py i have this error : psycopg2.errors.UndefinedColumn: column c.relispartition does not exist LINE 3: CASE WHEN c.relispartition THEN 'p' WHEN c.relki... where is my mistake!? and this project is on real host on internet -
Can anyone help me,when i send mail through django send mail i am getting errors,if i send mail without deploy then it working [closed]
but if i send without deploy , it's working 1: enter image description herehttps://i.stack.imgur.com/AhOTz.jpg*emphasized text* -
I want to print my data on html that is stored in excel sheet(xlsx), actually i am getting output but it is not in a proper way . please check code
Views.py info = [] def get_info(request): r1 = pd.read_excel('file_data.xlsx') for index, row in r1.iterrows(): if row["USER NAME"] == str(user_name()): info.append(row) #name = row['USER NAME'] #date = row['DATE'] #file_name = row['FILE NAME'] #remarks = row['REMARKS'] return render(request,'files.html',{'info':info}) #return render(request,'files.html',{'name':name, 'date':date, 'file_name':file_name, 'remarks':remarks, 'info':info}) output enter image description here I need to print data in corresponding fields but it coming only in single field in list format. -
What queryset should I do to select all One-to-one relations that are broken?
I have this 2 models : class Asset(models.Model): created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) ... some other fields ... class AssetConstructorData(models.Model): asset = models.OneToOneField( Asset, on_delete=models.CASCADE, primary_key=True, related_name='constructor_data', ) ... some other fields ... For some historical reason, I have some One-to-one which are broken : some AssetConstructorData object has not their corresponding Asset object. I would like to delete all AssetConstructorData objects that are broken. Actually I have done : for cd in AssetConstructorData.objects.all(): try: cd.asset except Asset.DoesNotExist: cd.delete() Which is definitively not optimized : Is that possible to make a queryset that selects all broken relations ? I tried with .filter(asset=None) and .filter(asset__isnull=True) but it does not work. -
Getting issue while edit record in Django Form
I Everyone i am getting issue while edit record based on problem id, only problem record show automatically chatquestion and option record not show automatically, maybe my ORM is wrong somewhere, please help me out. this is crud operation i have done list and add record but that is also complex if anyone can do simple its more helpful for me.. Thanyou. models.py -this is all 3 models. class Problem(models.Model): Language = models.IntegerField(choices=Language_CHOICE, default=1) type = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return self.type class ChatQuestion(models.Model): question = RichTextField(null=True, blank=True) problem_id = models.ForeignKey( Problem, models.CASCADE, verbose_name='Problem', ) sub_problem_id = models.ForeignKey( SubProblem, models.CASCADE, verbose_name='Sub Problem', null=True, blank=True ) def __str__(self): return self.question class Option(models.Model): option_type = models.CharField(max_length=250, null=True, blank=True) question_id = models.ForeignKey( ChatQuestion, models.CASCADE, verbose_name='Question', ) problem=models.ForeignKey( Problem, models.CASCADE, verbose_name='Problem', null=True, blank=True ) next_question_id = models.ForeignKey(ChatQuestion, on_delete=models.CASCADE, null=True, blank=True, related_name='next_question') forms.py class Editchatbot(forms.Form): problem=forms.ModelChoiceField(queryset=Problem.objects.all(), required=True, widget=forms.Select(attrs={'class': 'form-control select2'})) question=forms.ModelChoiceField(queryset=ChatQuestion.objects.all(), required=True, widget=forms.Select(attrs={'class': 'form-control select2'})) option=forms.ModelChoiceField(queryset=Option.objects.all(), required=True, widget=forms.Select(attrs={'class': 'form-control select2'})) class Meta: fields=['problem','question','option'] views.py def edit_chatbot(request,id=None): problem=Problem.objects.get(pk=id) question=ChatQuestion.objects.filter(problem_id=id) option=Option.objects.filter(question_id=id) if request.method == 'POST': form = Editchatbot(request.POST) if form.is_valid(): problem=form.changed_data['problem'] question=form.changed_data['question'] option=form.changed_data['option'] form.save() messages.success(request,'successfully!') return redirect('/fleet/chatbot_list') else: messages.error(request,'Please correct following',form.errors) else: form = Editchatbot(initial={'problem':problem,'question':question,'option':option}) context = { 'menu_management': 'active', 'chatbot': 'active', 'form': form, 'question':question, 'option':option …