Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Running multiple django apps in apache https server one in / and another in /app2
I am trying to deploy two django apps in same server ssl port 443. While I comment following three lines in first block app2 is running while commenting in second block app1 is running and when uncommenting in both block both apps is not running and showing Internal Server Error and apache error log showing "mod_wsgi (pid=48352): Failed to exec Python script file '/var/www/html/app1/app1/wsgi.py'." WSGIDaemonProcess ...... WSGIProcessGroup ...... WSGIScriptAlias ...... *my default.conf file VirtualHost :443 block is as follows Alias /static /var/www/html/app1/static <Directory /var/www/html/app1/static> Require all granted </Directory> <Directory /var/www/html/app1/app1> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess app1 python-path=/var/www/html/app1 WSGIProcessGroup app1 WSGIScriptAlias / /var/www/html/app1/app1/wsgi.py ######################################################################################## Alias /museum/static /var/www/html/app2/static <Directory /var/www/html/app2/static> Require all granted </Directory> <Directory /var/www/html/app2/app2> <Files wsgi.py> Require all granted </Files> </Directory> #WSGIDaemonProcess app2 python-path=/var/www/html/app2 #WSGIProcessGroup app2 #WSGIScriptAlias /app2 /var/www/html/app2/app2/wsgi.py for the above code app1 is running perfectly Alias /static /var/www/html/app1/static <Directory /var/www/html/app1/static> Require all granted </Directory> <Directory /var/www/html/app1/app1> <Files wsgi.py> Require all granted </Files> </Directory> #WSGIDaemonProcess app1 python-path=/var/www/html/app1 #WSGIProcessGroup app1 #WSGIScriptAlias / /var/www/html/app1/app1/wsgi.py ######################################################################################## Alias /museum/static /var/www/html/app2/static <Directory /var/www/html/app2/static> Require all granted </Directory> <Directory /var/www/html/app2/app2> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess app2 python-path=/var/www/html/app2 WSGIProcessGroup app2 WSGIScriptAlias /app2 /var/www/html/app2/app2/wsgi.py for the above code app2 is running … -
Azure-pipelines: No module named "xmlrunner"
There seem to be many "No module names..." on Azure Pipelines issues in Stackoverflow... and now, as none of them helped me, it's my turn :( This is the pipeline I'm trying to run: a simple CI to test my Django app, based on Microsoft's own template: trigger: - master pool: vmImage: ubuntu-latest strategy: matrix: Python310: PYTHON_VERSION: '3.10' maxParallel: 2 steps: - task: UsePythonVersion@0 inputs: versionSpec: '$(PYTHON_VERSION)' architecture: 'x64' - task: DownloadSecureFile@1 name: dotEnv inputs: secureFile: 'uploaded.env' - task: PythonScript@0 displayName: 'Export project path' inputs: scriptSource: 'inline' script: | """Search all subdirectories for `manage.py`.""" from glob import iglob from os import path # Python >= 3.5 manage_py = next(iglob(path.join('**', 'manage.py'), recursive=True), None) if not manage_py: raise SystemExit('Could not find a Django project') project_location = path.dirname(path.abspath(manage_py)) print('Found Django project in', project_location) print('##vso[task.setvariable variable=projectRoot]{}'.format(project_location)) - task: CopyFiles@2 displayName: 'Add .env file' inputs: SourceFolder: '$(Agent.TempDirectory)' Contents: 'uploaded.env' TargetFolder: '$(projectRoot)' - script: mv uploaded.env .env displayName: 'Rename .env file' - script: | python -m pip install --upgrade pip setuptools wheel python -m pip install poetry python -m pip install unittest-xml-reporting xmlrunner poetry install displayName: 'Install dependencies' - script: | pushd '$(projectRoot)' poetry run python manage.py test --testrunner xmlrunner.extra.djangotestrunner.XMLTestRunner --no-input poetry run coverage xml displayName: … -
Django FileField with custom storage still uploads to default storage (GoogleCloudStorage)
I want to upload files to custom storage, other than the one for static. But each time when i try to declare a custom google cloud storage bucket, it still refers to the bucket related to statics (probably to the default storage) I am trying to Declare a new class from wagtail's AbstractDocument class class VirtualVisitDocs(AbstractDocument): file = models.FileField(storage=CustomGoogleCloudStorage(), verbose_name=_('file')) Then using it as a foreign key for another wagtail page with document chooserpanel as follows: virtual_visit = models.ForeignKey( VirtualVisitDocs, on_delete=models.SET_NULL, verbose_name=_('Virtual Visit Zip File'), related_name='promotion_pages', null=True, blank=True, ) MultiFieldPanel( [ DocumentChooserPanel("virtual_visit"), ], heading=_("Virtual Visit"), classname="collapsible collapsed", ), The storage instance from above CustomGoogleCloudStorage is the one which I have declared as follows: @deconstructible class CustomGoogleCloudStorage(GoogleCloudStorage): def get_default_settings(self): default_settings = super().get_default_settings() default_settings['bucket_name'] = settings.GS_VIRTUAL_TOUR_BUCKET_NAME default_settings['project_id'] = settings.GS_VIRTUAL_PROJECT_ID return default_settings Each time I try to upload documents this way, I get HTTP 403 which is correct, cause the service account I am using is not allowed to make changes on the default bucket. Rather, I want files to be uploaded to the second bucket where my service account is allowed to create bucket instance objects, but I just can't point to that another bucket. Whenever I try to print custom CustomGoogleCloudStorage … -
How do I fill in the ProcessedImageField after saving the original image?
How do I fill in the ProcessedImageField after saving the original image? I tried to override the save method, smth like this: class A(models.Model): original = models.ImageField() webp_1x = ProcessedImageField(format='WEBP', processors=[ResizeToFit(320, 320), null=True, blank=True) webp_2x = ProcessedImageField(format='WEBP', processors=[ResizeToFit(640, 640)], null=True, blank=True) def save(self, *args, **kwargs): self.webp_1x = self.original self.webp_2x = self.original super().save(*args, **kwargs) But it doesn't work. Unfortunately, there is no argument source in ProcessedImageField -
How can I use 2 websocket in same page?
I am developing a django project and in chat page you can send message other people using websockets but in the same page I want to use webRTC to make video call but in asgi.py how can I define 2 different websocket or is there a better way to solve this problem. asgi.py: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') application = get_asgi_application() ws_pattern = [] application = ProtocolTypeRouter({ "websocket" : AuthMiddlewareStack(URLRouter( chat.routing.websocket_urlpatterns )) }) application2 = ProtocolTypeRouter({ "websocket" : AuthMiddlewareStack(URLRouter( call.routing.websocket_urlpatterns )) }) chat.roting: websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer.as_asgi(),name="websocketreconnect"), ] call.routing: websocket_urlpatterns = [ re_path(r'ws/call/', consumers.CallConsumer.as_asgi()), ] -
How do i modify my create function in Django model manager
So i have this model: class Token(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False) code = models.IntegerField(default=code) date_created = models.DateTimeField(auto_now_add=True) expiration_date = models.DateTimeField(null=False, blank=True) as you can see I have an expiration_date field. The reason why I set it to (null=False, blank=True) is because I want it to fill itself based of the date_created field, and I'm trying to do that from the model manager create method I have little to no experience in model manager outside of custom user model manager. Here's my first failed attempt: class TokenManager(models.Manager): def create(self, user, code, date_created): exp = date_created + datetime.timedelta(minutes=10) token = self.model(user=user, code=code, date_created=date_created, expiration_date=exp) token.save() return token basically my goal here is to get the value of date_created field, add the value by 10 minutes and set it as the expiration_date. can anyone help me with this? -
Django: set DEBUG = False causes Server Error (500)
the templats work when DEBUG = True but change to False gives Server Error (500) i used django 3.2.8 This is views.py file def test(request): context = {} if request.method == "POST": uploaded_file = request.FILES['document'] print(uploaded_file) if uploaded_file.name.endswith('.csv'): #save file in media folder savefile = FileSystemStorage() name = savefile.save(uploaded_file.name, uploaded_file) #name of the file #know where to save file d = os.getcwd() #current directory of the project file_directory = d + '\media\\' + name readfile(file_directory) return redirect(results) else: messages.warning(request, 'File was not uploaded. Please use csv or xlsx file extension!') return render(request, 'test.html', {}) #project.csv def readfile(filename): global rows, columns, data, my_file, missing_values, mydict, dhead, dtail, dinfo, ddesc, dcor, graph, dheat my_file = pd.read_csv(filename, engine='python', index_col = False, sep='[: ; , | -]', error_bad_lines=False) data = pd.DataFrame(data=my_file) #my_file= read_file(filename) data = pd.DataFrame(data=my_file) mydict = { "data ": data.to_html(), } #rows and columns rows = len(data.axes[0]) columns = len(data.axes[1]) #find missing data missingsings = ['?','0','--'] null_data = data[data.isnull().any(axis=1)] missing_values = len(null_data) def results(request): message = 'I found ' + str(rows) + ' rows and ' + str(columns) + ' columns. Missing data are: ' + str(missing_values) #message = info messages.warning(request, message) return render(request, 'results.html', context = mydict) This is settings.py file … -
WebSocket like grouping for Server Sent Events in Django
I have a Django website and I have a real-time "game" on it. Multiple people connect and play it. Every x seconds the users in the specific game will be getting updates. I have done this using WebSockets and it works, I would say, pretty good. The things I think that using WebSocket-s is an overkill, plus I'm not utilising the Bi-directional part of it, rather using it to get the updates from the server and using AJAX to send the data. I'm considering switching over to Server Sent Events. I've used it a bit and read about it online and have decided that it would be a good fit for my project (using it instead of WS). The "problem" that I have is that I'm not sure how to (I assume its possible) use something like a groups in ws. I've searched online and the best solution that I could find is doing the client side filtering, which although its totally fine, I do not prefer as I think it's a waste of resources. The way that I have it set up is that based on the url for the game, the users that are connecting would be placed … -
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 …