Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue with connecting to MongoDB docker container with another container
Having an issue with connecting to a docker container to another container. I'm able to connect to it locally outside the container but from within the container doesn't work. This is the stack trace pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 5f9cf7b6d9d395e79548d42a, topology_type: Single, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]> My docker-compose.yml file is pretty straight forward and simple. Nothing unique mongod: restart: always image: mongo:latest volumes: - ./mongodb/mongod.conf:/etc/mongod.conf ports: - "27017:27017" command: mongod app: build: ./app container_name: django-gunicorn restart: always env_file: - ./app/django.env ports: - "8000:8000" command: "gunicorn --workers=2 --bind=0.0.0.0:8000 webapp.wsgi:application" I've binded the port to 0.0.0.0 in the mongod.conf. What else am I missing? -
How to filter and paginate in ListView Django
I have a problem when I want to paginate the filter that I create with django_filter, in my template it shows me the query set and filter but paginate does not work, I would like to know why this happens and if you could help me. I'll insert snippets of my code so you can see. This is my views.py PD: i have all the necesary imports. @method_decorator(staff_member_required, name='dispatch') class EmployeeListView(ListView): model = Employee paginate_by = 4 def dispatch(self, request, *args, **kwargs): if not request.user.has_perm('employee.view_employee'): return redirect(reverse_lazy('home')) return super(EmployeeListView, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = EmployeeFilter(self.request.GET, queryset = self.get_queryset()) return context filters.py import django_filters from .models import Employee, Accident class EmployeeFilter(django_filters.FilterSet): class Meta: model = Employee fields = { 'rutEmployee' : ['startswith'] } and employee_list.html {% extends 'core/base.html' %} {% load bootstrap %} {% load static %} {% block title %}EMPLEADOS{% endblock %} {% block content %} <main role="main"> <div class="row"> <div class="col-md-12 stretch-card"> <div class="card"> <div class="card-body"> <p class="card-title">Lista de Empleados</p> <div class="table-responsive"> <form method="GET"> {{ filter.form|bootstrap }} <button type="submit" class="btn btn-primary">Filtrar</button> </form> <hr> <table class="table table-bordered"> <thead> <tr> <th>Rut</th> <th>Nombre</th> <th>Apellido Paterno</th> <th>Detalle</th> </tr> </thead> <tbody> {% for employee in filter.qs|dictsort:"id" reversed %} … -
Backend interfering with load times - Django
I am working on a project where a backend function in my Django project pulls data and then runs a data analysis on it. The issue I am encountering is that while this is happening the frontend shows a 404 error until the analysis is complete. As this will be client-facing is there a way to fix this without rewriting the analysis in Javascript? -
Django Video Wont Play How To Fix?
I am trying to load my basic video that I recored with gyazo but it wont load my video the video is a mp4 and the name is correct as well I loaded my {% static %} on top and made sure the video was in my static image file and in my setting is STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] correct as well I am not sure how to fix this problem this is how I load my videos from gyazo <video width="430" height="340" controls autoplay> <source src="{% static dam.mp4 %}" type="video/mp4"> </source> damcool </video> my full code <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Learn To Code</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <style> * { box-sizing: border-box; } body { font-family: Arial, Helvetica, sans-serif; } * { box-sizing: border-box; } body {font-family: "Times New Roman", Georgia, Serif;} h1, h2, h3, h4, h5, h6 { font-family: "Playfair Display"; letter-spacing: 0px; color: white; } /* Style the header */ .header { background-color: #58D68D; padding: 10px; text-align: center; font-size: 35px; } /* Create three equal columns that floats next to each other */ .column { float: left; width: 73.33%; padding: 10px; … -
Javascript runs in template html file but not extended html file in Django application
I am writing a website in Django and Vanilla JS I have 2 html pages, I want them both to share css but I want them to use different javascript. Both pages extend a layout.html. The layout.html looks begins like this {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Social Network{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'network/styles.css' %}" rel="stylesheet"> </head> My index.html (which extends my layout.html) begins like this {% extends "network/layout.html" %} {% load static %} <script src="{% static 'network/messages.js' %}"></script> and my Javascript file looks like this: document.addEventListener('DOMContentLoaded', function() { console.log("page loaded!") document.addEventListener('click', event => { const element = event.target; console.log("Something was clicked") }) }); It simply prints out a line when the page is loaded and when something is clicked. However, when I go to index.html with the code like this, the javascript file is not loaded, nothing is printed out when the page is loaded or when anything is clicked. However, if I modify the layout.html page to be like this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Social Network{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'network/styles.css' %}" … -
SMTPSenderRefused at /accounts/signup/
I tried to configure sending email on registration using gmail server and i get these error: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError u2sm3847520edr.70 - gsmtp', 'webmaster@localhost'). These are my configurations in settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') -
Django ImageField tamplate tag not displaying
The image is correctly saved to the static filed that I set in the setting filed. The image will display properly if I use a static path. But when I use a dynamic path, the image would not show and no error is given. As you can see the path, when called outside of , works correctly. But when puted inside of the , both {{item.image_1.path}}, nor {{item.image_1}},would show any picture. (item is the name of the model while image_1 is the name of the image_field) -----------For the not working dynamic path: {{item.image}} {{item.image.path}} <img src='{{item.image}}' alt=''> <img src='{{item.image.path}}' alt=''> [![for the not working method[1]][1] -----------For the working static path: {% static 'arrival7.png' as pic %} <img src='{{pic}}' alt=''> -
How can I restrict inserting data on behalf of another user in Django?
I have the following code in my django project. models.py from django.db import models class Doctor(models.Model): hospital = models.ForeignKey('auth.User', on_delete=models.CASCADE) name = models.CharField(primary_key=True, max_length=256, unique=True) education = models.CharField(max_length=256) class Patient(models.Model): doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) name = models.CharField(max_length=256) age = models.CharField(max_length=200) height = models.CharField(max_length=6) sex = models.CharField(max_length=12) serializers.py from rest_framework import serializers from .models import Doctor, Patient class DoctorSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = [ 'name', 'education' ] class PatientSerializer(serializers.ModelSerializer): class Meta: model = Patient fields = '__all__' views.py from rest_framework import status, permissions from rest_framework.response import Response from rest_framework.views import APIView from .models import Doctor, Patient from .serializers import DoctorSerializer, PatientSerializer class DoctorList(APIView): permission_classes = [permissions.IsAuthenticated] serializer_class = DoctorSerializer def get(self, request): doctors = Doctor.objects.filter(hospital=request.user) serializer = DoctorSerializer(doctors, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request): serializer = DoctorSerializer(data=request.data) if serializer.is_valid(): serializer.save(hospital=request.user) return Response({"message": "Doctor inserted!"}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class PatientList(APIView): permission_classes = [permissions.IsAuthenticated] serializer_class = PatientSerializer def get(self, request): patients = Patient.objects.filter(doctor__hospital=request.user) serializer = PatientSerializer(patients, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request): serializer = PatientSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"message": "Patient inserted!"}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) These views are then wired up with endpoints doctors/ and patients/ respectively. The problem I am having is restricting the owner … -
blog.Post.tags: (fields.E300) Field defines a relation with model 'Tag', which is either not installed, or is abstract. in django
I am making a django blog app. But when i run python manage.py makemigrations blog, I get this error: SystemCheckError: System check identified some issues: ERRORS: blog.Post.tags: (fields.E300) Field defines a relation with model 'Tag', which is either not installed, or is abstract. Here is my models.py: from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User from taggit.managers import TaggableManager class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. tags = TaggableManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'Comment by {self.name} on {self.post}' At first I thought that this error means I had not installed django-taggit. But when I … -
Logging with django rest framework with WSGI
I am fairly new in backend development. I was trying to write some log with Django rest framework. I set up the WSGI mode and the 000-default.conf file is <VirtualHost *:80> ServerAdmin user@gmail.com DocumentRoot /home/ubuntu/myproject_backend/myproject ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/myproject_backend/myproject/static <Directory /home/ubuntu/myproject_backend/myproject/static> Require all granted </Directory> <Directory /home/ubuntu/myproject_backend/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/ubuntu/myproject_backend/myproject python-home=/home/ubuntu/myproject_backend/env WSGIProcessGroup myproject WSGIScriptAlias / /home/ubuntu/myproject_backend/myproject/myproject/wsgi.py WSGIPassAuthorization On </VirtualHost> I added the LOGGING in the setting.py LOGGING = { 'version': 1, # Version of logging 'disable_existing_loggers': False, #disable logging 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'my_log.log', } }, 'loggers': { 'django': { 'handlers': ['file'], 'level': env("LOG_LEVEL"), 'propagate': True, }, }, } I tried with a simple warning log logging.warning("Logging Tutorials") Now the log is working when I was testing locally with the runserver command. However, when I pushed the code to the server it's getting permission denied writing the error.log file. PermissionError: [Errno 13] Permission denied I was wondering how do I give the permission and which user? the server is a ubuntu OS. I know there are a few posts about this issue. However, I could not figure out what exactly do I have to … -
How can I re-direct a user from the login page to the sign up page?
So, I have been trying to do this problem for a couple of days, but I seem to be having no luck, in actually solving it. For my side-project, I am creating a student grade management system in Django, and the problem that I am getting is that everytime the user clicks on the signup button on the homepage/login page, I get an error, because I haven't re-routed the user successfully. Specifically, the error I get is that it says, Page not Found. The page that I am trying to re-route the user to is in another app. So, I'm trying to route the user to the base url of that app, which from there, it will pop open a view. Here is the code for my urls.py on the loginpage/homepage (App1) from django.urls import re_path from django.shortcuts import redirect # import signUpPage.views as signupview from . import views urlpatterns = [ re_path(r'^$', views.login, name='login'), # re_path('signUpPage', signupview.register, name='signUpPage') # re_path('') ] Here is the code for my forms.py on the loginpage/homepage (App1) from crispy_forms.helper import FormHelper from crispy_forms.layout import Fieldset, Layout class loginForm(forms.Form): UserName = forms.CharField( label="Username", help_text="Please enter your username", widget=forms.TextInput(attrs={"placeholder":"Username"}), required=False ) Password = forms.CharField( label="Password", help_text="Enter … -
how to mock the django model?
i have to test a block of code ,like this: model: ''' class LoginHistory(models.Model): id = models.AutoField('ID', primary_key=True) class meta: db_table = 'login_table' ''' test model: ''' class TestLoginHistory(models.Model): id = models.AutoField('ID', primary_key=True) class meta: db_table = 'test_login_table' ''' util: ''' def registLoginHistory(self, loginId): model = LoginHistory(login_id=loginId) model.save() ''' test method: ''' def test_registLoginHistory(self): loginId = '003136130001' self.util.registLoginHistory(loginId) ''' now,i want to use TestLoginHistory(a django model) to change LoginHistory, so i try to use mock to do that. but it didnt work. it is the code i tried: ''' def test_registLoginHistory(self): loginId = '003136130001' LoginHistory = mock.MagicMock() LoginHistory.return_value.save = mock.MagicMock(side_effect=TestLoginHistory.save) self.util.registLoginHistory(loginId) ''' what should i do ? thx in advance. -
I can access my database with django and query it with objects.get() but objects.filter() will not work
I am just making a simple website as I am learning django. I have a view function that looks like this: def vieworkout(request): date= datetime.today() obj = userworkouts.objects.filter(userid=52) date = request.POST['date'] context = { 'exercise': obj.exercise } return render(request, 'clientIndex.html', context) when I use userworkouts.object.get() I can pass the exercise object no problem. When I change it to filter I get an error, "'QuerySet' object has no attribute 'exercise'". Does anyone know why this is happening? -
is there a way of defining function in models and save them to database as default by also filtering the fields? in Python Djnago
what i want to do is compute the value in percent for each learning styles there are and save them as default value to the field **result** on AssessmentLearningStyle model here is the model #MODEL_FOURTEEN class QuestionResults(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) student = models.ForeignKey(to=FacilityUser, on_delete=models.SET_NULL, null=True, blank=True) question = models.ForeignKey(to=QuestionLearningStyle, on_delete=models.SET_NULL, null=True, blank=True) agree = models.BooleanField(null=False) disagree = models.BooleanField(null=False) def __str__(self): return str(self.question) #MODEL_FIFTEEN class AssessmentLearningStyle(models.Model): @property def test(self): u = self.learning_style s = 0 if u == QuestionResults.question.learning_style: k = int(QuestionResults.objects.filter(agree=True, question__learning_style=self.learning_style).count()) l = int(QuestionResults.objects.filter(question__learning_style=self.learning_style).count()) if l != 0: s = (k/l) * 100 else: s = 0 return float(s) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) student = models.ForeignKey(to=FacilityUser, on_delete=models.SET_NULL, null=True, blank=True) assessent_date = models.DateField(blank=True, null=True) learning_style = models.ForeignKey(to=LearningStyle, on_delete=models.SET_NULL, null=True, blank=True) result = models.FloatField(default=test, editable=False) def __str__(self): return str(self.student) i want to save the value of test function to the result field...but it says float can't accept the value of property...and if i remove property... this method doesn't work at all...can you guys help me to fix this or show me a better way of doing this? Blockquote -
What would be the better way to write this class based view memcached caching
I am trying to do some caching in Django Here is what I have so far... # Jobs List View @method_decorator([vary_on_cookie, cache_page(900)], name='dispatch') class JobsListView( ListView): template_name = 'jobs_list.html' context_object_name = 'jobs' model = Job paginate_by = 6 def dispatch(self,request,*args,**kwargs): cache_key = 'my_jobs' # needs to be unique cache_key_featured = 'my_featuredjobs' # needs to be unique cache_time = 900 # time in seconds for cache to be valid datajobs = cache.get(cache_key) datafeatured = cache.get(cache_key_featured) if not datafeatured: cache.set(cache_key_featured, Discuss.objects.featured()[:5], cache_time) if not datajobs: cache.set(cache_key, super().get_queryset(), cache_time) return super(JobsListView,self).dispatch(request,*args,**kwargs) def get_context_data(self, **kwargs): context = super(JobsListView, self).get_context_data(**kwargs) cache_key = 'my_featuredjobs' # needs to be unique context["featured_discuss"] = cache.get(cache_key) if not context["featured_discuss"]: context["featured_discuss"] = Discuss.objects.featured()[:5] return context def get_queryset(self, *args, **kwargs): cache_key = 'my_jobs' # needs to be unique data = cache.get(cache_key) if not data: data = super().get_queryset() return data This looks awry to me. The fact that I have to do the cache.get() in all three methods, dispatch(), get_context(), get_queryset(). There must be a better way of doing this. What would be the better way to rewrite this class for better performance. -
"ValueError: year is out of range" with Django
When I started my current position, I inherited a Django Rest API that sits on top of our Postgres database. It was still running on Django v.1.7.11. Now almost two years later, I decided it's finally time to upgrade. I first upgraded to Django v1.11.29 (planning on getting it more current, but wanted to upgrade somewhat incrementally). I fixed any errors caused by the upgrade and was all set. I was able to access it and everything worked properly, except for reading data from one table. This table contains four date fields, and when accessing it's API endpoint, I get the following error: Request Method: GET Request URL: http://obis.twalk.tech:81/api/obis/occurrence/ Django Version: 1.11.29 Exception Type: ValueError Exception Value: year is out of range Exception Location: /usr/local/lib/python2.7/site-packages/django/db/utils.py in inner, line 101 Python Executable: /usr/local/bin/python Python Version: 2.7.18 From what I could tell initially with the debug output, this error was caused by having a null values in one of the date fields. I'm working in a personal development environment so I was able to change, at the database level, each instance of a null value in any of the date fields to be a properly formatted date. I still got the same … -
Got AttributeError when attempting to get a value for field `user` on serializer
I am trying to upload a csv file and then using it to populate a table in the database (creating multiple objects). serializers.py: class FileUploadSerializer(serializers.ModelSerializer): filedata = serializers.FileField(write_only=True) class Meta: model = WorkData fields = ['user', 'filedata'] def create(self, validated_data): file = validated_data.pop('filedata') data_list = csv_file_parser(file) # utility method batch = instantiate_batch_objects(data_list, validated_data['user']) # utility method work_data_objects = WorkData.objects.bulk_create(batch) # print(work_data_objects[0]) return work_data_objects views.py: class FileUploadView(generics.CreateAPIView): queryset = WorkData.objects.all() permission_classes = [IsAuthenticated] serializer_class = FileUploadSerializer def get_serializer(self, *args, **kwargs): print(kwargs.get('data')) if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super().get_serializer(*args, **kwargs) models.py class WorkData(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='work_data', ) work = models.IntegerField(blank=False, null=False) recordTime = models.DateTimeField(blank=False, null=True) When I upload the file and post it I get this error: Got AttributeError when attempting to get a value for field user on serializer FileUploadSerializer. The serializer field might be named incorrectly and not match any attribute or key on the list instance. Original exception text was: 'list' object has no attribute 'user'. But I can see table is populated successfully in the database. What could be the source for this error? -
Django collectstatic keeps waiting when run through Github Action
We are facing a very weird issue. We ship a django application in a docker container through Github Actions on each push. Everything is working fine except collectstatic. We have the following lines at the end of our CD github action: docker exec container_name python manage.py migrate --noinput docker exec container_name python manage.py collectstatic --noinput migrate works perfectly fine, but collectstatic just keeps on waiting if ran through the github action. If I run the command directly on the server then it works just fine and completes with in few minutes. Can someone please help me figuring out what could be the issue? Thanks in advance. -
TypeError: serve() got an unexpected keyword argument 'document_root'
my problem Here the image/file that the user uploaded aren't being displayed(They are being saved though!!) when I run the site using Terminal I get an error message on Terminal TypeError: serve() got an unexpected keyword argument 'document_root' but the site runs just fine. when I open my site on chrome it displays name of the image/file and only a symbol of an image/file but i want it to display the image/file it self not a symbol. Setting.py: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' ( This only some part of the urls.py) urls.py: from django.urls import path from django.conf import settings from django.conf.urls.static import static urlpatterns += static(settings.MEDIA_URL, documnet_root=settings.MEDIA_ROOT) ( This is also some part of the html file that displays the image) file.html {% if model.image %} <image src="{{model.image.url}}"> {% endif %} -
Django. Error saving empty string to DateTimeField(blank=True)
I have a model with a DateTimeField (blank=True, null=True). However, when I try to save an empty string in it, I get the following error: >>> from courses.models import Event >>> x = Event.objects.last() >>> x.date_start = "" >>> x.save() django.core.exceptions.ValidationError: ['“” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] I have never seen this, any ideas? All my migrations are up to date. -
Django + Mongo + Docker getting pymongo.errors.ServerSelectionTimeoutError
I've been struggling to get a simple app running using Django, Djongo, Mongo, and Docker Compose. My setup looks like this: docker-compose.yml services: mongodb: image: mongo:latest restart: always environment: MONGO_INITDB_ROOT_USERNAME: root MONGO_INITDB_ROOT_PASSWORD: mongoadmin MONGO_INITDB_DATABASE: django_mongodb_docker ports: - 27017:27017 web: build: ./src restart: always command: python src/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 links: - mongodb Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 RUN mkdir /code COPY . /code/ WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'HOST': 'mongodb', 'PORT': 27017, 'USER': 'root', 'PASSWORD': 'mongoadmin', 'AUTH_SOURCE': 'admin', 'AUTH_MECHANISM': 'SCRAM-SHA-1', } } What is annoying is that I am able to use pymongo from my web container to connect to the container running mongo. That works as follows. from pymongo import MongoClient c = MongoClient( 'mongodb://mongodb:27017', username='root', password='mongoadmin', authSource='admin', authMechanism='SCRAM-SHA-1') print(c.server_info()) The issue is that when I go to run migrations from within my web container I get the following error. pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 5f9c8d338cc55e515780edb9, topology_type: Single, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]> Any help on this would be greatly appreciated. -
How to edit the html page and save it at the same page using Django?
I have HTML page that contains a title and content that title, I had created an edit link that directs me to another page that should let me update the title and the content, and after editing click a button to save that update. How i can let the user do this kind of updating using Django? this is my HTML page <h1>CSS</h1> <p>CSS is a language that can be used to add style to an HTML page.</p> <ul> <li><a href="{% url 'wiki:edit' %}">Edit</a></li> </ul> -
How to write if else condition to retrieve data by querying django filter
I want to write if else condition for django filter to retrieve data by querying in django rest framework. I want to qerry data by filtering class CreateRoutineFilter(filters.FilterSet): class Meta: model = CreateRoutine fields = ('batchCode', 'roomCode') class CreateRoutineViewSet(viewsets.ModelViewSet): queryset = CreateRoutine.objects.all() serializer_class = CreateRoutineSerializer filterset_class = CreateRoutineFilter filter_backends = (django_filters.rest_framework.DjangoFilterBackend,) __basic_fields = ( 'dpt_code', 'roomCode') filter_backends = (filters.DjangoFilterBackend, OrderingFilter) filter_fields = __basic_fields def retrieve(self, request, *args, **kwargs): params=kwargs print(params['pk']) # programs = Program.objects.all() if(coursesOffered = CourseOffered.objects.filter(batchCode = params['pk'])) else: (coursesOffered = CourseOffered.objects.filter(dpt_code = params['pk'])) serializer = CourseOfferedMiniSerializer(coursesOffered, many=True) return Response(serializer.data) -
Django Rest API: View definition delete queryset
I'm still pretty new to creating views in Django Rest Framework, I can make basic views but I still have no clue about definitions so please help me out here. I've got this View which gets the answers of a question (by a given question id). The list definition works perfectly, however I want to make a delete_all function which deletes these results. You can see what I came up with below. URL router.register('manager/course/question/answers', QuestionAnswerView) http://.../manager/course/question/answers/5 works. http://.../manager/course/question/answers/delete_all/5 does not work. View class QuestionAnswerView(viewsets.ModelViewSet): queryset = QuestionAnswer.objects.all() serializer_class = QuestionAnswerSerializer # works def list(self, request): queryset = QuestionAnswer.objects.all() if request.query_params: question_id = request.query_params['question_id'] queryset = QuestionAnswer.objects.filter(question=question_id) serializer = QuestionAnswerSerializer(queryset, many=True) return Response(serializer.data) # does not work def delete_all(self, request): if request.query_params: question_id = request.query_params['question_id'] queryset = QuestionAnswer.objects.filter(question=question_id) queryset.delete() return Response('success') -
Stream multiple files with a single request using python requests
I'm using python's requests library to upload images into a server created by django / drf. It is a simple task and test script looks like this: files = { 'client_files[0]': ('415.png', open('E:\\Olaylar\\test_set\\cvat_test_small\\415.png', 'rb')), 'client_files[1]': ('422.png', open('E:\\Olaylar\\test_set\\cvat_test_small\\422.png', 'rb')), 'client_files[2]': ('485.png', open('E:\\Olaylar\\test_set\\cvat_test_small\\485.png', 'rb')) } payload = { 'image_quality': 50 } response = requests.post(post_url, auth=auth, data=payload,files=files) The problem is, I need to upload hundreds, if not thousands of images, and in a single request. So when I try to read all files into memory in order to post them, I run out of memory quite fast. I know there is a possible solution, by putting a generator in data argument of post method, and streaming the data by chunks. That would solve my problem quite well, but requests library does not support that functionality in files argument of the post method too. I will be grateful for any help or advice how to solve this problem. Thanks in advance