Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can login in production but not in development [closed]
I have backed up my postgres database from production and am using it in my dev environment. Everything works as it does in production aside from authentication. When I try to login with the correct details it fails. I thought this could be because of something in settings.py however I don't really have anything added (maybe I need something?) -
How to perform a validation according to types, instead of field by field, in Django?
In Django, before calling the "save" method of an instance, it is possible to implement your own validation by defining the "clean" or "full_clean" method in the corresponding model. The problem is that in that case it would be necessary to check each of the fields and add a particular behavior; however, what I want is a more general behavior, so that if you enter a type that does not match the one defined in the model, such field will be saved as None. Example: Let's suppose an application, with the following model: class Company(models.Model): name = models.CharField(max_length=255, null=True, blank=True) date_of_formation = models.DateTimeField(null=True, blank=True) assets = models.FloatField(null=True, blank=True) And assume we have these 3 json data inputs: input_1 = { "pk": 1, "name": "Alexander", # right type "date_of_formation": "2021-01-01", # right type "assets": 500023.658 # right type } input_2 = { "pk": 2, "name": ["Alex", "Vero"], # WRONG type "date_of_formation": "2021-01-01", # right type "assets": 523658 # right type } input_3 = { "pk": 3, "name": ["Alex", "Vero"], # WRONG type "date_of_formation": 65, # WRONG type "assets": "523658" # WRONG type } The behavior I would expect is something like: Company.objects.create(**input_1) Company.objects.create(**input_2) Company.objects.create(**input_3) >> Company.objects.get(pk=1).__dict__ { "id": 1, "name": "Alexander", … -
Why we cannot use select_related for ManyToMany fields
let's say i have the following fields class ABC(models.Model) whatever=models.ManyToManyField('DEF') class DEF(models.Model) something=models.CharField() I want to retrieve ABC along side each DEF it's connected to, why i cannot do this ? ABC.objects.filter(pk=123).select_related('DEF').get() I believe we can do this in one SQL query like so select * from ABC inner join ABC_DEF on ABC.id = ABC_DEF.ABC_ID inner join DEF on DEF.id = ABC_DEF.DEF_ID -
How to filter Django serializer data?
I'm trying to filter data based on userName in JWT. This is how I've been trying to do it: views.py: class TestView(APIView): permission_classes = (IsAuthenticated,) def get(self, request): token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1] data = {'token': token} try: valid_data = VerifyJSONWebTokenSerializer().validate(data) user = valid_data['user'] request.user = user person = Person.objects.filter(userName=request.user) except ValidationError as v: print("validation error", v) return Response(person[0]) This works as I can get the Person data with print("Person: ", person[0]). The return Response(person[0]) however returns an error: TypeError: Object of type Person is not JSON serializable. I guess I could use a serializer class to return a valid JSON, am I right? I have this in my serializers.py: class TestSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' I just don't know how to use this with my view. If I use serializer instead of person = Person.objects.filter(userName=request.user), how is the filtering supposed to be done? Please correct me if I'm not on right track at all. -
Semgrep: Looking for wrong import
How would I go on about making Semgrep check if my codebase is important the wrong module from the wrong place? E.g. in my django project: from gettext import gettext but we should really do from django.utils.translation import gettext Any ideas on how to achieve this with semgrep? -
What is actual meaning of r'^ icon in every urls? can any one explain what is his meaning and how important this are in details [duplicate]
This is the code in question: url(r'^dreamreals/', ListView.as_view(model = Dreamreal, template_name = "dreamreal_list.html")), ) -
Threading: Restarting a thread
I have a django project that I am currently working on. I have several threads that I use to fill a database through API requests when the user asks for a database update using a button. This works great. My problem is that I would like users to be able to refresh the database more than once while the server is active (in the future). Since threads can't be restarted once they finish, I'm not really sure how to proceed to achieve what I want. Here are my threads: agencies_thread = threading.Thread(target=fill_agencies, name="Database Updater1") companies_thread = threading.Thread(target=fill_companies, name="Database Updater2") contracts_thread = threading.Thread(target=fill_contracts, name="Database Updater3") orders_thread = threading.Thread(target=fill_orders, name="Database Updater4") projects_thread = threading.Thread(target=fill_projects, name="Database Updater5") resources_thread = threading.Thread(target=fill_resources, name="Database Updater6") I'm thinking that the threads have to be recreated everytime someones presses the button, but adding those lines ^^ in my views.py function that manages the database loading can't really work considering my function: elif urlRequest[:12] == 'loading.html': # PAGE DE CHARGEMENT global updateValue if updateValue == 0: agencies_thread.start() companies_thread.start() contracts_thread.start() orders_thread.start() projects_thread.start() resources_thread.start() updateValue = 1 updateState = 0 if agencies_thread.is_alive(): agenciesState = 'en cours de chargement' else: agenciesState = 'Chargement terminé' updateState += 1 if companies_thread.is_alive(): companiesState = 'en … -
How to pass value/variable from one function to another in django - views
Not able to pass a variable from one function to another. @api_view(['GET']) def UserList(request): loc = User.objects.all() latest_id = User.objects.latest('userid').userid #want to pass this variable into DetailList function serializer = UserSerializer(loc, many=True) return Response(serializer.data) @api_view(['GET']) def DetailList(request): loc = Detail.objects.all() serializer = DetailSerializer(loc, many=True) return Response(serializer.data) and finaly want to use that userid variable to add the data into Detail table. class UserAPIView(APIView): def post(self, request ): userid = request.data.get('userid') name = request.data.get('name') age = request.data.get('age') gender = request.data.get('gender') address = request.data.get('address') phone = request.data.get('phone') user_serializer = UserSerializer(data={"name": name, "age": age, "gender": gender}) detail_serializer = DetailSerializer(data={"userid": userid,"address": address, "phone": phone}) if user_serializer.is_valid(raise_exception=True): user_serializer.save() if detail_serializer.is_valid(raise_exception=True): detail_serializer.save() return Response({'status': 'Success'}) not able to pass variable data through declaring global , as getting error Nulltype is not callable. -
SQL to Queryset Django
i want to use this query in django, i have tried and read the django document but i still can't understand it Sql to QuerySet Django SELECT * FROM movie as m INNER JOIN similarity as s ON m.`movie_id` = s.first_movie WHERE `movie_id` = 1 ORDER BY `s`.`similarity_score` DESC -
Nginx error_page will not display
I can't configure nginx custom error pages /etc/nginx/sites-enabled/mysite looks like this error_page 404 /custom_404.html; location = /custom_404.html { root /usr/share/nginx/html; internal; I tried other paths as well looked all over the internet and still nothing that helped. I wasl also following this tutorial but no luck If anyone knows the solution for this and have a time to respond it would be awsome. Thank you all. -
Django-Beard MP_Node save to database with post request
I am new to django and I am trying to understand Django-beard. What I want is to save the data to the db, but for the models I have inherited from MP_Node. Here is the models: class Update(MP_Node): name = models.CharField(max_length=30) update = models.TextField() date = models.DateField(auto_now_add=True) node_order_by = ['created'] I am using viewsets for the views part and it takes care of the CRUD: class UpdateViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticatedOrReadOnly] serializer_class = UpdateSerializer queryset = Update.objects.all() Can someone help me understand how do I save the data using POST or PUT? Currently I am getting the error that the path and depth fields are required but it is supposed to be generated automatically. I am using all the fields while serializing but I tried to set a particular few fields but then I am getting the error from the database level that Depth cannot be a not null constraint. class UpdateSerializer(serializers.ModelSerializer): class Meta: model = Update fields = '__all__' Is there a way to save the data using the MP_Node? -
How can check Bookings related to specific saloon in django
How can a saloon check the booking like how many people reserve the time slot for different service. When i click on check booking button is show the error 'WSGIRequest' object has no attribute 'saloon' Model.py class Booking(models.Model): saloon = models.ForeignKey(SaloonRegister, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) service = models.CharField(max_length=40) time = models.TimeField() date = models.DateField() View.py class SaloonCheckBooking(TemplateView): template_name = 'saloonCheck.html' def get(self, request, *args, **kwargs): checkBooking = Booking.objects.get(saloon_id=self.request.saloon.id) return render(request, self.template_name, {'checkBooking': checkBooking}) -
trying to setup mysql on ubuntu for django but getting error 'django.db.utils.OperationalError: (1046, 'No database selected')'
my Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'DATABASE' : 'DjangoProject', 'USER' : 'myprojectuser', 'PASSWORD' : 'Akbar@123456', 'HOST': 'localhost', 'PORT': '', # 'default-character-se' : 'utf8', # 'NAME': BASE_DIR / 'db.sqlite3', } } SHOW DATABASES command on terminal mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | DjangoProject | | information_schema | | mysql | | performance_schema | | sample | | sys | +--------------------+ 6 rows in set (0.00 sec) mysql> error File "/usr/local/lib/python3.8/dist-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/usr/local/lib/python3.8/dist-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) django.db.utils.OperationalError: (1046, 'No database selected') I have granted the user rights on the database but it still showing error, please help i want to run mySql just like sqlite3 where you can see your databases in the admin panel, and works same once settings are made, please tell if there is gui interface for mySQL and also how to see your database on the browser, -
Data not saving in database in Django
I am trying to save data into the database from the website. My web page is taking the data(image from my system) but in the database , its not showing up. If i add manually then its creating a new user entry and storing it. Here are my files: models.py class Details(models.Model): name = models.CharField(max_length=122) username = models.CharField(max_length=122) email = models.EmailField(max_length=122) password = models.CharField(max_length=20) def __str__(self): return self.name class Image_Data(models.Model): img_User = models.ForeignKey( Details, blank=True, null=True, on_delete=models.CASCADE) img_password = models.ImageField(null=True, blank=True) def __str__(self): return str(self.img_password) forms.py class ImageForm(ModelForm): class Meta: model = Image_Data fields = ('img_password',) labels = { 'img_password': 'Add your image ', } widgets = { 'img_password': forms.FileInput(attrs={'class': 'form-control', 'placeholder': 'Upload from device'}) } views.py def register_new_b(request): saved = False if request.method == "POST": # take whatever is posted to the Details Form form = ImageForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Your message has been sent!') return HttpResponseRedirect('/register_new_b?saved=True') else: form = ImageForm() if 'saved' in request.GET: # sends saved var in GET request saved = True return render(request, 'register2.html', {'form': form, 'saved': saved}) here is what i get in database upon saving the image -
Docker run, after docker-compose build could not translate host name “db” to address: Name or service not known
I have currently a system built with docker-compose, it creates a Django application. I've use a database inside a container (postgresql) in my testing build. I want upload my docker image to docker-hub. When i run $ sudo docker-compose up Server goes up sucecesfully Recreating rest_api_db_1 ... done Recreating rest_api_web_1 ... done Attaching to rest_api_db_1, rest_api_web_1 db_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | db_1 | 2021-06-08 07:22:10.698 UTC [1] LOG: starting PostgreSQL 13.3 (Debian 13.3-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit db_1 | 2021-06-08 07:22:10.699 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2021-06-08 07:22:10.699 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2021-06-08 07:22:10.708 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2021-06-08 07:22:10.719 UTC [26] LOG: database system was shut down at 2021-06-08 07:15:22 UTC db_1 | 2021-06-08 07:22:10.726 UTC [1] LOG: database system is ready to accept connections web_1 | Operations to perform: web_1 | Apply all migrations: admin, api_bus_routes, auth, contenttypes, sessions web_1 | Running migrations: web_1 | No migrations to apply. web_1 | Watching for file changes with StatReloader web_1 | Performing system … -
Django images not displaying properly,static images not displaying
image I am a beginner and I have no idea what the problem is I did give URL and DIR in settings.py STATIC_URL = '/static/' STATICFILES_DIR = [(os.path.join(BASE_DIR, 'static'))] my index.html {% extends 'base.html' %} {% load static %} {% block title %} <title>Home page</title> {% endblock title %} {% block content %} <div class="container"> <div class="row"> <div class="col-lg-4"> <img src="{% static 'images/stickynotes.jpg' %}" alt="Notes" width="1500" hwight="993"> </div> <div class="col-lg-4"> <img src="{% static 'images/stickynotes.jpg' %}" alt="Notes" width="1500" hwight="993"> </div> <div class="col-lg-4"> <img src="{% static 'images/stickynotes.jpg' %}" alt="Notes" width="1500" hwight="993"> </div> </div> </div> {% endblock content %} my base.html <!doctype html> {% load static %} <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> {% block title %} {% endblock title %} <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'index' %}"><img src="{% static 'images/logo.png' %}"</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-link" href={% url 'index' %}>Home</a> <a class="nav-link" href={% url 'todolist' %}>Todo List</a> <a class="nav-link" href={% url 'contactus' %}>Contact Us</a> <a class="nav-link" href={% url 'aboutus' %}>About Us</a> </div> </div> </div> </nav> </head> <body class="bg-secondary"> {% block content %} {% … -
How to include Token in Header using Django Rest Framework
I am working with Token Authentication using Django REST Framework. I am generating a new token during User Registration. I need to pass this token to the frontend including in header. These are my code: settings.py: INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework.authtoken', ... ] urls.py: (project level) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('accounts.urls')), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] urls.py: (app level) urlpatterns = [ path('signup/', views.Register.as_view({"post":"register"}), name='users'), path('login/', views.Login.as_view({"post":"create"}), name='login'), path('profile/', views.Profile.as_view({"get":"list"}), name='profile'), ] views.py: # Register View class Register(viewsets.GenericViewSet, mixins.CreateModelMixin,): serializer_class = UserRegisterSerializer def register(self, request): data_dict = self.request.data firstname = data_dict['firstname'] lastname = data_dict['lastname'] username = data_dict['username'] email = data_dict['email'] password = data_dict['password'] mobile = data_dict['mobile'] data = userRegistrationModel.objects.create(firstname=firstname, lastname=lastname, username=username, email=email, password=password, mobile=mobile) if data: user = data.set_password(password) data.save() token = Token.objects.create(user=data) return Response({"message": "Registered Successfully", "code": "HTTP_201_CREATED", "Token": token.key}) else: return Response({"message": "Sorry Try Next Time!!!", "code": "HTTP_403_FORBIDDEN"}) # Login View class Login(viewsets.GenericViewSet, mixins.CreateModelMixin,): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer def create(self, request, *args, **kwargs): data_dict = self.request.data email = data_dict['email'] password = data_dict['password'] data = authenticate(email=email, password=password) if data: users = Token.objects.filter(user=data).first() userData = UserRegisterSerializer(data) return Response({"message": "Login Successfully", "code": "HTTP_200_OK", "token": users.key, "user": userData.data}) else: return Response({"message": "Invalid Login", "code": "HTTP_401_UNAUTHORIZED"}) # Profile View … -
call another viewset method from same viewset
I am writing a simple django app where all my apis are based on class based viewsets. I've the following viewset with 2 methods(2 different api calls) but in one of the apis i wanted to access another api's method. class TestViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet): queryset = Model.objects.all() serializer_class = MSerializer @action(detail=True, methods=["PUT"], name="viewone") def viewone(self, request, pk): try: <logic> except Exception as e: raise("error") @action(detail=True, methods=["PUT"], name="viewtwo") def viewtwo(self, request, pk): try: viewone = self.as_view({'put': 'viewone'})(request, pk=pk) except Exception as e: print(e) raise("error") the view set two throws me the following AttributeError: This method is available only on the class, not on instances. what am i doing wrong here? -
Django not recognizing empty url config
Sorry, beginner here. I was following this tutorial https://www.youtube.com/watch?v=JD-age0BPVo on py/django and managed to get the webserver running. However, it simply displays the default page: when in my urls.py, I have the default page set. urls.py from django.contrib import admin from django.urls import include from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', include('api.urls')) ] and in api.urls: from django.urls import path from .views import main urlpatterns = [ path('', main) ] and finally in api.views.py I have main(request) from django.shortcuts import render from django.http import HttpResponse # Create your views here. def main(request): return HttpResponse("hello") My project directory looks like this in case it helps: -
How to implement multiple subcategory selection in Django models
I want to implement multiple choice field in model for example i have table named as Category and Subcategory and what i want when i add subcategory i can select multiple Categories using checkbox and categories are stored in a list. NOTE : Categories will come dynamic -
How to achieve multiple sorting levels in Django ORM Queries
On the below Posts model , I need to sort the posts by both date and likes. the results should be last 24 hr posts ,sorted by likes , then the next day posts sorted by likes , it goes on.. class Posts(models.Model): comment_text= models.CharField(max_length=1000) date = models.DateTimeField(default=timezone.now()) likes = models.IntegerField(default=0) views.py latest=Posts.objects.filter().order_by(-date,-likes) the above query is not giving the desired results , let us say if there are two posts created at 07/06/2021 at 1 pm which has 3 likes and another one at 1:30 pm which as 1 like. Then the post created at 1:30 pm with 1 like comes on top instead of the post at 1 pm with 3 likes -
How to solve AttributeError: 'NoneType' object has no attribute 'encode' in Django
I tried to give validation to the give form in the HTML file using JAVASCRIPT and also check the email is available or not in the database table using AJAX.Also imported sha256 from hashlib.But I got an error like this. I did not understand why this error happens.Can anyone suggests a solution for this problem. Internal Server Error: /User/Registration/ Traceback (most recent call last): File "C:\PYTHON\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\PYTHON\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Project\salon\user\views.py", line 214, in userregister epassword = sha256(upassword.encode()).hexdigest() AttributeError: 'NoneType' object has no attribute 'encode' HTML file: <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <title>User Registration</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link href="{% static 'styles/style.css' %}" rel="stylesheet"/> <script type="text/javascript" language="javascript"> function getsid(str) { print(str) if(window.XMLHttpRequest) { xmlhttp= new XMLHttpRequest(); } xmlhttp.onreadystatechange=function() { if(xmlhttp.readystate==4 && xmlhttp.status==200) { document.getElementById("lemail").innerHTML= xmlhttp.responseText; } } xmlhttp.open("GET","{% url 'checkemail' %}?id="+str,true); xmlhttp.send(null); } </script> </head> <body> <section class="sreg" id="sreg"> <div class="container-fluid"> <div class="htop"> <h4>User <span>Register Form</span></h4> </div> <div class="row"> <div class="col-12"> <form method="POST" name="contact" action="{% url 'userregister' %}"> {%csrf_token%} <div class="form-row"> <div class="form-group col-md-6"> <label for="fname">First Name</label> <input type="text" class="form-control" id="fname" name="fname" placeholder="First Name"> <span id="lfname"></span> </div> <div … -
Can't create user post in django
I'm trying to create a post using the User profile instance. The post is saved but there is no object created in the database In my user_blog app i have created Profile model for user blog_users/models.py from django.db import models from django.conf import settings from django.utils import timezone from django.urls import reverse from django.utils.text import slugify # Create your models here. class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile_user', on_delete=models.CASCADE) bio = models.CharField(max_length=500, blank=True) url = models.URLField(max_length=200, blank=True, null=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics/', blank=True, null=True) created_date = models.DateTimeField(auto_now_add=True) slug = models.SlugField(unique=True, null=False) def save(self, *args, **kwargs): self.slug = slugify(self.user.username) return super().save(*args, **kwargs) I have created Post model in separate app (posts) posts/models.py from django.db import models from django.conf import settings from django.utils import timezone from django.urls import reverse from django.utils.text import slugify from ckeditor.fields import RichTextField from blog_users.models import Profile # Create your models here. class Post(models.Model): profile = models.ForeignKey(Profile, related_name='user_post', on_delete=models.CASCADE) title = models.CharField(max_length=250, blank=True) content = RichTextField(blank=True, null=True) date_created = models.DateTimeField(default=timezone.now) slug = models.SlugField(unique=True, null=False) def __str__(self): return f"{self.profile.user.username} | post" posts/views.py @login_required(login_url='account_login') def create_post(request): current_user = Profile.objects.get(user=request.user) form = CreatePost(instance=current_user) if request.method == "POST": form = CreatePost(request.POST, instance=current_user) if form.is_valid(): form.save() print('success') return redirect(f"/blog_users/{request.user}") context = { 'form': form … -
How to populate django select form from bootstrap
I'm currently having a problem in terms of populating the select tag from bootstrap 5. When I'm using {{form.as_p}} all options in select tag are shown but not with bootstrap. here is my forms.py and models.py: models.py class Category(models.Model): class Meta: verbose_name = _('Category') verbose_name_plural = _('Categories') ordering = ['id'] name=models.CharField(max_length=255,verbose_name=_('Category')) def __str__(self): return self.name def get_absolute_url(self): return reverse('home') class Post(models.Model): class Meta: verbose_name = _('Post') verbose_name_plural = _('Posts') ordering = ['id'] title= models.CharField(max_length=255,verbose_name=_('Post Title')) header_image= models.ImageField(null=True,blank=True,upload_to='images/',verbose_name=_('Image')) title_tag= models.CharField(max_length=255, verbose_name=_('Tag')) author=models.ForeignKey(User,on_delete=models.CASCADE,verbose_name=_('Author')) body=RichTextField(blank=True,null=True,verbose_name=_('Description')) status = models.BooleanField(default=False,verbose_name=_('Private')) post_date=models.DateTimeField(auto_now_add=True,verbose_name=_('Date Posted')) category= models.CharField(max_length=255,verbose_name=_('Category')) likes= models.ManyToManyField(User,related_name='blog_posts',verbose_name=_('Likes')) def total_likes(self): return self.likes.count() def __str__(self): return self.title + '|' + self.author def get_absolute_url(self): return reverse('home',args=(str(self.id))) forms.py choices=Category.objects.all().values_list('name','name') choice_list=[] for item in choices: choice_list.append(item) class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title','title_tag','author','body','category','header_image','status') widgets= { 'title':forms.TextInput(attrs={'class':'form-control'}), 'title_tag':forms.TextInput(attrs={'class':'form-control'}), 'author':forms.TextInput(attrs={'class':'form-control','value':'','id':'author_id','type':'hidden'}), 'category':forms.Select(choices=choices,attrs={'class':'form-select'}), 'status':forms.CheckboxInput(attrs={'class':'form-check-input'}), 'body':forms.Textarea(attrs={'class':'form-control'}), } and here is my html template file: <div class="form-floating"> <select name="category" class="form-select" id="id_category" aria-label="Floating label select example" maxlength="255"> </select> <label for="floatingInput">Category</label> </div> I have 3 inputs at the moment coding,news and sports but they only show when I use the {{ form.as_p }} template -
django rest framework - update ModelViewSet class variable
I have a ModelViewSet that looks like the following class BusinessViewSet(ModelViewSet): filterset_class = BusinessFilter serializer_class = BusinessSerializer ordering_fields = [ "source", "xl_source", "company_name", "contact_title", "category", "contact_name", "description", "tags", "business_hours", "location", "website", "phone", "email", "social_media", "address", "is_ecommerce", "is_verified", "ownership", "supplemental_information", "products", "location_street", "location_city", "location_state", "location_zip", ] def get_queryset(self): referer = self.request.META["HTTP_REFERER"] try: source = referer.split("source=")[1] except Exception as e: print(e) source = None if source == None: queryset = Business.objects.all() elif source == 'SBASpecial': queryset = SBABusiness.objects.all() self.serializer_class = SBABusinessSerializer self.filterset_class = SBABusinessFilter self.ordering_fields = [ 'name_and_trade_of_firm', 'contact', 'address_city', 'capabilities_narrative', 'ownership_self_certs', 'email_address', 'www_page_url', 'phone_number', 'year_established', 'keywords', 'naics_codes', ] else: queryset = Business.objects.filter(xl_source=source) return queryset As you can see, if the source is SBASpecial, I try to change the class variables serializer_class and ordering_fields inside get_queryset. Obviously this is not working. I've looked at the django rest framework documentation and there isn't anything there that can help me with this problem. What can I do? Any help is appreciated. Thanks in advance