Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bootstrap Navbar seems to Crop Background Image
I'm dipping my toes into the world of web development with Django, and Stackoverflow has been really helpful (as always). However, I'm running across something the forums haven't seemed to address before... I have a background image that I've put in my static folder and called it in my homepage html template file (see code below). I've also incorporated bootstrap in my base.html file, which includes a navbar which directs to various apps on my website (again, see code below). homepage.html: {% extends "base.html" %} {% load static %} {% block page_content %} <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body, html { height: 100%; margin: 0; } .bg { /* The image used */ background-image: url({% static "mountains2.jpg" %}); /* Full height */ height: 100%; /* Center and scale the image nicely */ background-position: center; background-repeat: no-repeat; background-size: cover; } </style> </head> <body> <div class="bg"></div> </body> </html> {% endblock %} base.html <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container"> <a class="navbar-brand" href="{% url 'homepage' %}">Home</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="{% url 'about' %}">About</a> </li> <li class="nav-item"> <a … -
How do I access the value of a dictionary in my context in my Django template?
I'm using DJango and Python 3.7. I want to access the value of a dictionary that I add to my context website_stats = dict() .... context = { ... 'website_stats': website_stats, } return render(request, 'articlesum/trending.html', context) in my template. I tried like this {{ website_stats[articlestat.article.website][articlestat.elapsed_time_in_seconds] }} but I'm getting the error Could not parse the remainder: '[articlestat.article.website][articlestat.elapsed_time_in_seconds]' from 'website_stats[articlestat.article.website][articlestat.elapsed_time_in_seconds]' -
How to send object from detail view to another view in Django?
I have a detail view that uses a Quiz object to display data stored in that object, like title and author. I want to have a button that links to a new page that displays different data from the same object. I don't know how to pass this data/object. I can render the view and pass it the context of a specific quiz using an id but I want the id to change to be the id of the object from the initial page. #assessement view def assessment(request): context = { 'quiz':Quiz.objects.get(id=1), } return render(request, 'quiz_app/assessment.html', context) #detailview template for quiz {% extends "quiz_app/base.html" %} {% block content %} <article class="quiz-detail"> <h1>{{ object.title }}</h1> <h2>{{ object.question_amount }} Questions</h2> <a class="btn" href="{% url 'quiz-assessment' %}">Start Quiz</a> </article> {% endblock content %} #assessment template {% extends "quiz_app/base.html" %} {% block content %} <h2>Assessment</h2> <h2>Title is {{ quiz.title }}</h2> {% endblock content %} -
Unable to get Images from AWS-S3 bucket in django-app?
I'm using AWS-S3 to store my users' profile images. I've repeated this process 7-8 times but when I open my app on local machine(I've not deployed it yet) the user profile images aren't there and it shows the alt='not found' in place of images. I've made a user in IAM and a bucket in S3 same as in this tutorial nearly 5 times but there's no way I'm getting the images. Also when I right click on any image in my app and go into the image location I'm getting this in my browser. This XML file does not appear to have any style information associated with it. The document tree is shown below. AccessDeniedAccess Denied6683BC64F8FCAB0CE2foYctY9f7GMW+VI64vr3rRfMPrXXGfscryk3Eqo7meEtenXCLSa4kGYnQBJV6qDG9AdBVVgR8= Here's my settings.py file import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') MEDIA_DIR = os.path.join(BASE_DIR,'myblog/media') SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'blogapp.apps.BlogappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] ROOT_URLCONF = 'myblog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], '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', ], }, }, ] WSGI_APPLICATION = 'myblog.wsgi.application' DATABASES = { 'default': { … -
Problem Setting Up django-autocomplete-light v3
I am following the instructions provided here https://django-autocomplete-light.readthedocs.io/en/master/install.html I have installed dal by using the command "pip install django-autocomplete-light" - this completed successfully & I can see dal under my python site packages As soon as I follow the Configuration section & update my INSTALLED_APPS in settings with INSTALLED_APPS = [ 'dal' 'dal_select2', 'django.contrib.admin',..... I get a 500 - Internal server error. As soon as I remove 'dal','dal_select2' from my settings my server works OK again. My understanding of Django is that the INSTALLED_APPS section was referencing the various folders within my app but there is not folder for dal or dal_select2 which would cause the 500 - Internal server error. Is there another command I should be using to either move the dal folders into my application or to make my settings reference the Python27/Lib/site-packages/dal folder I am running Django 1.11.23 django-autocomplete-light 3.4.1 Many thanks for any pointers provided. -
I don't understand django's 404 display
I want to move to my 404 page when accessing a URL that is not set. We are trying to implement it in multiple applications. I tried a few, but I can't. Where is the best way to write code? #setting DEBUG = False ALLOWED_HOSTS = ['127.0.0.1'] #project url.py from django.conf import settings from django.urls import re_path from django.views.static import serve # ... the rest of your URLconf goes here ... if settings.DEBUG: urlpatterns += [ re_path(r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, }), ] handler404 = 'person.views.handler404' handler500 = 'person.views.handler500' #application view.py def handler404(request): response = render_to_response('404.html', {}, context_instance=RequestContext(request)) response.status_code = 404 return response def handler500(request): response = render_to_response('500.html', {}, context_instance=RequestContext(request)) response.status_code = 500 return response -
How to create a date field once item is created?
Iam trying to have a date next to the item once the item is created. I did add datetimefield in the model and added the template in my home.html but somehow Once the item is created 'POST' nothing happens or appears. class List(models.Model): item = models.CharField(max_length=20) completed = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.item class Meta: ordering = ['created_at'] def home(request): if request.method == 'POST': form = ListForm(request.POST or None) if form.is_valid(): form.save() all_items = List.objects.all messages.success (request, 'item has been added to the list') return render(request, "home.html", {'all_items': all_items}) else: all_items = List.objects.all return render(request, "home.html", {'all_items': all_items}) the output is nothing. date doesnt appear even tho the item is successfully added. -
How can I override delete model action in Django
I override delete_model method on my admin model, but it doesn't calling. Please some one help me. Django admin: override delete method class ManageAdmin(ImportExportActionModelAdmin): actions = ['delete_model'] def delete_model(self, request, obj): logger.info('delete model method called!'); log is none. -
Ran _git rm --cached *.pyc and now No module named 'django'
I kept getting merge conflicts when trying to git pull from github to my production server and a lot of them had to do with the .pyc files. So on my local machine, I ran _git rm --cached *.pyc git add . git commit git push -u origin dev Since I had *.pyc in my .gitignore but hadn't committed properly. Anyways, when I go to git pull on my production server, everything is pulled fine no merge conflicts. But then I kept getting server errors on my site when trying to access the admin panel and this is the error File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in <module> ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Obviously I have a virtual env working and this must be because the __pycache__ files were removed with the latest commit. Can anyone help me? I'm not sure what to do. -
How to make a many to many links without altering the record object
I feel like I am missing something basic here but I can't figure it out. I will give a simplified example of what I am trying to achieve. Take this typical restaurant example for instance. If I have pizza table that is populated with records of pizza names. Another table is records pizza-toppings. They have a many to many relationship. If a customer orders the "2 Topping" with "Pepperoni" and "Mushrooms", then in the backend, some script would get the "2 Topping" pizza object and get the two topping objects and then link/add/relate them. So that pizza.toppings.all() would return a QuerySet of the two topping. If a different customer at shortly after orders the exact same pizza. The previously added toppings will already be linked to that pizza object. Obviously it's not practical to clear relationships after every order has been made. ##Model class Pizza(models.Model): name = models.CharField(max_length=30) toppings = models.ManyToManyField('Topping', related_name='pizzas')) def __str__(self): return self.name class Topping(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Order(models.Model): pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE) ## Logic cheese_pizza = Pizza.objects.create(name='Cheese') mozzarella = Topping.objects.create(name='mozzarella') mozzarella.pizzas.add(cheese_pizza) mozzarella.pizzas.all() -> <QuerySet [<Pizza: Cheese>]> How can I add pizza objects, with toppings linked, to an Orders table without affecting … -
Django Error: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module
I'm new to Python and Django, And I'm trying to run a Django app which uses MySQL as a database, I installed mysqlclient using pip, which it shows as Requirement already satisfied: mysqlclient in ./env/lib/python3.7/site-packages (1.4.4) But when I run the project or try to create a superuser,it throws me the following error - Aniruddhas-MacBook-Pro:python_django aniruddhanarendraraje$ ls djangocrashcourse-master env projectNameHere Aniruddhas-MacBook-Pro:python_django aniruddhanarendraraje$ source env/bin/activate (env) Aniruddhas-MacBook-Pro:python_django aniruddhanarendraraje$ pip install mysqlclient Requirement already satisfied: mysqlclient in ./env/lib/python3.7/site-packages (1.4.4) (env) Aniruddhas-MacBook-Pro:python_django aniruddhanarendraraje$ cd djangocrashcourse-master/ (env) Aniruddhas-MacBook-Pro:djangocrashcourse-master aniruddhanarendraraje$ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib Referenced from: /Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/utils/autoreload.py", … -
How to create fixture where I can add session?
I have my API and here I developed login and logout view. Now I want to write pytests and I have a problem, idk how to create fixture where I can make my user authorized and set some id in session(this is required for the logout). I create new_user via fixture(to avoid working with my db). views @csrf_exempt def login(request): if request.method == "POST": data = json.loads(request.body.decode('utf-8')) if not is_data_valid_for_login(data): return HttpResponseBadRequest() user = authenticate(email=data["email"], password=data["password"]) if user: auth_login(request, user) response = HttpResponse(status=200, content_type='application/json') request.session['id'] = user.id return response return HttpResponseBadRequest() return HttpResponseBadRequest() @csrf_exempt def logout(request): if request.method == "GET": auth_logout(request) response = HttpResponse(status=200) if 'id' in request.session: del request.session['id'] return response return HttpResponseBadRequest pytest import pytest from user.models import User PASSWORD = "testPassword" @pytest.fixture() def user(): return User.create(first_name="Name", last_name="Last", email="test@test.com", password=PASSWORD) -
Django : AttributeError: 'Manager' object has no attribute 'all_with_related_persons'
I am fairly new to django and currently working on a movie database project. However, i have a problem with the models which always comes up with the error. File "C:\Users\public\django\mymdb\django\core\views.py", line 17, in MovieDe queryset = (Movie.objects.all_with_related_persons()) AttributeError: 'Manager' object has no attribute 'all_with_related_persons' Here is the model for the core app from django.db import models from django.conf import settings # Create your models here. class PersonManager(models.Manager): def all_with_prefetch_movies(self): qs = self.get_queryset() return qs.prefetch_related( 'directed', 'writing_credits', 'role_set__movie') class Person(models.Model): first_name = models.CharField( max_length=140) last_name = models.CharField( max_length=140) born = models.DateField() died = models.DateField(null=True, blank=True) objects = PersonManager() class Meta: ordering = ( 'last_name', 'first_name') def __str__(self): if self.died: return '{}, {} ({}-{})'.format( self.last_name, self.first_name, self.born, self.died) return '{}, {} ({})'.format( self.last_name, self.first_name, self.born) class MovieManager(models.Manager): def all_with_related_persons(self): qs = self.get_queryset() qs = qs.select_related( 'director') qs = qs.prefetch_related( 'writers', 'actors') return qs class Movie(models.Model): NOT_RATED = 0 RATED_G = 1 RATED_PG = 2 RATED_R = 3 RATINGS = ( (NOT_RATED, 'NR - Not Rated'), (RATED_G, 'G - General Audiences'), (RATED_PG, 'PG - Parental Guidance ' 'Suggested'), (RATED_R, 'R - Restricted'), ) title = models.CharField( max_length=140) plot = models.TextField() year = models.PositiveIntegerField() rating = models.IntegerField( choices=RATINGS, default=NOT_RATED) runtime = \ models.PositiveIntegerField() … -
Django TypeError at //profile/: 'NoneType' object is not subscriptable
Whenever I create a user or superuser in django administration or in powershell and try to log in and click view profile it will give me an error saying 'NoneType' object is not subscriptable, but when I create a user or superuser in frontend side and try that to log in and click view profile it doesn't give me an error. Profile models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete =models.CASCADE,null=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics') update = models.DateTimeField(default = timezone.now) forms.py class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ['username','email','gender','mobile_number','first_name','middle_name','last_name'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields =['image'] views.py def profile(request): profile = Profile.objects.get_or_create(user=request.user) events = Event.objects.all().order_by('-date_posted') if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form':u_form, 'events':events, 'p_form':p_form, } return render(request,'users/profile.html',context) Registration views.py def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') form.save() messages.success(request, f'{ username } added successfully ') return redirect('announcement') else: form = RegistrationForm() return render(request, 'user_registration.html' ,{'form': form}) forms.py class RegistrationForm(UserCreationForm): email = forms.EmailField(required=False) class Meta: model = User fields = ['username','first_name','middle_name','last_name','gender','mobile_number','email','password1','password2'] … -
Getting a json from a string in Django TemplateView to make a request to django-rest API
I started from this question but was not able to solve this: I have a Django templateview with an information I want to pass to a django-rest API via HTML form. API POST request accepted: a JSON file with a string value [ {"filename" : "01-01-01-01-01-01-01.wav"} ] What I build: Views.py class SelectPredFileView(TemplateView): """ This view is used to select a file from the list of files in the server. After the selection, it will send the file to the server. The server will return the predictions. """ template_name = "select_file_predictions.html" success_url = '/predict_success/' def get_context_data(self, **kwargs): """ This function is used to render the list of file in the MEDIA_ROOT in the html template. """ context = super().get_context_data(**kwargs) media_path = settings.MEDIA_ROOT myfiles = [f for f in listdir(media_path) if isfile(join(media_path, f))] context['filename'] = myfiles return context def send_filename(self, request): filename_json = json.dumps(self.context) return render(request, "template.html", context={'filename': filename_json}) class Predict(views.APIView): def __init__(self, **kwargs): super().__init__(**kwargs) modelname = 'Emotion_Voice_Detection_Model.h5' global graph graph = tf.get_default_graph() self.loaded_model = keras.models.load_model(os.path.join(settings.MODEL_ROOT, modelname)) self.predictions = [] def post(self, request): """ This method is used to making predictions on audio files previously loaded with FileView.post """ with graph.as_default(): for entry in request.data: filename = entry.pop("filename") filepath = str(os.path.join(settings.MEDIA_ROOT, … -
How I can host .sql file on clever cloud platform on postgresql addons?
I have a database in the PostgreSQL database system. I want to host this database on clever-cloud platform. I have created a PostgreSQL instance on clever-cloud. -
Heroku stuck at Building Source for Django app
I have successfully pushed the previous versions of my Django app to Heroku. It usually shows some errors if it is not able to deploy, but this time it is stuck at this for about an hour: Counting objects: 10977, done. Delta compression using up to 8 threads. Compressing objects: 100% (7719/7719), done. Writing objects: 100% (10977/10977), 17.29 MiB | 3.00 MiB/s, done. Total 10977 (delta 3954), reused 6832 (delta 2062) remote: Compressing source files... done. remote: Building source: Here's the GitHub link to the app that I am trying to deploy: https://github.com/surajsjain/smart-aquaponics-backend Please Help -
Unable to run django on docker
I'm setting up a django server application on docker. docker runs the container well but the command to run django is not taking by docker. I've already gone through few youtube videos but none of them worked for me Dockerfile FROM python:3.6-stretch MAINTAINER *** ENV PYTHONBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /specfolder WORKDIR /specfolder COPY ./myfolder /specfolder EXPOSE 8000 CMD ["python", "manage.py runserver"] i've tried placing the command under docker-compose.yml file under commands: sh -c "python manager.py runserver" but none of them worked docker-compose.yml file version: "3" services: myapp: build: context: . ports: - "8000:8000" volumes: - ./myfolder:/specfolder requriements.txt django==2.2.4 pandas xlrd xlsxwriter as of now under kinematics i am getting the python shell Type "help", "copyright", "credits" or "license" for more information. >>> 2019-08-31T13:34:51.844192800Z Python 3.6.9 (default, Aug 14 2019, 13:02:21) [GCC 6.3.0 20170516] on linux unable to access the 127.0.0.1:8000/myapp/login in the browser. -
How to display text/image/gif as wait while the view method is rendering?
The Django App is taking some time to load. how can any test/image is displayed while page load time? -
Put in django admin form two TinyMCE side by side
If I try to put side side by side two tinyMCE fields in django admin form the second one on the right will be rendered ugly. I'd like to have something more proportionate, with the right ratio. I already tried to change the width inside tinyMCE profile. but what happened is that I had more white space instead reducing area of widget Here an example of what I did from tinymce.models import HTMLField from django.contrib import admin from django.db import models # THIS IS THE MODEL class A(models.Model): description = HTMLField( entity="entity", help_text="Description (HTML)", null=True, blank=True, ) description2 = HTMLField( entity="entity", help_text="Description 2 (HTML)", null=True, blank=True, ) # THIS IS THE ADMIN @admin.register(A) class AAdmin(admin.ModelAdmin): list_display = ('id', ) fieldsets = ( ( 'Properties', { 'fields': ( ('description', 'description2'), ), }, ), ) This is the result https://i.imgur.com/tOuVHLo.png -
Why Django can't find image on this path?
So. This is my first Django project. I am using Django Admin template to add/edit/delete content. I added option to add image to specific section. Here is the model class Project(models.Model): title = models.CharField(max_length = 100) description = models.TextField() technology = models.CharField(max_length = 20) image = models.ImageField(upload_to = "projects/images/") And it works. It creates images directory inside project directory which can be found in root directory. When I load image in template I load it with <img src="/{{project.image.url}}" alt="" class="card-img-top"> Then in HTML it creates element <img src="/projects/images/106780.jpg" alt="" class="card-img-top"> But inn console it says that it can't find image on http://127.0.0.1:8000/projects/images/106780.jpg My directory has this hierarchy portfolio | |__ blog |__ projects |__ __pycache__ |__ images |__ migrations |__ templates |__ ... |__ venv |__ db.sqlite3 |__ manage.py -
What is the CBV equivalent of passing params via kwargs and query strings in a FBV?
If I want to pass a number of variables via a URL path to a view so that I can use it to look up more than one object I have a couple of different ways to do this: 1. Passing as a key word argument in the URL path I can pass a parameter via the url path as a kwarg in both FBV and CBV: // Function based view: path('task/detail/<int:pk>/<int:abc>/', views.task_detail, name='task_detail')` // Class based view: path(`task/detail/<int:pk>/<int:abc>/`, views.TaskDetailView.as_view() Which is passed in the URL as mysite.com/task/detail/1/2/. In a FBV I can access both kwags to get separate objects via request: // Function based view: def task_detail(request, pk, abc) first_object = get_object_or_404(SecondObjectModel, id=pk) second_object = get_object_or_404(SecondObjectModel, id=abc) 2. Passing as a query string in the URL path Alternatively I can pass the parameter via a query string, which is parsed and parameters are stored as a QueryDict in request.GET, for example mysite.com/task/detail/?pk=1&&abc=2. I can then access these via both FBV and CBV as: // Function based view: def task_detail(request): first_object_id = request.GET.get('pk') second_object_id = request.GET.get('abc') first_object = get_object_or_404(SecondObjectModel, id=pk) second_object = get_object_or_404(SecondObjectModel, id=abc) What is the classed base view equivalent of each of these approaches? Why and when should … -
Retrieving results by running a query based on condition in Django
So i have following 2 tables which i am using to write a Book library in Django. class Book(models.Model): """Model representing a book (but not a specific copy of a book).""" title = models.CharField(max_length=200) author = models.CharField(max_length=200,null=True) summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book",null=True) genre = models.ManyToManyField(Genre, help_text="Select a genre for this book") shelflocation = models.CharField(max_length=10, null=True) pages = models.IntegerField(null=True) copies = models.IntegerField(null=True,default=1) and another BookInstance model where i am maintaining both the status and number of copies class BookInstance(models.Model): """Model representing a specific copy of a book (i.e. that can be borrowed from the library).""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular book across whole library") book = models.ForeignKey('Book',on_delete=models.SET_NULL,null=True) due_back = models.DateField(null=True, blank=True) borrower = models.ForeignKey('MemberList',on_delete=models.SET_NULL,null=True) LOAN_STATUS = ( ('d', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), ) So if a book is loaned then status will be set to 'o' in above table. I would like to display all the Books of a specific author whose books has been loaned and copies are still available. I tried adding queryset to list but it failed. Is there a way to query based on the condition in the following query if(book_instance_count < book.copies or … -
django ModelMultipleChoiceField generate multiple option from an instance
i have been given a project that has a ModelForm like this: class AddUserToPrivateCourseForm(forms.ModelForm): class Meta: model = Course fields = [ 'users', ] and users is a Foreignkey relation to user table .it works as expected it generates a select option html <select> <option value="pk1">Name</option> <option value="pk2">Name</option> </select> that are then in the template converted by select2 to dynamic search field , which the options are users to be selected By Name for the relevant course now i have to add users phone Numbers as a search property in the field. so i thought of something like the widget generates something like this <select> <option value="pk1">Name</option> <option value="pk1">Phone Number</option> <option value="pk2">Name</option> <option value="pk2">Phone Number</option> </select> is this possible or i have to come up with something completely different to solve this? -
How display form in HTML intergration DRF and django-filters
Hi I have problem with intergration DRF and django-filters. How to display filters form in my HTML like in DRF API views. I was trying use @action decorator but that no works me. Someone have a idea how solve this problem ? class AlbionViewsSets(viewsets.ModelViewSet): queryset = Albion_data.objects.all() serializer_class = Albion_data_Serializer filterset_class = Itemfilters lookup_field = "item"