Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there A Way To Format Serialized Response for Groups and their Permissions in Django Rest Framework?
I created an API endpoint in which I am sending a JSON data. to create a group and then assigned permission to the models (e.g add_user, change_user etc) programmatically. It works fine. The issue now is that I will like to format data retrieved in the same format I sent it in This is for the Django's inbuilt Group, Permissions, ContentType View.py class RolePermissionListCreateAPIView(generics.ListCreateAPIView): queryset = Group.objects.all() serializer_class = RolePermissionSerializer permission_classes = (IsAuthenticated,) def list(self, request): if not request.user.has_perm("auth.view_group"): return Response({"error":"Permission denied."}, status=status.HTTP_401_UNAUTHORIZED) queryset = self.get_queryset() serializer = RolePermissionSerializer(queryset, many=True) return Response(serializer.data) Serializer.py class PermissionSerializer(serializers.ModelSerializer): codename = serializers.CharField(allow_blank=False) class Meta: model = Permission fields ="__all__" class RolePermissionSerializer(serializers.ModelSerializer): name = CharField(max_length=100) permissions = PermissionSerializer(many=True) class Meta: model = Group fields = ["id", "name", "permissions"] Data [ { "id": 1, "name": "Administrator", "permissions": [ { "codename": "add_user" }, { "codename": "change_user" }, { "codename": "deactivate_user" }, { "codename": "delete_user" }, { "codename": "export_user" }, { "codename": "import_user" }, { "codename": "print_user" }, { "codename": "view_user" } ] } ] This actually the way I want the data to be formatted: { "role_name": "Administrator", "modules": [ { "module_name": "User", "can_view": "True", "can_add": "True", "can_edit": "True", "can_delete": "True", "can_print": "True", "can_deactivate": "True", "can_import": "True", … -
Django: How passing parameters from (forms.py) to (views.py)
Please, how i can pass parameters from: forms.py " class InscriptionForm(forms.ModelForm): " to views.py " def inscription(request): " thank you very much in the views.py i put just from .forms import * -
Custom Admin Page with Fields as Objects
I have 3 models: Category, SubCategory, Product. Category and SubCategory have one-to-many relationship. SubCategory and Product have many-to-many relationship(ManyToManyField is in Product). Currently, admin page for Product shows one field for SubCategory as multiple choice field. But I want fields for Product to be as Category objects. SubCategories should be divided by their Categories and user should be able to choose a SubCategory from each of this field. Can't work it out. Thanks in advance! models.py: class Category(models.Model): name = models.CharField(max_length=150, unique=True) created_at = models.DateTimeField(default=timezone.now) modified_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=150, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='subcategories') created_at = models.DateTimeField(default=timezone.now) modified_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=150, blank=True) description = models.TextField(blank=True) price = models.IntegerField(default=-1) quantity = models.IntegerField(default=-1) image = models.ImageField(blank=True) created_at = models.DateTimeField(default=timezone.now) modified_at = models.DateTimeField(default=timezone.now) discount = models.ForeignKey(Discount, on_delete=models.PROTECT, blank=True) subcategory = models.ManyToManyField(SubCategory) class Meta: ordering = ('-created_at',) def __str__(self): return self.name -
Django take object by slug
Hello i am new here and new in django/programing i try to make some basic staff but dont like what i done. must be a better solution class EventPostCreateView(CreateView): model = EventPost form_class = EventPostForms def form_valid(self, form): self.object = form.save(commit=False) self.object.event = Event.objects.filter( slug=self.kwargs.get("slug")).first() self.object.post = self.object.pk self.object.save() return super().form_valid(form) def get_success_url(self): return reverse("event:event", kwargs={"slug": self.object.event.slug}) # Optimize my problem in from_valid func and i don't like this solution for filtering. how i can make this better and if someone explain me how did this in model not in View i will drink for his code till new year-_- class Event(models.Model): name = models.CharField(max_length=64, blank=False, null=False) place = models.CharField(max_length=64, blank=False, null=False) # from poligon/place tags = models.ManyToManyField("event.EventTags", related_name="Tags", blank=True) owner = models.OneToOneField("Org.Organizations", on_delete=models.CASCADE, related_name="owner") # must be created by founder start_date = models.DateField() end_date = models.DateField() body = models.TextField(blank=True, null=True) additional_block1 = models.TextField(blank=True, null=True) slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") # img = models.ImageField(upload_to='media') # Pillow required # rules = # make rules base on base rule + additional block by orgs # Date_creation = if TYPE_CHECKING: objects: models.Manager def __str__(self): return self.name def get_absolute_url(self): return reverse("event", kwargs={"slug": self.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Event, self).save(*args, **kwargs) … -
Django - Redirecting to a view with <select> <option>
I'm taking my first steps on django, and i'm stuck with this problem: I'm planning to use a selection box to choose a chapter of the book/novel and be redirected to it. Either using a "go" button or just redirecting instantly. Preferably the latter. But i don't really know how to make it work. Thanks in advance. url.py urlpatterns = [ path('<int:id>/<int:pk>', views.ChapterView.as_view(), name='chapter_view'), ] views.py class ChapterView(DetailView): model = Chapter context_object_name = 'chapter' template_name = 'chapter.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['chapter_group'] = Chapter.similar_chapter(self.get_object()) context['novel'] = Novel.objects.get(novel_title=self.get_object().chapter_novel) return context HTML <select class="form-select" aria-label="Default select example"> <option selected>{{ chapter.chapter_number }} - {{ chapter.chapter_title }}</option> {% for capitulos in chapter_group %} <option value="{% url 'chapter_view' novel.id capitulos.pk %}"> {{ capitulos.chapter_number }} - {{ capitulos.chapter_title }} </option> {% endfor %} </select> I tried using an <a href={% url 'chapter_view' novel.id capitulos.pk %}> inside the option, to no avail. Now i'm searching ways to do it, but haven't found nothing using .as_view() like i'm using. -
Cronjob not running on django with celery
I am trying to run a periodic task using celery and django from celery.schedule import crontab app.conf.beat_schedule = { 'compute-every-minute-mon-through-friday-9-to-5': { 'task': 'sum', 'schedule': crontab(minute='*/1', hour='9-17', day_of_week='mon,tue,wed,thu,fri'), }, } However, the task does not run at all. Is there a command to activate my cronjob? -
Django ORM querying data in JSONField
class GiftItem(models.Model): myjsonfield = models.JSONField(null=True) Data in myjsonfield is in these formats Record 1: { "name": "Birthday Present Box", "category": "Gifts", "choices": [ { "name": "Watch", "points": 31.89 }, { "name": "Perfume", "points": 19.07 }, { "name": "Bracelet", "style": "Gold 9k", "points": 43.5 } ] } Record 2: { "name": "Wedding Present Box", "category": "Anniversary", "choices": [ { "name": "Diamond Ringh", "points": 31.89 },{ "name": "Gold Chain", "points": 29.97 "reviews": [{"User": "John", "rating": 5}, {"User": "Joe", "rating": 8}] },{ "name": "Bracelet", "style": "Gold 18k", "points": 73.2 } ] } I can list all the records where first item is watch: GiftItem.objects.filter(myjsonfield__choices__0__name="Watch") OR show all records who have a watch GiftItem.objects.filter(myjsonfield__choices__contains=[{'name': 'Watch'}]) **Question 1: ** I want to list all records which have any of the choices.points > 50 or < or = to some int. Question 2: I have some more inconsistently nested data such as above record two has reviews key. Is there any way to list all records without having to specify full path? myjsonfield__has_key="reviews" doesn't work unless I provide full path myjsonfield__choices__has_keys="reviews" Please advise. -
Howto properly test a django library
I frequently run into practical problems when I want to test a library I develop that is a django app. Django apps can be developed independently, like DRF etc. For testing, you either need a django project, or at least a settings.py file or the like, see here. But I don't get it how to do that properly for a "standalone" library. I need to generate migrations for that library (if it contains models) - so I need a manage.py file to invoke manage.py makemigrations, I need to check if the lib is integrating in project properly (in my case apps are full-fledged plugins, I am using GDAPS). What is the best approach here? should I create a separate "test project" in a separate repo that uses my library and tests it? should I create a project within my library's tests directory and use that? CAVE python paths... should I not use the project at all and mimick everything - how? Please give me at least a hint in some direction. -
How to best use pyproject.toml files in Django project/app hierarchies?
I'm in the process of modernizing the conventions around Django applications at our company, but I've got a lot of catching up to do. One of the main question marks right now is pyproject.toml, which would be convenient (though not mandatory) for configuring the Black code formatter, as well as listing dependencies for pip-compile. Until now, we've used this monorepo structure for our client projects: . |_ .git |_ apps | |_ app_1 # created with 'django-admin startapp' | |_ app_2 # likewise | |_ setup.py | |_ project # created with 'django-admin startproject cool_site', then renamed | |_ manage.py | |_ cool_site | |_ __init__.py | |_ settings.py | |_ ...other files created by 'startproject'... | |_ support # various helper scripts etc., not a Python package In development, we've used Vagrants or docker-compose and bind mounted this repo into the VM or container for convenient development on the host machine, and run pip install -e apps to have the packages inside apps be importable by the manage.py runserver process. (On our production servers, we either deploy this contanerized, or just git pull this repo in place with Ansible, then install without -e, and use gunicorn instead of runserver) … -
502 Bad Gateway / gunicorn.socket: Failed with result 'service-start-limit-hit' | Django, Postgres, Nginx, Gunicorn ,Ubuntu 20.04
I went through a instruction - https://arctype.com/blog/install-django-ubuntu/ The result id 502 BadGateway ` root@1104941-ch54462:~/django_project# systemctl status gunicorn.socket ● gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: failed (Result: service-start-limit-hit) since Tue 2022-11-15 16:21:55 MSK; 5s ago Triggers: ● gunicorn.service Listen: /run/gunicorn.sock (Stream) Nov 15 16:21:37 1104941-ch54462.tmweb.ru systemd[1]: Listening on gunicorn socket. Nov 15 16:21:55 1104941-ch54462.tmweb.ru systemd[1]: gunicorn.socket: Failed with result 'service-start-limit-hit'. ` ` 2022/11/15 16:17:35 [error] 11517#11517: *2 connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: 195.224.49.226, server: 1104941-ch54462.tmweb.ru, request: "GET /admin HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/admin", host: "1104941-ch54462.tmweb.ru" 2022/11/15 16:20:54 [error] 11517#11517: *5 connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: 195.224.49.226, server: 1104941-ch54462.tmweb.ru, request: "GET /admin HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/admin", host: "1104941-ch54462.tmweb.ru" 2022/11/15 16:21:07 [alert] 11517#11517: *7 open socket #14 left in connection 4 2022/11/15 16:21:07 [alert] 11517#11517: aborting 2022/11/15 16:21:55 [error] 11599#11599: *2 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 195.224.49.226, server: 1104941-ch54462.tmweb.ru, request: "GET /admin HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/admin", host: "1104941-ch54462.tmweb.ru" ` What is the problem ? -
Django Logging: ValueError: Unable to configure handler 'gunicorn'
I configured logging for a new Django project, and here is the code for my settings.py: LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "warnfile": { "level": "WARNING", "class": "logging.FileHandler", "filename": BASE_DIR / "warning.log", "maxBytes": 1024 * 1024 * 25, # 100 mb }, "errorfile": { "level": "ERROR", "class": "logging.FileHandler", "filename": BASE_DIR / "error.log", "maxBytes": 1024 * 1024 * 25, # 100 mb }, "gunicorn": { "level": "DEBUG", "class": "logging.handlers.RotatingFileHandler", "formatter": "verbose", "filename": BASE_DIR / "gunicorn.log", "maxBytes": 1024 * 1024 * 25, # 100 mb }, }, "loggers": { "": { # keeping it empty for all kinds of loggers "handlers": [ "warnfile", "errorfile", ], "level": "WARNING", "propagate": True, }, "gunicorn.errors": { "level": "DEBUG", "handlers": ["gunicorn"], "propagate": True, }, }, } Let me explain: I want to put 2 kinds of logs: warnings, and errors, in 2 differents files. I also want a third file for gunicorn logs to monitor the server side. When I run the server, I get the following error: ValueError: Unable to configure handler 'gunicorn' I also created all the files just in case the logger does't create them for me, but still no changes. Here is my full traceback: Exception in thread django-main-thread: Traceback … -
Required path doesn't exist: /code/bower_components/trix/dist/trix.css trix. Nodejs wont build. How do add trix?
After using the comand "docker system prune -a" nodejs wont build anymore beacuse trix.css is missing. This was probably deleted which pruning. How can I resolve this error (see the screenshot below)? Screenshot of the Error -
Django: How to create an tabular inline like the one in admin panel with "+ Add another"?
I currently rely on the admin panel to create or edit a new/existing order (i.e. Order with its children model OrderItem in the tabular inline). But this time I need to create a view with the same function for non-admin users. More specifically, I need the + Add another button in the tabular inline for users to add more Order Items themselves when necessary. I have looked into a few stackoverflows (one of them) and books. So far they at most only mentioned about inlineformset_factory, but not how to create the + Add another. Any ideas please? Thank you! -
How can I create an book index with Python?
I have a section, and in this section, I have topics, for example, book chapters. But, on this section page, I only have the last three chapters, so, when I click, I can move forward to the single page where I am. This is my HTML template. <ul> {% for chapter in book %} <li> <a href="#{{ chapter }}">{{ chapter }}</a> </li> {% endfor %} </ul> But, how can I access a section in example/book?page=2#chapter_five? I tried to create a function to find the chapter in a for loop with all the pages, but I got that the object was not iterable. I tried it in my views. chapter = chapters.object_list chapters_pages = paginator.num_pages for page in chapters_pages: if page.contains(chapter): context["chapter_page"] = page So I could do it, but it not worked. <ul> {% for chapter in book %} <li> <a href="?page=chapter_page#{{ chapter }}">{{ chapter }}</a> </li> {% endfor %} </ul> -
I can't get any mail from Django send_mail? Where is my mistake?
I am trying to send a mail using Django send_mail() but I can't get any mail from Django send_mail? Where is my mistake? if request.method == "POST": depName = request.POST.get("sedep") Pname = request.POST.get("name") Pmail = request.POST.get("mail") docName = request.POST.get("sedoc") Pphone = request.POST.get("phone") AppointDate = request.POST.get("date") appointment_list = Appointment_List(se_dept = depName, se_doc = docName, patient_name = Pname, patient_phone = Pphone, patient_email = Pmail, calendar = AppointDate) appointment_list.save() # SEND EMAIL subject = 'Your appointment status!' message = 'hello '+ Pname + '! \n' + 'Welcome to Doctor appointment system.\n'+ 'Congratulations your appointment is booked.\n\n Thanking you Team malloc()' from_email = settings.EMAIL_HOST_USER to_list = [Pmail] send_mail(subject,message,from_email,to_list,fail_silently = True) EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'sa3518548@gmail.com' EMAIL_HOST_PASSWORD = 'uqnoifwqucnlefgp' EMAIL_PORT = 587 -
data in my table but it is not showing in django admin
I have data in my table but it is not showing in admin. I started by creating the model from django.db import models class VilleStation(models.Model): nomVille = models.CharField(max_length=255) adresse = models.CharField(max_length=255) cp = models.CharField(max_length=5) def __str__(self): return self.nomVille then in the admin.py I did this from django.contrib import admin from prixcarbu.models import VilleStation class VilleStationAdmin(admin.ModelAdmin): list_display = ('nomVille', 'adresse','cp',) fields = ('nomVille', 'adresse','cp',) admin.site.register(VilleStation, VilleStationAdmin) then I imported via db browser for sqlite a csv file. I see in my base the table correctly filled but in the admin I have nothing. thank for any help. -
HTML can't find JS script in the same folder [closed]
I'm using Django framework I have home.html: <head> </head> <body> <div> <button onclick="test()">Test button</button> </div> <script type="text/javascript" src="utils/htmlScript.js"></script> </body> And htmlScript.js: function test() { alert('hey there') } It cannot get simpler than this. Still, when I load the page I get this log: [15/Nov/2022 21:13:25] "GET /myapp/ HTTP/1.1" 200 147519 Not Found: /myapp/utils/htmlScript.js [15/Nov/2022 21:13:25] "GET /myapp/utils/htmlScript.js HTTP/1.1" 404 2349 My htmlScript.js file is in the folder /myapp/utils/htmlScript.js 100%. I have also tried to put it on the same folder as home.html and put src="htmlScript.js" but it doesn't work either. Can someone guide me on this? Thanks -
Images are disappearing from media folder(i think) after some time after uploading them, app deployed on digital ocean
I have an option for users to upload images from frontend which then gets uploaded in the media folder. But after sometime I notice that the images are disappearing and only the text that I get is remaining. Why is that happening? -
Using related_name instead of name.Class python Django(related_name=favorites)
My reviewer wants me to use related_name instead of referring to Class model! ` @admin.register(Recipe) class RecipeAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'author', 'favorites'] search_fields = ['name', 'author__username'] list_filter = ['tags'] empty_value_display = EMPTY inlines = ( IngredientsInLine, ) def favorites(self, obj): if Favorite.objects.filter(recipe=obj).exists(): return Favorite.objects.filter(recipe=obj).count() return 0 `` I did this: ` def favorites(self, obj): recipe = obj['recipe'] if obj.favorites(recipe=recipe).exists(): return obj.favorites(recipe=recipe).count() return 0 But I do not know if this is correct. -
Post data (dictionary list) with python requests
I'd like to post my dictionary list below via python's http requests. my_data=[ { 'kl':'ngt', 'schemas': [ { 'date':'14-12-2022', 'name':'kolo' } ], }, { 'kl':'mlk', 'schemas': [ { 'date':'23-10-2022', 'name':'maka' } ] } ] trying to do url='http://myapi.com/product x=requests.post(url,json=my_data) after execution it does not post the products on the database -
App not loading error while executing commands
` dam 2022-11-15 18:05:49,686 - adam - INFO - Welcome to ADAM, Finquest's Application for Data Annotation Management! Traceback (most recent call last): File "/home/finq/miniconda3/envs/adam/bin/adam", line 33, in <module> sys.exit(load_entry_point('adam', 'console_scripts', 'adam')()) File "/home/finq/miniconda3/envs/adam/bin/adam", line 25, in importlib_load_entry_point return next(matches).load() File "/home/finq/miniconda3/envs/adam/lib/python3.10/importlib/metadata/__init__.py", line 171, in load module = import_module(match.group('module')) File "/home/finq/miniconda3/envs/adam/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/finq/review/106_review/adam/adam/__main__.py", line 6, in <module> from adam.common.common import check_database_exists File "/home/finq/review/106_review/adam/adam/common/common.py", line 9, in <module> from adam.graphical_user_interface.db_graphical_user_interface.models import UserLogin File "/home/finq/review/106_review/adam/adam/graphical_user_interface/db_graphical_user_interface/models.py", line 5, in <module> class UserLogin(models.Model): File "/home/finq/miniconda3/envs/adam/lib/python3.10/site-packages/django/db/models/base.py", line 127, in __new__ app_config = apps.get_containing_app_config(module) File "/home/finq/miniconda3/envs/adam/lib/python3.10/site-packages/django/apps/registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "/home/finq/miniconda3/envs/adam/lib/python3.10/site-packages/django/apps/registry.py", line 138, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. ` I tried everything from path ,run migrtaions ,migrate but nothing helped . Please help to reoslve this . Thanks I tried everything from path ,run migrtaions ,migrate but nothing helped . Please help to reoslve this . Thanks … -
Django | Only show foreign keys not already assigned in django form
Im making a booking system in django where the user picks a date and then is able to see what times are available on that date. Models.py class Slot(models.Model): title = models.CharField(max_length=50) def __str__(self): return f'There is a slot at {self.title}' class Booking(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slot = models.ForeignKey(Slot, on_delete=models.CASCADE, null=True, blank=True, related_name='all_times') booking_date = models.CharField(max_length=15, default='foo') def __str__(self): return f'{self.user} has booked a session at {self.slot.title} on {self.booking_date}' Where the Slot model is they times that are available to pick(e.g. 9-10, 1-2 etc.) Views.py def DateView(request): form = DateForm(request.POST or None) if form.is_valid(): request.session["dateSelected"] = str( form.cleaned_data["booking_date"]) return redirect('../create/') context = { 'form': form } return render(request, "bookingapp/date_form.html", context) def BookingView(request): instance = Booking(booking_date=request.session.get('dateSelected')) form = BookingForm(request.POST or None, instance=instance) if form.is_valid(): form.save() form = BookingForm context = { 'form': form } return render(request, "bookingapp/book_form.html", context) Forms.py class DateInput(forms.DateInput): input_type = 'date' class DateForm(forms.ModelForm): class Meta: model = Booking fields = [ 'booking_date', ] widgets = {'booking_date': DateInput()} class BookingForm(forms.ModelForm): class Meta: model = Booking fields = [ 'user', 'slot', 'booking_date', ] widgets = {'booking_date': forms.HiddenInput()} The first form lets the user select a date, which then brings them to the second form where they can choose what … -
In Linux, how to run Django custom management using crontab?
I have generated a bash script that activates virtaulenv and runs my custom management command in Django. I want to run the bash script every day at midnight. Bash Script : cd ~ cd path_to_virtualenv/ source virtualenv_name/bin/activate cd path_to_project/ python manage.py custom_command deactivate When I run this script using . or source it runs perfectly. I have configured crontab to run this bash script (For testing, I have set execution time per minute). But I am not getting desired output. crontab -e */1 * * * * source /path_to_bash_script/bash_script_filename -
Is django's SCRIPT_NAME applied to STATIC_URL?
I'm serving django with gunicorn and nginx. And I've observed a strange behavior, which looks like django is prefixing MEDIA_URL with SCRIPT_NAME but it is not prefixing the STATIC_URL. Am I handling it properly? My static's configuration: STATIC_URL = "backend/static/" # this looks odd but works STATIC_ROOT = "/var/www/static" STATICFILES_DIRS = [BASE_DIR / "static"] MEDIA_URL = "media/" # this looks fine MEDIA_ROOT = "/var/www/media" gunicorn configuration: [Service] User=www-data Group=www-data Environment="DJANGO_SETTINGS_MODULE=backend.settings.production" WorkingDirectory=/var/www/backend ExecStart=/var/www/backend/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ backend.wsgi:application nginx configuration: location ^~ /backend { proxy_set_header SCRIPT_NAME /backend; include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; location ^~ /backend/static { alias /var/www/static/; } location ^~ /backend/media { alias /var/www/media/; } } -
Django 'DetailView' object has no attribute '_meta'
This has floored me. I'm building a model with Django & REST API, and I'm having trouble rendering the DetailView for individual cars to the browser. The ListView works fine, but I'll include the code too since they are interlinked. In particular, I can't get the get_object() function to work properly. The first approach I tried used this approach: views.py class CarDetailView(generics.RetrieveUpdateDestroyAPIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'car-detail.html' queryset = Car.objects.all() lookup_field = Car.id @action(detail=True, renderer_classes=[TemplateHTMLRenderer]) def get(self, request, *args, **kwargs): car = self.get_object() return Response({ 'car': car, }) While the page rendered properly with no errors, none of the template tags worked. Only {{ car.model }}, which returned None. So I changed the code to use a self.get_object() class CarDetailView(generics.GenericAPIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'car-detail.html' queryset = Car.objects.all() lookup_field = Car.id def get(self, request, id): serializer_class = CarSerializer car = self.get_object() id = Car.id return Response({ 'car': car, }) but that raises the Error: "AttributeError at /rentals/car/43c9b98d-9f2d-473f-9c34-7b2e25630278 'CarDetailView' object has no attribute '_meta'" Can you help with this? I've looked through most of the previous questions here (that's where I learned to pass the self into the get function etc...) but I'm still stuck. Here's the code: views.py …