Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django is not rendering my static file (css, images, etc)
I am able to view my site (html)in the browser but none of my mark-up is working. I have checked my stylesheet links for types, settings.py, but I am at a lost. When I run my site I am getting the below responses in my terminal. `[10/Nov/2022 20:46:23] "GET / HTTP/1.1" 200 168 [10/Nov/2022 20:46:23] "GET /static/css/main.css HTTP/1.1" 404 1795 [10/Nov/2022 20:46:23] "GET /static/images/6%2Bcart.png HTTP/1.1" 404 1810` I have tried going over everything possible but cannot locate the issue, any and all feedback would be greatly appreciated. I am not allowed to post images yet so unfortunately, I could not include. I have re-coded, deleted and remade static folder, scoured the internet with no luck yet. -
JWT token authentication in Github Social Authentication
I am working with django github social authentication using dj_rest_auth. I am trying to add JWT token authentication in it. I am trying to get access_token and refresh_token. To get it i want to enter username and password in api view.In social authentication login there is no password. we have Only username and mail id. Is it possible to access token by using only username? If Yes. How is it possible? -
Restrict users to see detailview based on model field value in Django
I am learning and have a change management project where my model contains field confidential which is by default False, however during instance creation so called initiator could tick it as True. This basically means that only users which are part of current record so called signees could open and see the instance. I am trying to apply get_queryset override on my DetailView: # MOC DetailView class MocDetailView(LoginRequiredMixin, DetailView): model = Moc template_name = 'moc/moc_detail.html' def get_queryset(self, *args, **kwargs): qs = super().get_queryset(*args, **kwargs) for obj in qs: print(obj) confidential = obj.confidential initiator = obj.initiator coordinators = obj.coordinators.all() reviewers = obj.reviewers.all() approvers = obj.approvers.all() preimplements = obj.preimplements.all() authorizers = obj.authorizers.all() postimplements = obj.postimplements.all() closers = obj.closers.all() if initiator and initiator == self.request.user and confidential == True: qs = qs.filter(Q(confidential=True) & Q(initiator=self.request.user)) return qs for signee in coordinators: coordinator_name = signee.coordinator_name if coordinator_name and coordinator_name == self.request.user and confidential == True: qs = qs.filter(Q(confidential=True) & Q(coordinators__coordinator_name=self.request.user)) return qs for signee in reviewers: reviewer_name = signee.reviewer_name if reviewer_name and reviewer_name == self.request.user and confidential == True: qs = qs.filter(Q(confidential=True) & Q(reviewers__reviewer_name=self.request.user)) return qs for signee in approvers: approver_name = signee.approver_name if approver_name and approver_name == self.request.user and confidential == True: qs = qs.filter(Q(confidential=True) … -
Django Model Serializer manyToMany relationship
I have problem with Django 4.1.2 (Python 3.8.9). I have 2 entities: Idea and IdeaTheme, which have manyToMany relationship. class Idea(models.Model): short_name = models.CharField(max_length=70) description = models.TextField(null=True, blank=True, default='') class State(models.IntegerChoices): CREATED = 0, _("Создано") TEAM_SEARCHING = 1, _("Поиск команды") IN_PROCESS = 2, _("Реализация") READY = 3, _("Готово") state = models.IntegerField(choices=State.choices, default=State.CREATED) wanted_skills = models.ManyToManyField(to=UserSkill) themes = models.ManyToManyField(to=IdeaTheme, null=True, blank=True) class IdeaTheme(models.Model): name = models.CharField(max_length=70, verbose_name="Название") background_photo = models.ImageField(blank=True, null=True, verbose_name="Изображение для фронта") Also I have ModelSerializer class IdeaSerializer(serializers.ModelSerializer): class Meta: model = Idea fields = '__all__' depth = 1 extra_kwargs = { 'state': { 'read_only': True }, 'pk': { 'read_only': True } } And when I using CreateAPIView in order to create Idea I face the problem, that I must provide IdeaTheme pks. But in the model there are Null and Blank option and I want to create idea without IdeaThemes. I tried to specify IdeaTheme serializer inside IdeaSerializer like this, but Django still require not empty array of IdeaTheme. themes = IdeaThemeSerializer(many=True, required=False) Could someone help me, please, who already has experience using built-in serializers? -
Uploading Image from angular to Django using Rest Api Angular 13 / Django 4.1 Rest Framework
I'm trying to upload an image from Angular to Django using Rest framework, When I try uploading i got the following error : UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 177: invalid start byte So i tryied most of all the answers but no success. Angular v13 Django v4.1 This is My class Model that I'm trying to fetch : ` class Product(models.Model): famille = models.ForeignKey(Famille, on_delete=models.CASCADE) tva = models.ForeignKey(Tva, on_delete=models.CASCADE) poidsUnity = models.ForeignKey(Poids, on_delete=models.CASCADE, null=True) tailleUnity = models.ForeignKey(Taille, on_delete=models.CASCADE, null=True) couleur = models.ForeignKey(Color, on_delete=models.CASCADE, null=True) marque = models.ForeignKey(Marque, on_delete=models.CASCADE, null=True) poids = models.FloatField(null=True) taille = models.FloatField(null=True) photo = models.ImageField(upload_to='pics', null=True, blank=True) ``` ` This is My Serializer Class : class ProductSerializer(serializers.ModelSerializer): photo = Base64ImageField( max_length=None, use_url=True, allow_empty_file=True, allow_null=True, ) class Meta: model = Product fields = '__all__' ``` ``` ``` ` This is My Views : @csrf_exempt def productCrud(request, id=0): if request.method == 'GET': if id != 0: products = Product.objects.filter(id=id).first() products = ProductSerializer(products) else: products = Product.objects.all() products = ProductSerializer(products, many=True) return JsonResponse(products.data, safe=False) elif request.method == 'POST': product = JSONParser().parse(request) product = ProductSerializer(data=product) if product.is_valid(): product.save() return JsonResponse(product.data, safe=False) return JsonResponse(product.errors, safe=False)` ` urls.py : ` urlpatterns = [ # full path /product/ [get, post, … -
Django - Form that lists the fields for every foreign key
I have this 2 models: class AccountsPlan (models.Model): code = models.CharField(max_length=7, unique=True) name = models.CharField(max_length=100, unique=True) active = models.BooleanField(default=True) class Planning (models.Model): accountplan = models.ForeignKey(AccountsPlan, on_delete=models.PROTECT, limit_choices_to={'active': True}) month = models.DateField() amount = models.DecimalField(max_digits=14, decimal_places=2) This form: class PlanningForm(forms.ModelForm): accountplan = ModelChoiceField(queryset=AccountsPlan.objects.filter(active=True).order_by('code')) month = forms.DateField(required=True) amount = forms.DecimalField(max_digits=14, decimal_places=2, required=True, localize=True) class Meta: model = Planning fields = '__all__' And this view: def new_planning(request): if request.method == 'POST': form = PlanningForm(request.POST) if form.is_valid(): form.save() else: form = PlanningForm() return render(request, 'app/pages/planning/new_planning.html', context={ 'form': form, }) The form works as intended, but right now, I have more than a 100 entries in the AccountsPlan model and this number will increase overtime. The user needs to fill the PlanningForm every month for every foreign key in the AccountsPlan model, so filling one by one is not ideal. Since the month field will be the same for every foreign key and only the amount field is different, what I'm trying to do is this: The form lists every foreign key with an amount field for each one and a single month field. The user selects de date and enter just the amount and that saves the data. I tried this answer and managed … -
Unable to load css while running django in docker
If I access http://0.0.0.0:8000/admin/ The console says the following and the css does not load. The Cross-Origin-Opener-Policy header has been ignored, because the URL's origin was untrustworthy. It was defined either in the final response or a redirect. Please deliver the response using the HTTPS protocol. You can also use the 'localhost' origin instead. See https://www.w3.org/TR/powerful-features/#potentially-trustworthy-origin and https://html.spec.whatwg.org/#the-cross-origin-opener-policy-header. My settings is as follows: ALLOWED_HOSTS = ['0.0.0.0', '127.0.0.1', 'localhost'] DISABLE_COLLECTSTATIC = 0 # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "books.apps.BooksConfig", "debug_toolbar", "corsheaders", "django.contrib.postgres", "django_celery_beat", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "corsheaders.middleware.CorsMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "debug_toolbar.middleware.DebugToolbarMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", ] ROOT_URLCONF = "search.urls" LOGIN_REDIRECT_URL = "home" LOGOUT_REDIRECT_URL = "home" CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:8000', 'https://localhost:8000', 'http://0.0.0.0:8000', 'https://0.0.0.0:8000', 'http://127.0.0.1:8000', 'https://127.0.0.1:8000' ) TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [BASE_DIR / "templates"], "APP_DIRS": True, "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", ], }, }, ] STATIC_URL = "/static/" -
Get Data Problem with Foreignkey Models QuerySet (Django)
I am making django practising. I found a repo and edited to myself. When i came to the get data from models with foreignkey, i get query instead of data. I think my function is a little bit spagetti or my template file. Full repo is here https://github.com/eseymenler/demo2 Here is the output of my codes. First red square is query, but i want second red square datas. Hasta Adı: {{ patient.name }} Hastanın Sağlık Problemi: {{ prob }} Hastanın Boyu: {{ vital }} Hastanın Sigara Kullanım Durumu: {{ social }} First data {{ patient.name }} is very good for me. Thats what i want. But when i get write {{ prob.problem }} it gives me nothing. So where is my fault. But also when i make for loop like this, i get data which i want. So how can i fix this. {% for y in prob %} {{ y.problem }} {% endfor %} And my views.py @login_required() def patienttumbilgiListView(request, id): patient = Patient.objects.get(aadhaarId = id) prob = ProblemList.objects.filter(patient = patient) vital = VitalSign.objects.filter(patient = patient) social = SocialHistory.objects.filter(patient = patient) return render( request, 'patient_records/patient-problem-tum.html', context={'prob': prob, 'vital': vital, 'social': social, 'patient': patient }) and my template file {% extends … -
(MacOS) Django can't find the MySQL driver ... but, why?
Here's the traceback: Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/mike/.virtualenvs/djangoprod/lib/python3.10/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/mike/.virtualenvs/djangoprod/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so, 0x0002): Library not loaded: '@rpath/libmysqlclient.21.dylib' Referenced from: '/Users/mike/.virtualenvs/djangoprod/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so' Reason: tried: '/usr/lib/libmysqlclient.21.dylib' (no such file) And here's the problem: $ locate libmysqlclient [...] /usr/local/mysql-8.0.31-macos12-x86_64/lib/libmysqlclient.21.dylib So, the library is there, but Django isn't finding it. So, before I "bang my head uselessly against this thing," especially given that it used to work, will someone out there kindly give me a nudge in the right direction? What am I missing here? I particularly notice that the package is trying the path, /usr/lib... when that is not in fact the proper location here. In particular: I see in the text a reference to @rpath which I am sure is the root cause of the problem – obviously, the value is wrong. (I notice that it does have the library-name right.) I'm frankly not familiar with this @rpath thing, nor exactly what sets it. Thank you kindly in advance ... -
Django Channels Freezes when calling internal Django-Filters API
I am using django-nextjs which required me to install Django Channels. Now this works fine until my frontend makes an API call to a DRF APIView which in turn makes an API call to Django-Filters to return a queryset. This freezes the entire server until the connection times out. Do you have an idea how this could be fixed? My asgi.py import os from django.core.asgi import get_asgi_application from django.urls import re_path, path os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.production') django_asgi_app = get_asgi_application() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django_nextjs.proxy import NextJSProxyHttpConsumer, NextJSProxyWebsocketConsumer from django.conf import settings http_routes = [re_path(r"", django_asgi_app)] websocket_routers = [] if settings.DEBUG: http_routes.insert(0, re_path(r"^(?:_next|__next|next).*", NextJSProxyHttpConsumer.as_asgi())) websocket_routers.insert(0, path("_next/webpack-hmr", NextJSProxyWebsocketConsumer.as_asgi())) application = ProtocolTypeRouter( { # Django's ASGI application to handle traditional HTTP and websocket requests. "http": URLRouter(http_routes), "websocket": AuthMiddlewareStack(URLRouter(websocket_routers)), # ... } ) And here is my APIView with the internal API call to Django Filters class SearchAPI(APIView): permission_classes = [] def get(self, request, *args, **kwargs): received_params = {} ... full_request = f"{settings.BASE_URL}api/filter-recipes/?{col_to_search}__icontains={search_term}{additional_filters}" print('full_request: ', full_request) response = httpx.get(full_request) print('response: ', response) response = response.json() response = response["results"] if "results" in response else response ... return Response(json.dumps(final_response)) Everything freezes upon calling the get: 'response = httpx.get(full_request)', is there anyway I … -
Filter the logged in Users groups in before saving Django
Hi upon registering a new user all the groups are listed for the user to select from the drop down. I am trying to filter this to only the groups that the logged in user is part of. views.py from .forms import UserRegisterForm @login_required(login_url='login') def addUser(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save() group = form.cleaned_data['group'] group.user_set.add(user) return redirect('login') else: form = UserRegisterForm() return render(request, 'base/adduser.html', {'form':form}) forms.py from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): group = forms.ModelChoiceField(queryset=Group.objects.all(), required=True) class Meta: model = User fields = ['username', 'password1', 'password2', 'group'] adduser.html > {% extends 'main.html' %} > > {% block content %} <style> > .home-container{ display:grid; grid-template-columns: 1fr 4fr; > > } </style> <div class="home-container"> > > > > <div> > > </div> > <div> > {% include 'settingmenu.html' %} > > </div> > <div></div> > <div> > <form method="POST" action=""> > {% csrf_token %} > > {{form.as_p}} > > <input type="submit" value="Add User" /> > </form> > > > > </div> </div> {% endblock %} -
Why django admin is not reading the __str__ method?
I'm trying to add a str method in my models.py file to my administrative page show me the objects I've register with their own name and not like a 'UserObject(1)' But when I add this method that's what is happening: AttributeError at /admin/crud_app/user/ 'User' object has no attribute 'first_name' models.py -> from django.db import models class User(models.Model): """ A normal class that represents an User object, the attributes are those bellow: """ first_name = models.CharField(name="First Name", max_length=30) last_name = models.CharField(name="Last Name", max_length=30) cpf = models.CharField(name="CPF", max_length=30) age = models.IntegerField(name="Age") email = models.EmailField(name="email", max_length=30) def __str__(self): return self.first_name admin.py -> from django.contrib import admin from .models import User admin.site.register(User) I try to add the str method and I'm was expecting to recive the name that I give to my object registered instead of 'Name object(1)' -
How can I create an index with django that takes into account multiple columns and most importantly a 5 second interval
I want to create an interval for a table that says "each entry will be unique based on it's col a, col b, col c, and a 5 second interval" For example I want to be able to do something like this: class Meta: indexes = [ models.Index(fields=['col_a',]), models.Index(fields=['col_b',]), models.Index(fields=['col_c',]), models.Index(expression='five second interval') ] Is this possible? If so what's the right way to do something like this? -
Why setUpTestData has an argument and setUp doesn't?
Pretty much the title. In django, when creating tests, we have two options, setUp and setUpTestData. I understand that setUp will be called each time a single test runs, while setUpTestData will be called only once and be used in multiple tests. I don't understand what the cls does in setUpTestData(cls), though. And why setUp() doesn' t have that argument? -
django custom admin login page
I have a custom auth mechanism for users and I want to use the same for django admin. All works fine for authenticated users but if an unauthenticated user opens the url /admin he is redirected to /admin/login with the std. login page for admin. I want to redirect to auth/sign-in or block the page. urlpatterns = [ path('admin/', admin.site.urls), path('admin/login', SignInView.as_view(), name='admin/login'), ... Redefining the url like in the code block does not work. Any idea? -
Django Form is not submitting (No POST action on HTML form)
I have created a Django Form but it does not submit after hitting the submit Button. It seems like the HTML is broke because if i hit the submit button Django doesn´t output a POST Action. Template is as follows: <form method="POST"> {% csrf_token %} <div class="relative transform overflow-hidden rounded-lg bg-gray-800 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg"> <div class="bg-gray-50 dark:bg-gray-800 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"> <div class="sm:flex sm:items-start"> <div class="mt-3 text-center text-gray-200 sm:mt-0 sm:ml-4 sm:text-left"> {{ addForm.email }} {{ addForm.givingLessons }} </div> </div> </div> </div> <input type="submit" class="inline-flex w-full justify-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-base font-medium text-white shadow-sm focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 sm:ml-3 sm:w-auto sm:text-sm" value="Update" /> </form> views.py def manage_students(request): if request.method == "POST": form = addStudentGivingLessons(request.POST) if form.is_valid(): lessons = form.cleaned_data.get('givingLessons') print(lessons) return redirect('home') else: print("form is not Valid") else: Forms.py class addStudentGivingLessons(forms.Form): email = forms.EmailField() givingLessons = forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple, queryset = Faecher.objects.all()) -
Django GROUP BY without aggregate
I would like to write the following query in Postgresql using Django ORM: SELECT t.id, t.field1 FROM mytable t JOIN ... JOIN ... WHERE .... GROUP BY id Note that there is NO aggregate function (like SUM, COUNT etc.) in the SELECT part. By the way, it's a perfectly legal SQL to GROUP BY primary key only in Postgresql. How do I write it in Django ORM? I saw workarounds like adding .annotate(dummy=Count('*')) to the queryset (but it slows down the execution) or introducing a dummy custom aggregate function (but it's a dirty hack). How to do it in a clean way? -
is_valid() don't work with my form in Django
i'm a beginner with Django 4.1. I'm using model to edit a form and render it in a webpage. This run correctly. When i click on submit, my function recognize the POST method but never validate the form. I'm sure that i have to fix a bug in my models or my form but i don't know where. in models.py class Auction(models.Model): HOUSE = "HOU" MOTORS = "MOT" PROPERTY = "PPT" HOBBIES = "HOB" INFORMATION_TECHNOLOGY = "IT" MUSIC = "MUS" BOOK = "BOK" CATEGORY_CHOICES = [ (HOUSE, "All for your House"), (MOTORS, "Car, Moto, Boat"), (PROPERTY, "Houses, flats, manors"), (HOBBIES, "Hobbies"), (INFORMATION_TECHNOLOGY, "Laptop, Desktop, Mobile Phone"), (MUSIC, "CD, Musical Intrusments"), (BOOK, "Books, Comics,...") ] ONE = 1 THREE = 3 SEVEN = 7 FOURTEEN = 14 DURATION_CHOICES = [ (ONE, "1 day"), (THREE, "3 days"), (SEVEN, "7 days"), (FOURTEEN, "14 days") ] title = models.CharField(max_length=64) description = models.TextField(max_length=500, blank=True) creation_date = models.DateTimeField(auto_now_add=True) image = models.URLField(null=True, blank=True, default="") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="seller") duration = models.CharField(max_length=7, choices=DURATION_CHOICES, default=SEVEN) category = models.CharField(max_length=3, choices=CATEGORY_CHOICES, default=INFORMATION_TECHNOLOGY) price = models.DecimalField(max_digits=12, decimal_places=2, default=0.0) def __str__(self): return f"{self.id}: {self.title}" in forms.py class CreateListingsForm(forms.ModelForm): class Meta: model = Auction fields = ["title", "description", "image", "category", "duration", "price"] and … -
How to automatically and regularly update database for a web application?
I am new to web development and I have a fundamental question on developing a website that takes queries from the users and searching inside a database. I am developing a website that takes queries from users and searches in an existing database. I already developed the web app part with Django. The app takes some keywords, searches the database, and displays the returned data in a table form. The database is made out of several csv files that are irregularly updated, say every one or two weeks. They are located in some local storage, say /home/james/csv_files/. To develop the website, I first processed the csv files in my local machine and made them into db.sqlite3 file, the default(?) database that comes with Django. I uploaded these to GitLab, including the db.sqlite3, and deployed to see if it works, and it worked file. But current implementation always searches in the uploaded db.sqlite3. I am looking for an automatic way that regularly process the csv files in /home/james/csv_files/ to update the database and let the web app to use the updated database. Where should I start? Currently, there is a python script that reads /home/james/csv_files/*.csv and merge them into /home/steven/project/db.sqlite3. Application … -
Password reset confirmation link redirects to page not found 404
DJOSER = { 'LOGIN_FILED': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION':True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION':True, 'SEND_CONFIRMATION_EMAIL':True, 'PASSWORD_RESET_CONFIRM_RETYPE':True, 'SET_USERNAME_RETYPE': True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'email/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL':True, 'SERIALIZERS':{ 'user_create': 'app1.serializers.UserCreateSerializer', 'user': 'app1.serializers.UserCreateSerializer', 'user_delete': 'djoser.serializers.UserDeleteSerializer', } } Here it works fine: You're receiving this email because you requested a password reset for your user account at localhost:8000. Please go to the following page and choose a new password: http://localhost:8000/password/reset/confirm/MTI/bep1bq-486f1f58d396e13f7bdf862a12ba0a18 Your username, in case you've forgotten: m**********0@gmail.com The localhost:8000 team I want to: when I click to this link, it should navigate to the page that I customized to set a new password, but It redirects to page not found Page not found (404) Request Method: GET Request URL: http://localhost:8000/password/reset/confirm/MTI/bep1bq-486f1f58d396e13f7bdf862a12ba0a18 Please anyone knows how to solve this issue))? -
How to get the date by day name in python?
I have a day name such as Monday. and the current day is Wednesday. Now i want to get the date of next coming Monday. How can i do it with a best practice in a very short way. Right now i have done this with bunch of if conditions. and that thing made the code messy. and it only work when the day name is same as current day name. here is my code : day_time = timezone.now() current_day = day_time.strftime("%A") coming_day = "monday" if coming_day == current_day: day_to_set = day_time + timedelta(days=7) -
How to add a hyperlink to a list of objects in Django Rest Framework?
I have this code: class EntrySerializer(serializers.HyperlinkedModelSerializer): comments = serializers.HyperlinkedRelatedField(many=True, view_name='comment-detail', read_only=True) owner = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Entry fields = ['url', 'owner', 'title','comments'] which produces this: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ ... { "url": "http://127.0.0.1:7000/api/posts/34476dbd-89fc-420b-8d9e-28f2feb7c193/", "title": "A Title For This Entry", "comments": [ "http://127.0.0.1:7000/api/comments/dd1a0f06-c096-494f-a70e-5507f99082e6/" ] }, ... ] What I want to achieve is: the "comments" field to a hyperlink that leads to a Comment List. I tried using: comments = serializers.HyperlinkedRelatedField(many=True, view_name='comment-detail', hoping to get something like this: "comments": "http://127.0.0.1:7000/api/comments/" but that produces the following error: ImproperlyConfigured at /api/posts/ Could not resolve URL for hyperlinked relationship using view name "comment-list". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Request Method: GET Request URL: http://127.0.0.1:7000/api/posts/ Django Version: 4.1.3 Exception Type: ImproperlyConfigured Exception Value: Could not resolve URL for hyperlinked relationship using view name "comment-list". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Exception Location: /Users/banana/.virtualenvs/mvp/lib/python3.10/site-packages/rest_framework/relations.py, line 416, in to_representation Raised during: api.viewsets.EntryViewSet Python Executable: /Users/banana/.virtualenvs/mvp/bin/python Python Version: 3.10.2 Python Path: ['/Users/banana/Library/Mobile ' 'Documents/com~apple~CloudDocs/repos_x/projects/Duck_take/Backend/django/dev/entries_comments_requirements', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python310.zip', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10', … -
Using multiple backend frameworks with one database in a virtual machine
I'm wondering if I could use multiple backend frameworks, using only 1 database in a VM instance in production without any problems. For example, I wanna keep Django Admin and its authentication rest API services, while using FastAPI for other things, possibly even ExpressJs in the future. I want to achieve this because different frameworks have different strengths and available third-party libraries in their ecosystems. I know NGINX as a reverse proxy and a load balancer will control the traffic load and directions to different endpoints. Still, would there be any conflicts in the database or anything I should be watching out for? Thank you! -
How to add custom view to custom AdminSite in Django
im a beginner with Django and basically want to add a section in Django Admin where if I click on it, I have a view that can process data. For example: I have models Campaign and Components which I can access through Django Admin and now I also want an Option "Analytics" that work the same way as if it was a model. Maybe this image will make clear what I want: When I click on "Analytics" I want to call a view that can fill a html template with data that I calculate from my models e.g. build a table that counts my instances of Campaigns and Components. What I've done so far: create a custom AdminSite to overwrite the default AdminSite. Problem: I do not see my option appearing. #admin.py class MyAdminSite(admin.AdminSite): def get_urls(self): urls = super(MyAdminSite, self).get_urls() custom_urls = [ path(r'myapi/test/', self.admin_view(testview)), ] return urls + custom_urls site_header = "My custom site" admin_site = MyAdminSite(name="myadmin") #apps.py class MyAdminConfig(AdminConfig): default_site = "myapi.admin.MyAdminSite" #settings.py INSTALLED_APPS = [ 'rest_framework', #'django.contrib.admin', "myapi.apps.MyAdminConfig", #views.py @api_view(["GET", "POST"]) def testview(request): print("testmyview") return render(1, "mytest.html") #urls.py urlpatterns = [ path('admin/', admin_site.urls), path('api/', include('myapi.urls')), ] I tried to follow this tutorial: https://adriennedomingus.medium.com/adding-custom-views-or-templates-to-django-admin-740640cc6d42 but I think after … -
Create a GENERATED ALWAYS AS IDENTITY identifier field in a PostgreSQL 14+ database table using Django 4.1.x
I would like Django 4.1.x (I'm using 4.1.3 at the time of writing) to create a PostgreSQL (v14+) table for which the identifier, id, has to be created as if I were creating the table with this SQL snippet for the id field: id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY. This would normally ends up on a schema like this in PG 15: $ pg_dump --table table --schema-only -d postgres -- multiple SET statements here (...) CREATE TABLE public.table ( id bigint NOT NULL, name character varying(1024) NOT NULL ); ALTER TABLE public.table OWNER TO postgres; ALTER TABLE public.table ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY ( SEQUENCE NAME public.table_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1 ); ALTER TABLE ONLY public.table ADD CONSTRAINT table_pkey PRIMARY KEY (id); Here's my current model in Django: class Foo(models.Model): name = models.CharField( max_length=256, verbose_name=_("Name"), null=False, ) def __str__(self): return f"{self.name}" It actually creates this table (makemigrations/migrate) with the following ALTER statement instead: ALTER TABLE public.table ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( SEQUENCE NAME public.table_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1 ); How can I achieve that, …