Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can we create object in desire database in rest framework
I'm creating project but that project is saving in the default database. I want to create that project in other database... I'm using CreatApiView.. class CreateProjectAPIView(generics.CreateAPIView): """This endpoint allows for creation of a Project""" queryset = Project.objects.using('notification_dev').all() serializer_class = serializers.ProjectSerializer def get_serializer(self, *args, **kwargs): serializer_class = self.get_serializer_class() kwargs["context"] = self.get_serializer_context() draft_request_data = self.request.data.copy() print("draft_request_data :",draft_request_data) kwargs["data"] = draft_request_data return serializer_class(*args, **kwargs) I don't get it how can i use that .using("otherdataName") in get_serializer -
TemplateDoesNotExist graphene/graphiql.html
I'm trying to setup Graphene, but have a following exception raised when open http://localhost:8000/graphql/ in browser: TemplateDoesNotExist at /graphql/ graphene/graphiql.html Request Method: GET Request URL: http://localhost:8000/graphql/ Django Version: 3.2.10 Added did whole setup, added to urls, configured schema, queries and mutations. But still not work. And even don't remember that ever needed to configure templates for Graphene. -
How do I add an image to the imagefield in django model that is present in the static folder?
Basically, I have an image file certificate.png in the static folder. I have written a view that will access this image and then write the student's name on it. I now want to add this image to the ImageField 'certificate' in the Model 'My_course'. I am not able to figure out how to do that. Please help. This is the view: def certificate(request, slug): course = My_course.objects.get(course=Course.objects.get(slug=slug), user=request.user) try: course.certificate.url except ValueError: image = Image.open('course/static/course/images/Certificate.png') draw = ImageDraw.Draw(image) font = ImageFont.truetype('course/static/course/fonts/Oswald-Medium.ttf', size=100) (x, y) = (700, 570) name = request.user.first_name + ' ' + request.user.last_name color = 'rgb(0, 0, 0)' draw.text((x, y), name, fill=color, font=font) image.save('course/static/course/images/Certificate'+str(course.id)+'.png') certimage = urllib.request.urlretrieve(static('course/images/Certificate'+str(course.id)+'.png')) course.certificate.save(os.path.basename(course.url), File(open(certimage[0], 'rb'))) course.save() return render(request, 'course/certificate.html', {'image':course.certificate,'msg':'Error did not occur'}) This is the model: class My_course(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) payment = models.ForeignKey(Payment, on_delete=models.CASCADE, blank=True, null=True) certificate = models.ImageField(blank=True, null=True) -
kubernetes create a persistent volume and use in my django app
I wouldd to create a persistent volume on my kubernetes (gcp) cluster and use it in my django app as , for example, media folder. On my kubernetes side i do: First create a volumes claim: apiVersion: v1 kind: PersistentVolumeClaim metadata: name: pvc-zeus namespace: ctest spec: accessModes: - ReadWriteOnce resources: requests: storage: 5Gi , then in my deployments.yaml i create a volume and associate to the pod: apiVersion: apps/v1 kind: Deployment metadata: name: django namespace: ctest labels: app: django spec: replicas: 3 selector: matchLabels: app: django template: metadata: labels: app: django spec: volumes: - name: cc-volume persistentVolumeClaim: claimName: pvc-zeus containers: - name: django image: gcr.io/direct-variety-3066123/cc-mirror volumeMounts: - mountPath: "/app/test-files" name: cc-volume ... then in my django settings: MEDIA_URL = '/test-files/' Here my Dockerfile: FROM python:3.8-slim ENV PROJECT_ROOT /app WORKDIR $PROJECT_ROOT COPY requirements.txt requirements.txt RUN pip install -r requirements.txt COPY . . RUN chmod +x run.sh CMD python manage.py runserver --settings=settings.kube 0.0.0.0:8000 when i apply volume claim on my cluster all was done (volume claim was created) but whe apply deployment.yaml no volume was created for the pods (also if i connect in bash to my pods, no folder test-files exist). How can i create a volume on my deployments pods … -
One specific module shows import error while other modules are imported in venv python
I have installed Django in venv and then installed suntimes, suntime and astral (all latest versions) in the same venv. But only Django is getting imported, other 3 modules are showing import error. I have a Mac with default python 2.7 and I have installed python 3.6 from python website long time back. PATH variable is set to 3.6 via nano editor and I have been using alias for python = python3. Django works fine with the alias or without alias, but other 3 modules just don’t get imported no matter I remove the alias too. I have tried putting the site_packages folder from my venv directly into my project folder and then the modules work fine, but this is not the right way. When I did like this and removed alias, the modules work with python3 and not the default python 2.7. So I am guessing the problem is somewhere with my venv and not PATH, but then why would Django get imported even with venv or without venv and others just won’t? I have tried basic troubleshooting of restarting the Mac and recreating venv and reinstalling Django and other modules but I am still back to where i … -
Django rest framework custom renderer in testing response
I'm trying to make my testing code in my django app. My app has a custom renderer class so the response will look like this: { "code": 422, "message": "Unprocessable Entity", "data": { "non_field_errors": [ "Unable to log in with provided credentials." ] } } My test code: class AuthenticationTestCase(TestCase): """Test login and registration""" def setUp(self): self.client = APIClient() def test_login_success(self): """Test success login""" payload = { 'email': 'test@test.com', 'password': 'password', 'is_active': True } create_user(**payload) res = self.client.post(LOGIN_URL, payload) self.assertEqual(res.data['code'], status.HTTP_200_OK) The client response only return: "non_field_errors": [ "Unable to log in with provided credentials." ] Question is, can I make my testing client response using my custom renderer class as well? -
Can we buld a django project with out source code?
I am building a django project in a business moto then I want to sold my project but I want to encrypt my source code. If any possibilities to build my project like (.pyc ,.exe or something else...). -
Access sql dump inside docker container django postgres
I'm using Django with Postgres database so I've created separate docker containers for Django and Postgres, now I want to share the dump file with my team but I'm unable to access the dump file, please let me know how can I access the dump file and after accessing it how can we import it using the container? docker-compose.yml version: "3.8" services: pgdb: image: "postgres" restart: always volumes: - postgres_data:/var/lib/postgresql/data/ ports: - "5432:5432" location inside db docker container -
Using absolute online location for Django templates
I am currently working on a django project, I have hosted it on heroku.And I don't really want to keep pushing to heroku unless really necessary, so i thought of pushing the templates to github , where i can change at ease and no extra zipping and host timer is needed. My problem is I am unable to set a link to a file online as template location in django. Is this possible? how to alter the following lines in settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [T], 'APP_DIRS': False, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] to get template from say https://gitcdn.link/cdn/KarthikRaja2k1/ieeesb_public/master/home_templates/500.html -
How to pass a video return from JavaScript to python backend in Django view for OpenCV
I want to do certain tasks and the processes are as follows: 1. Access the camera of the user to get the video-frames from them. 2. Process the video frames from the backend code for facial recognition and some more tasks. 3. Return the processed frame back to the user. Initially, I had used cv2.VideoCapture(0) and it was simply triggering the camera of the system which was hosting the server, i.e. my personal laptop. So, I used JavaScript to trigger the camera of the user's system. The HTML and JS code is as follows: <div id="container"> <video autoplay="true" id="videoElement"> </video> </div> <script> var video = document.querySelector("#videoElement"); if (navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({ video: true }) .then(function (stream) { video.srcObject = stream; }) .catch(function (err0r) { console.log("Something went wrong!"); }); } </script> Now I want to get the video feed from the user and link it to the backend to process the video frames. My views.py : class VideoCamera(): def __init__(self): self.video = cv.VideoCapture(0) success, frame = self.video.read() ... -
Django - "get raise self.model.DoesNotExist: Course matching query does not exist
I am building a LMS from a tutorial using Django backend with Vue.js for the frontend. I keep getting the following traceback when I try to post a comment to a lesson on the site. get raise self.model.DoesNotExist( course.models.Course.DoesNotExist: Course matching query does not exist. [23/Dec/2021 12:18:25] "POST /api/v1/courses/undefined/Heat_Transfer_understand/ HTTP/1.1" 500 102326 I believe Django is throwing this error due to the Foreignkey being used on the Course Model in views.py: from django.shortcuts import render from rest_framework import serializers from django.core.exceptions import ObjectDoesNotExist from rest_framework.response import Response from rest_framework.decorators import api_view, authentication_classes, permission_classes from .models import Course, Lesson, Comment, Category from .serializers import CourseListSerializer, CourseDetailSerializer, LessonListSerializer, CommentsSerializer, CategorySerializer @api_view(['GET']) @authentication_classes([]) @permission_classes([]) def get_course(request, slug): course = Course.objects.get(slug=slug) course_serializer = CourseDetailSerializer(course) lesson_serializer = LessonListSerializer(course.lessons.all(), many=True) if request.user.is_authenticated: course_data = course_serializer.data else: course_data = {} data = { 'course': course_data, 'lessons': lesson_serializer.data } return Response(data) @api_view(['GET']) def get_comments(request, course_slug, lesson_slug): lesson = Lesson.objects.get(slug=lesson_slug) serializer = CommentsSerializer(lesson.comments.all(), many=True) return Response(serializer.data) @api_view(['POST']) def add_comment(request, course_slug, lesson_slug): data = request.data name = data.get('name') content = data.get('content') course = Course.objects.get(slug=course_slug) lesson = Lesson.objects.get(slug=lesson_slug) comment = Comment.objects.create(course=course, lesson=lesson, name=name, content=content, created_by=request.user) serializer = CommentsSerializer(comment) return Response(serializer.data) Because of this error it is also not dynamically updating the … -
How to modify values in m2m field in form? (Django)
I have 2 models in my models.py. They are Doctor and Specialty: class Doctor(models.Model): name = CharField(max_length=255) specialties = ManyToManyField('Specialty', related_name='doctors') mc_id = CharField(max_length=255, unique=True) class Specialty(models.Model): name = CharField(max_length=255) mc_id = CharField(max_length=255, unique=True) def __str__(self): return self.name When i'm creating new Doctor instance via admin interface (change_form.html template) I see my Doctor model fields, which I should fill with data. Among these fields there is a field specialties ("Cпециальности"), which is m2m field and conatins names (as I set __str__(self) method in Specialty model to return self.name) for specialties which were previously added to Specialty model (see a screen). A I want is to see in this list not only specialty names, but also values of mc_id field of Specialty model, but it is not my case to make it at the expense of something like this: class Specialty(models.Model): name = CharField(max_length=255) mc_id = CharField(max_length=255, unique=True) def __str__(self): return self.name + '(' + self.mc_id + ')' I thought i could make it through overriding of formfield_for_manytomany() method in my admin model (associated with Doctor model) in admin.py: @admin.register(Doctor) class DoctorAdmin(admin.ModelAdmin): def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "specialties": queryset = Specialty.objects.all() for specialty in queryset: specialty.name += '(' … -
How to write Django ORM query for .... WHERE substring(field1, 1, 2) in ('AB', 'BC')?
How to write Django ORM filter for following query. SELECT field1, field2, field3 FROM table1 WHERE substring(field1, 1, 2) in ('AB', 'BC') I want to write query using Model1.objects.filter(.....) I think sql query self explaining, I don't have to give more context. -
hx-get not fire after infinite scrolling
In each post I have this code : {% if result.has_url %} <div hx-get="{% url 'post:load-url-preview' result.pk %}" hx-trigger="revealed"> </div> {% endif %} In the first pagination, the htmx is firing but after infinite scrolling, it is not firing (I'm using Waypoints Infinite Scroll). I noticed that other jquery too is not working after page > 1. Any help would be appreciated -
django modal bootstrap Async with select list update
I am trying to implement a bootstrap modal on my django app that allows my user to create a new element that they can then pick in a select html list. I successfully implemented a way to generate a select list using selectize and querying for all the titles in my DB (function GetTitles). And I managed to create a new title through a modal using django bootstrap modal async (without re-direct - $("#title-modal").modalForm...) However, I now need to make sure that the new title created is added to the select list. Since the title is already in the db, i was thinking about calling the function GetTitles again upon submission of the modal. I tried to do so using the parameter addModalFormFunction: GetTitles but it's not really working...so I am definitely doing something wrong...right? <div id="title_div" style="margin-top: 20px;"> <label for="id_title" style="margin-bottom: 5px;" class="lead">Title</label><br/> <select class="" name="title" required="" id="id_title" multiple=""></select> </div> $(document).ready(function() { function GetTitles(){ $.ajax({ url: "{% url 'action:GetTitles' %}", type: 'GET', data: { csrfmiddlewaretoken: "{{ csrf_token }}", user:"{{ request.user.id }}", }, error: function(err) { console.log(err); }, success: function(options) { $('#id_title').selectize({ valueField: 'id', labelField: 'title_name', searchField: 'title_name', maxItems: 3, preload: true, options: options, create: true, plugins: ['remove_button'], create: function(input) … -
How to include related fields when serializing to geojson in django
I have two models. The first contains point data. The second is a ForeignKey back to the point model. How do I include fields from the second model when seralizing the first model? class Site(models.Model): ptgeom = models.PointField(srid=2953, blank=True, null=True) ... class File(models.Model): site = models.ForeignKey(Site, on_delete=models.PROTECT, blank=True, null=True) name = models.CharField(verbose_name='File', max_length=250, blank=True, null=True) ... In my view I build a queryset of the visible points and attempt to pass it back to the map: def file_points(request): ... q_set = Dmsesite.objects.filter(ptgeom__contained=geom) points_as_geojson = serialize('geojson', q_set, geometry_field='ptgeom') return JsonResponse(json.loads(points_as_geojson)) From this, I get a json of all the point records in q_set. I want this to include the File records as well. I have searched but am really lost. I have attempted .select_related(), but from the Site side the File model is not actually a related field. I attempted to follow this question: Specify fields of related model in Django GeoJSON serializer field and create the CustomSerializer, but I still didn't get any File records. Another possibility may be to somehow build a new queryset on the opposite side (File side) based on the current queryset (Site), but I'm not sure how I would go about this as I think … -
how to pass view method param to user passes test in django?
i have a view method such as @login_required(login_url='/users/login') def my_submission(request,submission_id): submission = Submission.objects.get(pk=submission_id) return render(request, "assignments/mysubmission.html", { "submission": submission }) I was wondering if there is a way to pass submission_id which is the second param to user passes test decorator so that i can do something like @user_passes_test(lambda u: u.id == Submission.objects.get(pk=submission_id).user.id, login_url='/') thanks for the guide in advance. -
Django chunked upload on apache
I am running a Django application on an Apache2 server, but each time I try to upload a file, I get a PermissionError: [Errno 13] Permission denied: '/chunked_uploads' error. I already gave permission to write into the chunk_uploads directory, but it did not work out either. Does some have an idea how to fix it? My config file: <VirtualHost *:80> Alias /static /home/usr/app/static <Directory /home/usr/app/static> Require all granted </Directory> <Directory /home/usr/app/backend> <Files wsgi.py> Require all granted </Files> </Directory> WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess app python-path=/home/usr/app python-home=/home/usr/app/appEnv WSGIProcessGroup app WSGIScriptAlias / /home/usr/app/backend/wsgi.py WSGIChunkedRequest On # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # … -
Django use urls with same ending
I ahve a django project with the application web-api and the following url configuration: main project urls.py urlpatterns = [ path('admin/', admin.site.urls), path('web-api/', include('webapi.urls')), ] application web-api/urls.py urlpatterns = [ path('<param1:param1>/summary', Param1Summary.as_view()), path('<param1:param1>/item/<int:id>/summary', ItemView.as_view()), ] The /web-api/param1/summary endpoint works but /web-api/param1/item/12121/summary does not work and returns a 404 status code. If I change the <param1:param1>/item/<int:id>/summary' to <param1:param1>/item/<int:id>/whatever, in the web-api/url.py I get the desired results. I have tried using url regex without succees. Any ideas on how to solve the problem? Thanks in advance! -
Import "rest_framework_swagger.views" could not be resolved
I wanted to implement swagger in Django rest framework, for that I install django-rest-swagger and register in setting.py but while importing in url.py it show error:- "Import "rest_framework_swagger.views" could not be resolved. How can I use rest_framework_swagger? -
Get the client_id and client_secret dinamically in django with the social_oauth2 authentication
I want to authenticate the users with Oauth but in the request to get the tokens I have to put the client_id and client_secret hardcoded, is there a better form to have dynamically these credentials, or just I have two credentials for all the users? Thank you! -
DJANGO VIews: how can I add another view already developed to a new one?
i am new with django with poor programming experience. I have written a view (agence view) in django which works fine. I would like to add this view to another one in the developing process. the new one includes agnecy view plus other attributes to write.. can someone help me please thanks in advance the existing view def nos_agences (request): """"display nos agences""" try: agence = Agence.objects.all() except Agence.DoesNotExist: raise Http404 return render(request, 'visitor/nos_agences.html', {'agences':agence}) path('nos_agences',views.nos_agences, name= 'nos_agences'), the new one which must include nos_agences def reservation (request): return render(request, 'visitor/reservation.html') -
How to change seed packages versions when creating virtualenv?
I am running into an issue when deploying a django-rest-framework API to production. The addition of seed packages pip, setuptools and wheel upon virtualenv's creation causes my deployment to fail. It appears that the specific version of setuptools (59.1.1) used here prevents usage from Newlines (related to this issue) which are used in the description of django-hijack==2.10.1 and causes the following error. This behaviour has been reverted in the newer versions of setuptools (from 59.4.0). Thus I would like to pin the version of setuptools added in seed packages upon virtualenv creation to make sure my deployment succeeds but I have no idea if/where I can set added packages versions. Any help is appreciated! Successfully created virtual environment! Virtualenv location: /var/www/backoffice/20211223111028/back/.venv Installing dependencies from Pipfile.lock (6e978f)... Ignoring appnope: markers 'sys_platform == "darwin"' don't match your environment To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. Running command 'cd /var/www/backoffice/20211223111028/back && pipenv install' on host 172.31.128.48 Creating a virtualenv for this project... Pipfile: /var/www/backoffice/20211223111028/back/Pipfile Using /home/ignition/.pyenv/versions/3.9.0/bin/python3.9 (3.9.0) to create virtualenv... ⠸ Creating virtual environment...created virtual environment CPython3.9.0.final.0-64 in 152ms creator CPython3Posix(dest=/var/www/backoffice/20211223111028/back/.venv, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, wheel=bundle, pip=bundle, setuptools=bundle, via=copy, app_data_dir=/home/ignition/.local/share/virtualenv) added … -
How to change dates when filtering a queryset in Django?
I want to display a list of all payments done by the company. But I want to be able to filter the dates, only showing payments for example: In the last 30 days In the last 90 days Between two specific dates Now, I know I can filter in my views between two dates, or before today for example. But how I can I do this using something like a dropdown or a Data chooser on the template? Something like this for reference. For reference, the payments model would be this: class Payment(models.Model): name = models.CharField(max_length=250) date = models.DateField(default=datetime.now) value = models.DecimalField(max_digits=10, decimal_places=2, validators=[MinValueValidator(0.00)]) -
Google Login Redirect Url Integrity Error
I have done proper configurations and google login is working correctly. When Google authenticates and redirect user to website it shows this error IntegrityError at /auth/social/google/ null value in column "appointments_enabled" violates not-null constraint DETAIL: Failing row contains (166, 2021-12-23 10:11:01.370877+00, 2021-12-23 10:11:01.370907+00, f, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 166, null, null, null, null, null). Request Method: POST Request URL: http://cozmo.gvmtechnologies.com:8000/auth/social/google/ Django Version: 2.0.9 Python Executable: /root/.local/share/virtualenvs/cozmo-FEPF8JuT/bin/python Python Version: 3.6.15 Python Path: ['/root/cozmo-server-develop/cozmo', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/root/.local/share/virtualenvs/cozmo-FEPF8JuT/lib/python3.6/site-packages', '/root/cozmo-server-develop/cozmo'] Server time: Thu, 23 Dec 2021 10:11:01 +0000 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.postgres', 'guardian', 'storages', 'rest_framework', 'rest_framework_swagger', 'rest_framework_tracking', 'rest_framework_jwt', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'rest_auth', 'rest_auth.registration', 'cozmo_common.apps.CozmoCommonConfig', 'accounts.apps.AccountsConfig', 'automation.apps.AutomationConfig', 'accounts.profile.apps.ProfileConfig', 'app_marketplace.apps.AppMarketplaceConfig', 'crm.apps.CrmConfig', 'listings.apps.ListingsConfig', 'events.apps.EventsConfig', 'listings.calendars.apps.CalendarsConfig', 'notifications.apps.NotificationsConfig', 'owners.apps.OwnersConfig', 'pois.apps.PoisConfig', 'payments.apps.PaymentsConfig', 'public_api.apps.PublicApiConfig', 'message_templates.apps.MessageTemplatesConfig', 'rental_connections.apps.RentalConnectionsConfig', 'rental_integrations.apps.RentalIntegrationsConfig', 'rental_integrations.airbnb.apps.AirbnbConfig', 'rental_integrations.booking.apps.BookingConfig', 'rental_integrations.expedia.apps.ExpediaConfig', 'rental_integrations.homeaway.apps.HomeawayConfig', 'rental_integrations.trip_advisor.apps.TripAdvisorConfig', 'send_mail.apps.SendMailConfig', 'search.apps.SearchConfig', 'vendors.apps.VendorsConfig', 'send_mail.phone.apps.PhoneConfig', 'services.apps.ServicesConfig', 'chat.apps.ChatConfig', 'settings.apps.SettingsConfig', 'rental_network.apps.RentalNetworkConfig', 'dashboard.apps.DashboardConfig', 'pricing.apps.PricingConfig', 'behave_django', 'corsheaders', 'internal.apps.InternalConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.messages.middleware.MessageMiddleware'] Exception Type: IntegrityError at /auth/social/google/ Exception Value: null value in column "appointments_enabled" violates not-null constraint DETAIL: Failing row contains (166, 2021-12-23 10:11:01.370877+00, 2021-12-23 10:11:01.370907+00, f, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, …