Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, … -
ModuleNotFoundError: No module named 'django.utils'
Hi am getting these error ...do we know how to fix Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line File "/mnt/c/Users/krammurti/counselcareer/venv/lib/python3.8/site-packages/django/init.py", line 1, in from django.utils.version import get_version ModuleNotFoundError: No module named 'django.utils' -
How to display files by only its name
[![enter image description here][1]][1] [1]: https://i.stack.imgur.com/sjO7r.jpg Here i want to display only the file name i.e sample.pdf. I use postgresql as database ,django rest for backend and angular as frontend. If you want other code ask me i will share -
KeyError: 'password'
There's frontend on react and backend on Django, on registering user, got an issue with password field,like ** KeyError 'password'**, the code is below. serializer.py ... class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' ... views.py ... from.django.contrib.auth.hashers import make_password ... @api_view(['POST']) def userRegister(request): data = request.user user = User.objects.create( email = data['email'] password = make_password(data['password']) serializer = UserSerializer (user, many=False) return Response (serializer.data) ... -
User form foreignkeyfield form not valid
I was creating a post based website i want to show the author's name to show up in the post it works in the admin site when adding posts but when i try uploading a post from the site the form is not getting validated therefore it is not getting saved please help model : from django.conf import settings class MemeImg(models.Model): Title = models.CharField(max_length=500) op = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) Post_Img = CloudinaryField('Post') forms : class PostImg(forms.ModelForm): class Meta: model = MemeImg fields = ['Title', 'op', 'Post_Img'] view : @login_required(login_url='/login') def post(request): func = data(request) if request.method == 'POST': form = PostImg(request.POST, request.FILES, instance=request.user) form.op = request.user if form.is_valid(): print('success') posts = form.save(commit=False) posts.op = request.user form.save() return HttpResponseRedirect('https://youtu.be/dQw4w9WgXcQ') else: print("fail") form = PostImg(request) ctx = { 'form': form, 'url': func[0], 'name': func[1], 'date': func[2], } return render(request, 'Post.html', ctx) and finally the post page template : <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="container"> {{ form.Title|materializecss }} <div class="file-field input-field"> <div class="btn"> <span>File</span> <input type="file"> </div> <div class="file-path-wrapper"> {{ form.Post_Img }} <input class="file-path validate" type="text"> </div> </div> <button class="btn waves-effect waves-light" type="submit" name="action">Submit <i class="material-icons right">send</i> </button> </div> </form> If anymore code is required please … -
How to retrieve data from MySQL database in Django and display it in html page?
I am trying to add data from MySQL database and display it in a html page using python. Here is my view.py: def show(request): data = Persons.objects.all() person = { "Persons": data } return render(request, "home.html", person) models.py: class Persons(models.Model): PersonID = models.IntegerField() LastName = models.CharField(max_length=100) FirstName = models.CharField(max_length=100) Address = models.CharField(max_length=100) City = models.CharField(max_length=100) class Meta: db_table = "persons" html: <div> <div class="numbers">Graph</div> {% for item in Person %} {{ item.LastName }} {% endfor %} </div> But I didnot retrieve anything. Any help will be highly appreciated. -
Google Cloud App Engine (Django) and Google Cloud Storage working on a Single Domain with Custom URLs
I have a Django application working on supereye.co.uk. Django handles all URL routing such as supereye.co.uk/signin supereye.co.uk/watch etc. I am also using Google Cloud Storage that is working with Google Cloud App Engine on gs://production2.supereye.co.uk How shall I handle the routing so both App Engine and Storage can be accessible through the supereye.co.uk domain. For instance : supereye.co.uk -> Django App, Google Cloud App Engine data.supereye.co.uk -> Google Cloud Storage bucket, gs://production2.supereye.co.uk Is there any way to achieve this without relating Django App to bucket at all ? Can the bucket be accessible by its own resources? Is there any internal Google Cloud tool that will let me achieve this ? -
Best way to handle articles with Django
I'm looking for the best possible way to manage articles in Django. My idea was to load the articles as static files (there's no upload from users, so no form necessary, I guess), then create the model, but which field type to use here ? Textfield or FilePathField (in the static ?) or something else ? Then create the view and render it. The articles will be showned as cards with a summary on the index page, and each card will point to the full article page. If someone would point me in the right direction, I would appreciate. I'm checking the docs since yesterday, I might have missed the relevant part. -
Add custom admin actions to django irrelevant to objects
I want to add admin actions (for example with buttons) to django admin site that are irrelevant to particular model, for example doing administrative tasks such as optimizing database or clearing cache or log files or deleting records from multiple tables... I have seen django admin action without selecting objects, but the answers seems tricky and the solutions was selecting objects of particular model, in other ways. Is there a better to add this functionality to admin site anyway? -
How Django works with Mongodb
I need to make a Django restful api. I have a volume of data that is distributed in a tree structure with 3 attachments. I want to implement this nesting in Mongo: base->collection->object. The objects are generally the same so I don't really want to prescribe millions of models. I can draw an analogy with library: hall->stack->book. Each shelf has different books on it, but all of them are made of paper and covers. I found how to work with different databases and how to send the model to a certain database: 'default': { 'ENGINE': 'djongo', 'NAME': 'some_name', 'CLIENT': { { "host": "mongodb://.........../", } }, { "user": { 'ENGINE': 'djongo', 'NAME': 'some_name2', 'CLIENT': { { "host": "mongodb://......../", } } And accessing different databases Author.objects.using('other').all(). How to relate one model to one collection I found too: class MongoMeta: db_table = "some_collection_name" But how to combine all this I can't find. That one model can belong to different databases to different collections while being one single. -
Cannot connect to websocket by unicorn and uwsgi
I have tried the following 6 methods to start my django project. 1. command=python3 manage.py 2. command=daphne myproject.asgi:application -b 0.0.0.0 -p 778 3. command=uwsgi --ini /root/uwsgi.ini 4. command=uvicorn myproject.asgi:application --workers 4 --host 0.0.0.0 --port 778 5. command=gunicorn myproject.wsgi --workers 2 --bind 0.0.0.0:778 6. command=gunicorn myproject.asgi:application -k uvicorn.workers.UvicornWorker -b 0.0.0.0:778 However, only the first two methods are able to connect to websocket. Unfortunately, there is not two much error details left in my client(Only know the error code is 1006). Anyone knows why I cannot connect?