Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch: Reverse for 'about' not found. 'about' is not a valid view function or pattern name
I am building blog in django and stuck bcz of this error. When I click on Readmore button to load full blog post. this error appears. it should load the page which diplay blog post with detail it showed this error to me. Kindly help me i tried different solution which are available on internet but didn't get rid of this error. Here is my code! project url.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('Blog_App.urls')), ] app urls from django.urls import path from . import views urlpatterns = [ path('', views.PostList.as_view(), name= 'home'), path('user/<str:username>/', views.UserPostList.as_view(), name= 'user-posts'), path('<slug:slug>', views.PostDetail.as_view(), name= 'post_detail'), path('register/', views.Register, name= 'Registration'), path('login/', views.Login, name= 'Login'), path('logout/', views.logout_view, name= 'Logout'), ] views.py from django.db import models from .forms import NewUserForm from django.shortcuts import get_object_or_404, redirect, render from django.http import HttpResponse from django.contrib.auth import login,logout, authenticate from django.contrib import messages from django.contrib.auth.forms import AuthenticationForm from django.views import generic from .models import STATUS, Post from django.contrib.auth.models import User class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'Blog_App/index.html' class UserPostList(generic.ListView): model = Post template_name = 'Blog_App/user_posts.html' context_object_name = 'posts' def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-created_on') class PostDetail(generic.DetailView): model = Post … -
does implementing a csrf token fix an idor exploit?
as ive understood you need a csrf in each post request. So is it possible to do an idor exploit if you have a csrftoken? and if it is how do you fix an idor exploit? -
"Got KeyError when attempting to get a value for field devUserId on serializer AssetSerializer. Original exception text was: 'devUserId'
models.py class User(models.Model): googleId = models.CharField(max_length=512, primary_key=True, default='') imageURL = models.CharField(max_length=512, null=True) userName = models.CharField(max_length=512, null=True) firstName = models.CharField(max_length=512, null=True) lastName = models.CharField(max_length=512, null=True) #phoneNumberRegex = RegexValidator(regex=r"^+?1?\d{8,15}$") phoneNumber = models.CharField(max_length=512, null=True) email1 = models.CharField(max_length=512, blank=False) email2 = models.CharField(max_length=512, blank=True) bio = models.TextField(blank=True) planId = models.ForeignKey('primal_user.Plans', on_delete=models.CASCADE, default="Free") password = models.CharField(max_length=512, null=True) accountCreationDate = models.DateTimeField(auto_now_add=True) coins = models.IntegerField(default=2) assetsDownloaded = models.IntegerField(default=0) assetsPurchased = models.IntegerField(default=0) class Asset(models.Model): assetId = models.CharField(max_length=20, primary_key=True) devUserId = models.ForeignKey(User, on_delete=models.CASCADE) keywordId = models.ForeignKey(Tags, on_delete=models.CASCADE) assetName = models.CharField(max_length=50, null=False) description = models.TextField(blank=True) features = models.TextField(blank=True) uploadedDate = models.DateField(auto_now_add=True) typeId = models.BooleanField(default=True) paidStatus = models.BooleanField(default=False) price = models.IntegerField(null=True) size = models.FloatField(null=False) downloadCount = models.BigIntegerField(null=True) version = models.CharField(max_length=10) serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = 'all' class AssetSerializer(serializers.ModelSerializer): class Meta: model = Asset fields = 'all' views.py class UserAsset(APIView): def get(self,request,devUserId): try: user = Asset.objects.filter(devUserId=devUserId).values() serializer = AssetSerializer(user, many= True) return Response(serializer.data) except Asset.DoesNotExist: raise Http404 KeyError I am a beginner in Django, so am unable to figure out what the issue is. I tried looking for solutions to similar questions but could not resolve the issue. I was getting attribute error, then it was resolved after I entered many=True in AssetSerializer but now I am stuck … -
How can access programmatically to Django related_name QuerySet of objects
I have this models and relations class Address(models.Model): .. content_type = models.ForeignKey(ContentType, verbose_name=_('Content Type'), on_delete=models.CASCADE) object_id = models.PositiveIntegerField(verbose_name=_('Object ID')) content_object = GenericForeignKey() class SocialNetwork(models.Model): .. content_type = models.ForeignKey(ContentType, verbose_name=_('Content Type'), on_delete=models.CASCADE) object_id = models.PositiveIntegerField(verbose_name=_('Object ID')) content_object = GenericForeignKey() class Company(models.Model): addresses = GenericRelation('Address') social_networks = GenericRelation('SocialNetwork') I would like to access the relation programmatically through attribute name or attribute related name. Something like this element = Company.objects.get(id=1) element.addresses.clear() element.social_networks.add(*queryset) element.attribute_name.all() ... Anybody could help me please ? -
operator does not exist: character varying = integer
I am building a BlogApp and I was working on a feature and I am stuck on a error. operator does not exist: character varying = integer LINE 1: ...d" = "taggit_tag"."id") WHERE "taggit_tag"."name" IN (SELECT... I am trying to retrieve all the comments commented by user from Tags which were used in comment's post. When I access the comments then it is keep showing that error when i access the variable in template. models.py class Post(models.Model): post_user = models.ForeignKey(User, on_delete=models.CASCADE) post_title = models.CharField(max_length=30) tags = models.TaggableManager() class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_of = models.ForeignKey(Post, on_delete=models.CASCADE) views.py class page(request): tagQuery = Tag.objects.filter(post__comment__user=request.user) #this is showing error subquery = Comment.objects.filter(post_of__tags__name__in=tagQuery) context = {'subquery':subquery} return render(request, 'page.html', context) It was showing The QuerySet value for an exact lookup must be limited to one result using slicing. So i used __in but then it keep showing that error. Any help would be much Appreciated. Thank You -
How can Ajax work with a dynamic Django dropdown list? does not select every subcategory in the selected category
does not select every subcategory in the selected category. I will show you examples from my codes my models are as follows: class Category(TranslatableModel): translation = TranslatedFields( name=models.CharField(max_length=255, blank=True, null=True, verbose_name=_('Name')) ) slug = models.SlugField(max_length=255, unique=True, blank=True, null=True) class Subcategory(TranslatableModel): translation = TranslatedFields( name=models.CharField(max_length=255, blank=True, null=True, verbose_name=_('Name')) ) category = models.ForeignKey(Category, on_delete=models.CASCADE) slug = models.SlugField(max_length=255, unique=True, blank=True, null=True) class Announcement(TranslatableModel): translations = TranslatedFields( title=models.CharField(max_length=255, verbose_name=_('Sarlavha')), description=models.TextField(verbose_name=_('Tavsif'))) slug = models.SlugField(max_length=255, unique=True) created_at = models.DateTimeField(auto_now_add=True, ) image = models.ImageField(upload_to='elonimages') category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True) subcategory = models.ForeignKey(Subcategory, on_delete=models.CASCADE, null=True, blank=True) is_public = models.BooleanField(default=False) full_name = models.CharField(max_length=50) address = models.CharField(max_length=250) phone = models.CharField(max_length=12) cost = models.CharField(max_length=9, blank=True, null=True) My views.py file is as follows: class AnnouncementCreateView(CreateView): model = Announcement form_class = AnnouncementForm template_name = "announcement/add.html" success_url = reverse_lazy('announcement_list') def load_category(request): category_id = request.GET.get('category') subcategory = Subcategory.objects.filter(category_id=category_id).order_by('name') return render(request, "announcement/category_dropdown.html", {'subcategory': subcategory}) My forms.py file is as follows: class AnnouncementForm(TranslatableModelForm): class Meta: model = Announcement fields = ('title', 'description', 'image', 'category', 'subcategory', 'cost', 'full_name', 'address', 'phone',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['subcategory'].queryset = Subcategory.objects.none() if 'category' in self.data: try: category_id = int(self.data.get('category')) self.fields['category'].queryset = Subcategory.objects.filter(category_id=category_id).order_by('name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['subcategory'].queryset = self.instance.subcategory_set.order_by('name') My index.html file is as follows and the … -
Update the div element by clicking the button
I just recently started learning Django and web programming. I need to update the information in my div when the button is clicked. How can this be done? Is it possible to do this only with Django? -
Django Rest Framework: Convert serialized data to list of values
I'm using a DRF ModelSerializer to serve a one-field queryset, but the response returns as a list of dicts [{"state": "AL"}, {"state": "AR"}, {"state": "AZ"}] Is there any way to return a pure string list, like ["AL", "AR", "AZ"] ? I've explored other questions, but haven't found anything useful. -
How do I omit .virtualenv packages when testing Django project with Coverage.py
I have a Django project which I want to test with Coverage.py. I want to exclude the files in .virtualenvs. I am using pipenv and the editor is VS Code. Coverage version is 5.5 I followed the documentation instructions to create a .coveragec file in the root directory of the project. I then ran the test but Coverage does not omit the packages in .virtualenvs. .coveragec [run] source = . omit = *.virtualenvs/*,*tests*,*apps.py*,*manage.py*,*__init__.py*,*migrations*,*asgi*,*wsgi*,*admin.py*,*urls.py* [report] omit = *.virtualenvs/*,*tests*,*apps.py*,*manage.py*,*__init__.py*,*migrations*,*asgi*,*wsgi*,*admin.py*,*urls.py* When this approach did not work, I then resorted to using the Command line approach. This did not also work. cmd commands coverage run --omit=*./virtualenvs/*,*tests*,*apps.py*,*manage.py*,*__init__.py*,*migrations*,*asgi*,*wsgi*,*admin.py*,*urls.py* manage.py test -v 2 coverage html --omit=*./virtualenvs/*,*tests*,*apps.py*,*manage.py*,*__init__.py*,*migrations*,*asgi*,*wsgi*,*admin.py*,*urls.py* I have also used .venv instead of .virtualenvs but it still does not work. What can I do? -
Django models.Model & DJANGO_SETTINGS_MODULE throwing error on "import" command
Getting a django.core.exception error when trying to invoke the API using from newapp.models import NewApp. I have added the newapp App to the INSTALLED_APPS section of the settings.py file. There are several sources such as this one: Error with setting DJANGO_SETTINGS_MODULE variable while running debug in PyCharm However, it does not lead to a resolution. I've tried set DJANGO_SETTINGS_MODULE but that doesn't help here. I have tried export DJANGO_SETTINGS_MODULE I have tried using python settings: After trying the os.environ approach, i get a new error 'Apps aren't loaded yet' There error suggests to call settings.configure() but I can't find any sources online about how to do this. Seems if I don't use models.Model then I don't get the error? What on earth am I doing wrong? This is such a basic task. It seems like others have struggled with this but there is no clear answer out there. -
Raw query results multiplies many times when I use INNER JOIN in Django
I can't figure it out why my raw query multiplies the result as many time as the number of users. I'm using INNER JOIN and I bonded two objects so I really can't get it. (I'm not experienced in Django Query Language so I'm using raw query). views.py def index(request): projekt = Projekt.objects.raw('SELECT projekt_id, stressz_projekt.projekt, last_name, first_name, stressz_profile.id, stressz_profile.user_id, auth_user.id FROM stressz_profile INNER JOIN stressz_projekt ON stressz_projekt.id = stressz_profile.projekt_id INNER JOIN auth_user ON auth_user.id = stressz_profile.user_id') template = loader.get_template('stressz/index.html') context = { 'projekt': projekt, } return HttpResponse(template.render(context, request)) -
How to use PUT operation without ID in url with django
I was trying to implement a PUT method without an ID although this does not comply with REST principle. However I was just wondering if this can be done in anyway because I can easily get User instance from self.request.user. So, if I make the view class ProfileViewSet(mixins.ListModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): serializer_class = UserProfileSerializer permission_classes = [IsAuthenticated] queryset = User.objects.all() lookup_field = 'username' def get_object(self): try: return User.objects.get(pk=self.request.user.id) except User.DoesNotExist: raise NotFound() def update(self, request, *args, **kwargs): ............??? Unfortunately, I could not reach the update function as it always throw an exception saying "PUT method is not allowed". Thanks in advance. -
Sort ForeignKey field on Wagtail Page
I'm trying to sort a ForeignKey field on Page content type, which references another Page. class MyPage(Page): ... partner = models.ForeignKey( 'education.PartnerPage', on_delete=models.CASCADE, related_name="+" ) The PartnerPage model (a simple Page type) is inside a different app (but the same project). Wagtail seems to ignore ordering in the Meta class on the model definition, maybe because of the Page tree ordering. I don't need custom ordering (so its not useful to make it an Orderable), I just need the PartnerPages to appear in alphabetical order from the MyPage form. In the content panels I tried: FieldPanel('partner', widget=forms.Select( choices=PartnerPage.objects.all().order_by('title').values_list('pk', 'title') )) but can't import PartnerPage because "Models aren't loaded yet" (not sure what that means). -
How to highlight the current section [Power Apps Menu]
When navigating in the menu bar, some of the options are not selected. I have tried to do it with JQuery but my attempts are in vain. Briefly what I am looking for is that if the user clicks Home Page it will be marked with a color and if About Us is clicked, the above selection will suffice and it will be marked as new. I tried using the condition {% if request.path ==" / "%} class =" weblink active mr-3 "{% else%} class =" weblink mr-3 "{% endif%} in the "Option 1 "but it didn't work. What am I doing wrong? {% if user %} <li role="none" {% if request.path=="/"%}class="weblink active mr-3" {% else %} class="weblink mr-3"{% endif %}> <a role="menuitem" aria-label="P&#225;gina principal" href="/" title="P&#225;gina principal" > P&#225;gina principal </a> </li> <!--Option 2--> <li role="none" class="weblink dropdown"> <a role="menuitem" aria-label="Servicios" href="#" class="dropdown-toggle" data-toggle="dropdown" title="Servicios" > Servicios <span class="caret"></span> </a> <ul class="dropdown-menu" role="menu"> <li role="none"> <a role="menuitem" aria-label="Servicios" href="/services/" title="Servicios" >Servicios</a> </li> <div class="divider"></div> <li role="none"> <a role="menuitem" aria-label="Producto A (ejemplo)" href="/services/product-a/" title="Producto A (ejemplo)" > Producto A (ejemplo) </a> </li> <li role="none"> <a role="menuitem" aria-label="Producto B (ejemplo)" href="/services/product-b/" title="Producto B (ejemplo)" > Producto B (ejemplo) </a> </li> </ul> … -
Django The redirect_uri does not match the registered value for linkedin signup
I am trying to add linkedin signup to my website but I am getting this error: "Bummer, something went wrong.The redirect_uri does not match the registered value" I am using django social-auth. I put this redirect url in linkedin OAuth 2.0 settings: https://www.example.com/complete/linkedin-oauth2/ I also found few question on stackoverfolow and followed but didn't work. question1 -
Request URL : http://127.0.0.1:8000/searchapp/?csrfmiddlewaretoken=qW5J7j0FQWjRQQgFsiWpX9hVh3YQ2loqZL5IuJnsZeJe2YDIcBM33wpVDBoUSAxx&q=black
Raised by: shop.views.allproduct project.urls """ecommerceproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('shop.urls')), path('searchapp/',include('searchapp.urls')), path('cart/',include('cart.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) i cannot acesses the search app. that is when i enter the shop app and try to search a product i am not able to search the item.as it is not accessing to the search app from shop app.please help me with this issue.this issue was somewhat solved by renaming the urls from '' to 'shop/'.but it is not a perment remady.please help me with this -
ImportError: No module named 'base' django1.8
I have django 1.8 this was working fine with Python 2.7 in my Windows, now I upgraded from Python 2 to Python 3 (Python 3.5.0) in my Windows pc, https://docs.djangoproject.com/en/3.2/releases/1.8/ Python compatibility Django 1.8 requires Python 2.7, 3.2, 3.3, 3.4, or 3.5. We highly recommend and only officially support the latest release of each series. Django 1.8 is the first release to support Python 3.5. Then I've created a virtual env with this command: python C:\Python35\Tools\Scripts\pyvenv.py e:\myproject_development_new\myproject_project\myproject\myenv Then I have installed manually all the requirements with pip install: Django==1.8.18 Pillow==2.9.0* beautifulsoup4==4.4.1 dj-database-url==0.3.0 django-ckeditor==5.0.3 django-hvad==1.4.0 django-imagekit==3.3 django-model-utils==2.4 flickr-api==0.5 inlinestyler==0.2.3 lxml==3.5.0 -e git+https://github.com/arneb/pyslideshare2.git@47cad8309ea2d6fe0f6cf0da13a486681a410128#egg=pyslideshare2-master requests==2.8.1 libsass==0.19.4 sass==2.3 sqlparse==0.1.16 XlsxWriter==1.0.2 django-debug-toolbar==1.4 honcho==0.7.1 mysqlclient==1.3.9 python-memcached==1.58 And all needed modules have been installed. Now I try to launch my webapp with this command: python manage.py runserver 80 And I see this error: (myenv) E:\myproject_development_new\myproject_project>python manage.py runserver 80 Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "e:\project_development_new\myproject_project\myproject\myenv\lib\site-packages\django\core\management\__init__.py", line 354, in execute_from_command_line utility.execute() File "e:\myproject_development_new\myproject_project\myproject\myenv\lib\site-packages\django\core\management\__init__.py", line 303, in execute settings.INSTALLED_APPS File "e:\myproject_development_new\myproject_project\myproject\myenv\lib\site-packages\django\conf\__init__.py", line 48, in __getattr__ self._setup(name) File "e:\myproject_development_new\myproject_project\myproject\myenv\lib\site-packages\django\conf\__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "e:\myproject_development_new\myproject_project\myproject\myenv\lib\site-packages\django\conf\__init__.py", line 92, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python35\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], … -
Getting POST requests Django Python
I have Django framework in my site, and i need to receive post request from user. So, how I can do this, and how may i process this request(etc, after getting post request, pull this datas) -
How to connect SQLlite to a project in Django (not an app)
While creating the project I didn't create an app and did everything in the base project. Now I am trying to connect database to my base project(not the app) I tried 'python manage.py makemigrations' but its showing "No changes detected". I even tried adding my project to INSTALLED_APPS in settings.py and then trying 'python manage.py makemigrations ' but it is showing an error " for model in model_or_iterable: TypeError: 'type' object is not iterable " I have created two models and also registered the models in admin.py 'admin.site.register(studentlogin), admin.site.register(facultylogin) I need help !! -
Django ORM: how to get 10 most recent Comments for each Post in a queryset
I have a Post model and Comment model which has FK to Post and a timestamp. I want to select all Posts, and for each Post I want to select 10 most recent comments available. This is for the django REST framework serializer to include those 10 Comments for each serialized Post. I want the query to be efficient, avoid making 101 selects when serializing a page of 100 Posts. prefetch_related does not seem to allow to slice X records for each selected record. annotation and subqueries won't work beacause it cannot return a list of objects. -
Django The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS. even though my fields are little
I created a script to programmatically upload data to my backend, but django keeps throwing the The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS. error at me, here is the data I am sending {'store': 'dang-1', 'name': 'Nike Air Max Plus', 'description': 'Let your attitude have the edge in your Nike Air Max Plus, a Tuned Air experience that offers premium stability and unbelievable cushioning.', 'brand': 'Nike', 'model': 'Air Max Plus', 'gender': 'U', 'category': 'shoes', 'image_v0_1': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (3).jpg'>, 'image_v0_2': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (3).png'>, 'image_v0_3': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (3).jpg'>, 'image_v1_1': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (1).jpg'>, 'image_v1_2': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (1).png'>, 'image_v1_3': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (1).jpg'>, 'image_v2_1': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (2).jpg'>, 'image_v2_2': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (2).png'>, 'image_v2_3': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (2).jpg'>, 'variants': '[{"is_default": true, "price": 65000, "quantity": 10, "shoe_size": 45, "color": "black"}, {"is_default": false, "price": 65000, "quantity": 10, "shoe_size": 45, "color": "multi-colored"}, {"is_default": true, "price": 65000, "quantity": 10, "shoe_size": 45, "color": "green"}]'} And here is the script I created import json import requests if __name__ == '__main__': json_file = open('data/data.json') products = json.load(json_file).get("products") for index, product in enumerate(products): print(f"Creating {index + 1}/{len(products)} - {product.get('name')}") … -
Specify exact opening hours for buisness
im trying to create custom field for django model. I need to store opening hours for every day of the week. class Restaurant(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) city = models.CharField(max_length=15) street = models.CharField(max_length=15) house_number = models.CharField(max_length=3) flat_number = models.CharField(max_length=3, default='0') phone_number = models.CharField(max_length=12) image = models.ImageField() rating = models.FloatField(validators=[validate_rating_number]) def __str__(self): return f'{self.name}, {self.city}' I have to store opening hours in a field like opening_hours = models.CustomField() -
Django dynamic url with data from DB
Models.py from django.db import models # Create your models here. class reviewData(models.Model): building_name = models.CharField(max_length=50) review_content = models.TextField() star_num = models.FloatField() class buildingData(models.Model): building_name = models.CharField(max_length=50) building_loc = models.CharField(max_length=50) building_call = models.CharField(max_length=20) views.py # Create your views here. from django.shortcuts import render from rest_framework.response import Response from .models import reviewData from .models import buildingData from rest_framework.views import APIView from .serializers import ReviewSerializer class BuildingInfoAPI(APIView): def get(request): queryset = buildingData.objects.all() serializer = ReviewSerializer(queryset, many=True) return Response(serializer.data) class ReviewListAPI(APIView): def get(request): queryset = reviewData.objects.all() serializer = ReviewSerializer(queryset, many=True) return Response(serializer.data) urls.py from django.contrib import admin from django.urls import path from crawling_data.views import ReviewListAPI from crawling_data.views import BuildingInfoAPI urlpatterns = [ path('admin/', admin.site.urls), path('api/buildingdata/', BuildingInfoAPI.as_view()), #path('api/buildingdata/(I want to put building name here)', ReviewListAPI.as_view()) ] I am making review api. I want to use building name as url path to bring reviews for specific buildings For example, there are a, b, c reviews a, b reviews are for aaabuilding c reviews are for xxxbuilding api/buildingdata/aaabuilding (only shows aaabuilding review) { building_name = aaabuilding review_content = a star_num = 5 building_name = aaabuilding review_content = b star_num = 3 } api/buildingdata/xxxbuilding (only shows xxxbuilding review) { building_name = xxxbuilding review_content = c star_num = 4 … -
How to add a date and time column in my Django default user page in admin
I am using the Django default user model and in my admin, I can see 5 columns which are username, email address, first name, last name, and staff status. I need to add another column here that displays the date joined. Can anyone help here? thanks in advance -
How to call a dropdown list html select with Ajax JQuery in Django
I'd like to choose an option in the first select dropdown list and based on the selected option, the ajax should load the second select dropdown list, how to do it? This is my code: Models: class MaintenanceEquipment(models.Model): equip_id = models.CharField(max_length=30, auto_created=False, primary_key=True) line_nm = models.CharField(max_length=20, blank=True, null = True) sequence = models.CharField(max_length=30, blank=True, null = True) equip_model = models.CharField(max_length=30, blank=True, null = True) def __str__(self): return self.equip_id Views: from django.shortcuts import render from maintenance.models import MaintenanceEquipment def maintenanceIssueView(request): equipment_list = MaintenanceEquipment.objects.all() context = {'equipment_list':equipment_list} return render(request, 'maintenance/maintenanceIssue.html', context) def load_equipment(request): if request.method == 'GET': line = request.GET.get('line_nm') equipment = MaintenanceEquipment.objects.filter(line_nm=line) context = {'equipment': equipment} return render(request, 'maintenance/maintenanceIssue.html', context) urls: urlpatterns = [ path('maintenanceIssueView/', views.maintenanceIssueView, name="maintenanceIssueView"), path('ajax/load_equipment/', views.load_equipment, name="ajax_load_equipment"), ] maintenanceIssue.html: <form method="POST" id="maintenanceForm" data-equipment-url="{% url 'ajax_load_equipment' %}" novalidate> {% csrf_token %} <div style="text-align:left;" class="container-fluid"> <div style="text-align:left;" class="form-row"> <div class="form-group col-md-6"> <label for="line_nm" style="font-size:medium;">Line</label> <select class="form-control" id="line_nm" name="line_nm" > {% for instance in equipment_list %} <option id="{{ instance.line_nm }}" value="{{ instance.line_nm }}">{{ instance.line_nm }}</option> {% endfor %} </select> </div> <div class="form-group col-md-6"> <label for="sequence" style="font-size:medium;">Machine</label> <select class="form-control" id="sequence" name="sequence"> {% for instance in equipment %} <option value="{{ instance.sequence }}">{{ instance.sequence }}</option> {% endfor %} </select> </div> </div> </div> </form> <script> …