Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add array of integer field in Django Rest Framework?
I want to add an array of integer fields in my model class Schedule(models.Model): name = models.CharField(max_length=100) start_time = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(null=True, blank=True) day_of_the_week = ?? ( array of integer ) I tried with class Schedule(models.Model): name = models.CharField(max_length=100) start_time = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(null=True, blank=True) day_of_the_week = models.CharField(max_length=100) and in the serializer add ListField class ScheduleSerializer(serializers.ModelSerializer): day_of_the_week = serializers.ListField() class Meta(): model = Schedule fields = "__all__" but this one is not working can anyone suggest me how to deal with this issue? -
can find the problem to solve Template doesn't working?
from django.shortcuts import render # Create your views here. def home(request): return render(request, 'dashboard/home.html') from django.urls import path from . import views urlpatterns = [ path('', views.home), ] Plz Help me to Resolve the Problem adding path in template_DIRs -
Pointing Nginx to Gunicorn on a different server
I have a bunch of different services running across several lxc containers, including Django apps. What I want to do is install Nginx on the Host machine and proxy pass to the Gunicorn instance running in an lxc container. The idea is that custom domain names and certs are added on the Host and the containers remain unchanged for different installs. it works if I proxy_pass from the host to nginx running in a container, but I then have issues with csrf, which for the Django admin, cannot be turned off. Thus, what I would like to do is only run nginx on the host server connecting to the Gunicorn instance on the lxc container. Not sure if that will fix the csrf issues, but it does not seem right to run multiple nginx instances -
How to get filtered elements in table in paginator django
views.py get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)) get_records_by_date = check_drop_down_status(get_records_by_date,drop_down_status) filtered_results = MyModelFilter(request.GET,queryset=get_records_by_date) context['filtered_results'] = filtered_results page_numbers = request.GET.get('page', 1) paginator = Paginator(filtered_results.qs, 5) users = paginator.get_page(page_numbers) context['users'] = users index.html <table id="bootstrapdatatable" class="table table-striped table-bordered" width="100%"> <thead> <tr> <th>scrapper_id</th> <th>scrapper_jobs_log_id</th> <th>external_job_source_id</th> <th>start_time</th> <th>end_time</th> <th>scrapper_status</th> <th>processed_records</th> <th>new_records</th> <th>skipped_records</th> <th>error_records</th> </tr> </thead> <tbody> {% for stud in users %} {% csrf_token %} <tr> <td>{{stud.scrapper_id}}</td> <td>{{stud.scrapper_jobs_log_id}}</td> <td>{{stud.external_job_source_id}}</td> <td>{{stud.start_time}}</td> {% if stud.end_time == None %} <td style="color:red">No result</td> {% else %} <td>{{stud.end_time}}</td> {% endif %} {% if stud.scrapper_status == "1" %} <td>{{stud.scrapper_status}} --> Started</td> {% else %} <td>{{stud.scrapper_status}} --> Completed</td> {% endif %} <td>{{stud.processed_records}}</td> <td>{{stud.new_records}}</td> <td>{{stud.skipped_records}}</td> <td>{{stud.error_records}}</td> </tr> {% endfor %} </tbody> </table> <div class="paginator"> <span class="step-links"> {% if users.has_previous %} <a href="?page=1">&laquo; First</a> <a href="?page={{ users.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{users.page}} of {{users.paginator.num_pages}}. </span> {% if users.has_next %} <a href="?page={{ users.next_page_number }}">&raquo; Next</a> <a href="?page={{ users.paginator.num_pages }}">&raquo; Last</a> {% endif %} </span> I have to filter dates and need to find the status of checkbox the filtered element should show in table. Is there any solutions. How to paginate the datas based on the filtered result and pass the filtered results to the table. Is there any solution how to pass … -
How to convert a False or True boolean values inside nested python dictionary into javascript in Django template?
this is my views.py context = { "fas": fas_obj, } # TemplateResponse can only be rendered once return render(request, "project_structure.html", context) in the project_structure.html and javascript section const pp = {{ fas|safe }}; I get an error here. because fas contains a False or True boolean value somewhere deep inside. fas is complicated and has lists of dictionaries with nested dictionaries. What did work is I did this context = { "fas": fas_obj, # need a fas_json version for the javascript part # because of the boolean in python doesn't render well in javascript "fas_json": json.dumps(fas_obj), I know now I have two versions because I need the original version for the other part of the template in the javascript const pp = {{fas_json|safe}}; Is there an easier way than passing the original and the json version? -
I don't have django_redirect table with migration marked applied though
python manage.py showmigrations redirects [X] 0001_initial [X] 0002_alter_redirect_new_path_help_text Request URL: http://127.0.0.1:8000/admin/redirects/redirect/add/ But ERROR saying..... \Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 357, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: django_redirect -
I am getting csrftoken in cookie and do not able to send in response make post, delete and put request from angular13 to Django rest framework
I need to make delete request to the server(django) from client(angular13) with session authentication, and i am also getting the session id and csrf token in the cookie but not able to make the request, i am getting csrftoken missing in the console. thank you //component.ts deleteStory(id : string){ console.log(id) this.storyapiService.deleteStory(id).subscribe(); } //service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { story } from './story'; import { Observable, of } from 'rxjs'; import { catchError, map, tap } from 'rxjs/operators'; import {CookieService} from 'ngx-cookie-service'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', cookieName: 'csrftoken', headerName: 'HTTP_X_CSRFTOKEN', // 'X-XSRF-TOKEN': 'csrftoken', }) }; @Injectable({ providedIn: 'root' }) export class StoryapiService { API_URL = 'http://127.0.0.1:8000/storyapi/'; constructor(private http: HttpClient) { } /** GET stories from the server */ Story(): Observable<story[]> { return this.http.get<story[]>(this.API_URL); } /** POST: add a new story to the server */ addStory(story : story[]): Observable<story[]>{ return this.http.post<story[]> (this.API_URL,story, httpOptions); //console.log(user); } /** DELETE: delete source to the server */ deleteStory(id: string): Observable<number>{ return this.http.delete<number>(this.API_URL +id, httpOptions); } } //component.html <!--<h2>My stories</h2>--> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <div class="container mt-5"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search..." [(ngModel)]="filterTerm" /> </div> <ol> <li *ngFor="let story of … -
Django Rest Framework, how to use serializers.ListField with model and view?
I want to store an array of integers in the day_of_the_week field. for which I am using the following code models.py class Schedule(models.Model): name = models.CharField(max_length=100) day_of_the_week = models.CharField(max_length=100) serializers.py class ScheduleSerializer(serializers.ModelSerializer): day_of_the_week = serializers.ListField() class Meta(): model = Schedule fields = "__all__" Views.py # schedule list class ScheduleList(APIView): def get(self, request): scheduleData = Schedule.objects.all() serializer = GetScheduleSerializer(scheduleData, many=True) return Response(serializer.data) def post(self, request): serializer = ScheduleSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response("Schedule Added") Data save successfully but when I try to get data it returns data in this format "day_of_the_week": [ "[2", " 1]" ], is there any way to get an array of integers as a response? -
How can show variable in UI in django from view function?
I want to show value of pro in UI but not getting , here is my test view function code .value of pro is getting from previous function using django session variable. @api_view(['GET', 'POST']) def test(request): pro = request.session.get('j') print("Request ID from Index View : ", pro) if request.method == "POST": form = TestForm(request.POST) if form.is_valid(): print("Form is Valid") selected = form.cleaned_data.get('myfield') print(selected) else: # rq = request_id["request_id"] s = sql() query = f"""update request_form_db.request_form_mymodel set is_approved=1 where request_id = '{pro}' """ print(query) s.update_query(query) print("Updated Successfully") form = TestForm() else: form = TestForm() context = {'form': form, 'pro': pro} return render(request, 'test.html', context) Here is my html code test.html <form action ="{% url 'test' %}" method="POST"> <div class="form_data"> {% csrf_token %} <br><br> {{form.myfield}} <label><b>Git Id</b></label> <br><br> <br><br> {{form.pro}} <input type="submit" value="Submit" class="btn btn-success" /> form.myfield returns what i want but value of pro variable not getting.please help -
Shengpay payment in Python (Django)
I need to set up customer payments using Shengpay. Is there any documentation or demo available for that. The official docs only support Java. I seatched the official docs and various search engines to see if anyone had implemented it before. Couldn't find anything. -
How to apply filtering over order by and distict in django orm?
Name email date _________________________________________________ Dane dane@yahoo.com 2017-06-20 Kim kim@gmail.com 2017-06-10 Hong hong@gmail.com 2016-06-25 Dane dddd@gmail.com 2017-06-04 Susan Susan@gmail.com 2017-05-21 Dane kkkk@gmail.com 2017-02-01 Susan sss@gmail.com 2017-05-20 I can get the first entries of each unique by using EmailModel.objects.all().order_by('date').distinct('Name'). this returns Name email date _________________________________________________ Dane dane@yahoo.com 2017-06-20 Kim kim@gmail.com 2017-06-10 Hong hong@gmail.com 2016-06-25 Susan Susan@gmail.com 2017-05-21 What i want to do here is to only include it in the result if the very first entry is something different like more filtering over it? for ex- i don't want to include it in the result if the first email id is dane@yahoo.com for Dave and only include it if it is something different. -
Show html spans for certain users only in Django
{% if show_approval %} <span>Approvals</span></a> {% endif %} I've to create this certain if condition in the html, where this Approvals would be visible for certain users, i've code for this in the python file context_data = {'show_approval': self.is_approval_supported()} I've to write a function to show it for this user only. where request.user == 'abcd@mail.com' i'm not sure how should i be writing this, i tried like this, but it ain't working. def is_approval_supported(request,self): if request.user == 'abcd@mail.com': return True else: return False -
django models Foreighn key правильно поставить
как поставить Foreighn key чтобы вибрать несколько объектов из выпадающий списка У меня два таблица один из них столбик выбираетса несколько вариант -
Serialize QuerySet to JSON with FK DJANGO
I want to send a JSON of a model of an intersection table so I only have foreign keys saved, I tried to make a list and then convert it to JSON but I only receive the ids and I need the content, I also tried in the back as a temporary solution to make a dictionary with the Queryset but the '<>' makes it mark an error in the JS, does anyone know a way to have the data of my foreign keys and make them a JSON? models: class Periodos(models.Model): anyo = models.IntegerField(default=2022) periodo = models.CharField(max_length=10) fecha_inicio = models.DateField(blank=True, null=True) fecha_fin = models.DateField(blank=True, null=True) class Meta: app_label = 'modelos' verbose_name = u'periodo' verbose_name_plural = u'Periodos' ordering = ('id',) def __str__(self): return u'%s - %s' % (self.anyo,self.periodo) class Programas(models.Model): programa = models.CharField(max_length=255,blank=True, null=True) activo = models.BooleanField(default=True) class Meta: app_label = 'modelos' verbose_name = u'Programas' verbose_name_plural = u'Programas' def __str__(self) -> str: return self.programa class Programa_periodo(models.Model): periodo = models.ForeignKey(Periodos, related_name='Programa_periodo_periodo',on_delete=models.CASCADE) programa = models.ForeignKey(Programas, related_name='Programa_periodo_Programa',on_delete=models.CASCADE) class Meta: app_label = 'modelos' verbose_name = u'Programa Periodo' verbose_name_plural = u'Programa Periodo' def __str__(self) -> str: return self.programa.programa py where i send data def iniciativa(request): if request.user.is_authenticated: context = {} context['marcas'] = json.dumps(list(Marcas.objects.values())) context['eo'] = … -
Django template syntax: Compare with string fails
Here is the code: "parents" is a ManyToManyRelation key in model student. class Parents(models.Model): """docstring for parents""" name = models.CharField(_('name'),max_length=8, default="") phone_number = models.CharField(max_length=10) relationship_choices = [("M", _("mom")),("D",_("Dad"))] relationship = models.CharField(_("gender"),max_length=6, choices = relationship_choices, default="M"); Template: {% for parent in student.parents.all %} {% if parent.relationship =="M" %} <td name ="contactor"> {{parent.name}} </td> <td name ="relationship"> {{parent.relationship}} </td> <td name ="phone_number"> {{parent.phone_number}} </td> {% endif %} {% endfor %} This line {% if parent.relationship =="M" %} has error error: Could not parse the remainder: '=="M"' from '=="M"' What's the problem? Thanks. -
How can I compare the user's answer in the quizz with the correct answer in the database and give a point if the answer is correct?
How can I compare the user's answer in the quizz with the correct answer in the database and give a point if the answer is correct? currently i get all answers wrong, after the quiz.I Want, if the user choice the right answer, that he get a point and if the answer wrong than get he 0 points. views.py def math(request): if request.method == 'POST': print(request.POST) questions = QuesModel.objects.filter(kategorie__exact="mathematics") score = 0 wrong = 0 correct = 0 total = 0 for q in questions: total += 1 answer = request.POST.get(q.question) if q.ans == answer: score += 10 correct += 1 else: wrong += 1 percent = score / (total * 10) * 100 context = { 'score': score, 'time': request.POST.get('timer'), 'correct': correct, 'wrong': wrong, 'percent': percent, 'total': total, } return render(request, 'result.html', context) else: questions = QuesModel.objects.all() context = { 'questions': questions } return render(request, 'mathe.html', context) model.py class QuesModel(models.Model): Categorie= ( ("mathematics", "mathematics"), ("Business Administration", "Business Administration"), ) categorie= models.CharField(max_length=400, null=True, choices=Categorie) explaination= models.CharField(max_length=400, null=True) user = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL) question = models.CharField(max_length=200, null=True) op1 = models.CharField(max_length=200, null=True) op2 = models.CharField(max_length=200, null=True) op3 = models.CharField(max_length=200, null=True) op4 = models.CharField(max_length=200, null=True) ans = models.CharField(max_length=200, null=True) def __str__(self): return self.question … -
Django Class Based View - Generic detail View must be called with object pk or a slug in URLconf
So I have a program that takes in the currently logged in user and updates their profile image. Initially I had a function based view, and a url matching pattern (the url for accessing profile, and thereby editing it is localhost:8000/profile) #views.py @login_required def profile(request): 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, "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, 'p_form':p_form} return render(request, 'users/profile.html', context) #following line in URLpatterns of urls.py path('profile/', user_views.ProfileUpdateView.as_view(), name='profile'), It worked fine. However when I tried changing it to a class based view as below, it started giving errors #views.py class ProfileUpdateView(UpdateView): model=Profile fields=['image'] Case 1: I had this in urls.py URLpatterns path('profile/', user_views.ProfileUpdateView.as_view(), name='profile'), It gave an error - (https://i.stack.imgur.com/6mXfI.png)](https://i.stack.imgur.com/6mXfI.png) I don't understand why this error popped up because there is no page specific ID, like profile/1, profile/2 - just profile/ because the user is automatically identified by who is currently logged in hence no need to pass in a separate parameter in the url Case 2: after I added in pk parameter path('profile/<int:pk>/', user_views.ProfileUpdateView.as_view(), name='profile'), This error pops up (https://i.stack.imgur.com/Op9eQ.png)](https://i.stack.imgur.com/Op9eQ.png) I have been stuck for a day now. I went through the Django … -
Django - Null Integrity error not allowing POST
The error that I am getting when trying to POST is: django.db.utils.IntegrityError: null value in column "interest_category_id" of relation "teamStart_project" violates not-null constraint Here are my Serializers: class InterestSerializer(serializers.ModelSerializer): class Meta: model = Interests fields = ('id', 'interest_name') class ProjectsSerializer(serializers.ModelSerializer): interest_category = serializers.StringRelatedField() class Meta: model = Project fields = ( 'project_title', 'project_description', 'interest_category', 'created_at', 'updated_at', ) Here are my models: class Interests(models.Model): interest_name = models.CharField(max_length=50) created_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.interest_name class Project(models.Model): project_title = models.CharField(max_length=255) project_description = models.TextField(max_length=1500) interest_category = models.ForeignKey(Interests, on_delete=models.CASCADE) created_by = models.ForeignKey(User, related_name='projects', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return "Project name:" + "\n" + self.project_title + "\n" + "|" + "\n" + "Created By:" + "\n" + self.created_by.username I can get rid of the error by removing interest_category = serializers.StringRelatedField() but this issue is, if I do not remove this line, the frontend shows the ID of interest_category and not the respective name. For example, this is what the frontend will show: With this line: interest_category = serializers.StringRelatedField() -------------------------------------------------------------------- Project Title: TestItem1 Project Description: TestItem1Desc Interest Category: Django Without the line: --------------------------------------------------------------------- Project Title: TestItem1 Project Description: TestItem1Desc Interest Category: 1 When I … -
django - swap foreign keys of one-to-one relationship in an atomic transaction
i have a Unit model with a one-to-one related handler defined as such: handler = models.OneToOneField('users.Handler', related_name="unit_obj", blank=True, null=True, on_delete=models.SET_NULL) i'm trying to update a set of units in an atomic transaction where the unit's handler_id foreign key can be set to null or any other handler_id. the problem is when handlers are being swapped. i initially tried saving the updated unit inside an atomic transaction. but as soon as unit.save() is called on the first unit i get an integrity error because the second unit still has the same handler_id. i was hoping that the atomic transaction would defer the integrity error on individual unit.save() calls and only throw the error at the end of the transaction if there actually were any. try: with transaction.atomic(): for unit_model in unit_models: unit = Unit.objects.get(id=unit_model['id']) unit.handler_id = unit_model['handler']['id'] if unit_model['handler'] is not None else None unit.save() except IntegrityError as e: print(f'Error saving units: {str(e)}') then i tried using bulk_update which i was sure would solve the issue. unfortunately i get the same error (duplicate key value violates unique constraint) even though i have confirmed that there are no duplicates in the list. it still seems to be applying the saves sequentially, though … -
Django Testing for Login and token collection
Trying to write test for Django login. I want to request to login, collect token and access different view functions. How do i write a test in python for this. Help appreciated. -
connect to a postgres database inside of a docker container from django running on host machine
I have a postgres database running inside a container with pgadmin connected to it, the docker-compose.yml is as follows: postgres: image: postgres:13.0-alpine volumes: - postgres:/var/lib/postgresql/data ports: - "5432:5432" env_file: - $ENV_FILE pgadmin: image: dpage/pgadmin4 volumes: - pgadmin:/var/lib/pgadmin ports: - "${PGADMIN_PORT:-5050}:80" restart: unless-stopped depends_on: - postgres env_file: - $ENV_FILE my django database settings are: DATABASES = { "default": { "ENGINE": os.environ.get("POSTGRES_ENGINE", "django.db.backends.postgresql"), "NAME": os.environ.get("POSTGRES_NAME", "postgres"), "USER": os.environ.get("POSTGRES_USER", "admin"), "PASSWORD": os.environ.get("POSTGRES_PASS", "admin"), "HOST": os.environ.get("POSTGRES_HOST", "127.0.0.1"), "PORT": os.environ.get("POSTGRES_PORT", "5432"), } } The traceback is: Traceback (most recent call last): File "C:\Users\liam.obrien\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\liam.obrien\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\channels\management\commands\runserver.py", line 76, in inner_run self.check_migrations() File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\core\management\base.py", line 576, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\db\migrations\loader.py", line 58, in __init__ self.build_graph() File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\db\migrations\recorder.py", line 81, in applied_migrations if self.has_table(): File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\db\migrations\recorder.py", line 57, in has_table with self.connection.cursor() as cursor: File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\db\backends\base\base.py", line 284, in cursor return self._cursor() File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\db\backends\base\base.py", line 260, in _cursor self.ensure_connection() File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, … -
Can i use doument.cookie to edit a cookie created with request.set_cookie in django project?
I am working on a Django project. Basically a simple game that uses x and y cordinates to determine the pos of the player on the map using js. So i figured that using cookies to "save" the progress of the player would be a simple way for what i need. Since i need to get these parameters from javascript file i was wondering if i could edit them directly from the file without the need of using a json to pass them to the views.py in order to check if the cookie is empty or has data when the user selects either load game or start a new one. I prefer doing it this way if possible to be able to maintain cookies without expiring thanks to django sessions engine since i haven't found a way to pass the data directly between the views.py and the .js files. Thanks for the help anyway -
How to edit many to many relation different ways in Django admin
Models Movie(models.Model): categories = ManyToManyField('Category', blank=True) Category(models.Model): grouping = CharField(choices=CategoryGroupings) where CategoryGroupings is one of 'genre', 'holiday', or 'custom' Question In the Movie Django admin, I would like to have three autocomplete_fields, one for each of the individual category types. I can't add 'categories' three times to the autocomplete_fields array. Without altering the model field definitions (ie without needing a migration), how would I manage this? -
How to pass extra argument to get_serializer_class
I need to select a serializer based on the value of an object instance. How do I pass an additional argument to get_serializer_class to be able to do the validation there? def get_serializer_class(self, extra_option): if extra_option: return ModelSerializer return ModelSerializer2 serializer = self.serializer_class(data=request.data, extra_option=smth_instance) Error: TypeError: Field.__init__() got an unexpected keyword argument 'extra_option' -
How to add filters to jQuery.fancyTable (or alternative)
I'm currently using fancyTable to display a table of django results. I have been able to add a search bar and sortable columns (ascending/descending). I've also added "filters" but all they really do is update the search bar with pre-defined text The problem is that I want to be able to use these filters to only show text that matches exactly. For example, if I'm trying to filter by Stage looking for Prescreen I will currently get lines that include Prescreen, Passed - Prescreen 1, and Passed - Prescreen 2 I've already tried writing a function that sets the tr = display="none", but the pagination does not refresh, so I'm left with several blank pages. t Currently initiating fancyTable as such: <script type="text/javascript"> $(document).ready(function () { $(".sampleTable").fancyTable({ /* Column number for initial sorting*/ sortColumn: 0, sortOrder: 'descending', // Valid values are 'desc', 'descending', 'asc', 'ascending', -1 (descending) and 1 (ascending) /* Setting pagination or enabling */ pagination: true, /* Rows per page kept for display */ perPage: 12, globalSearch: true }); }); </script> Any ideas on how I can create these filters? I don't see anything from fancyTable about filters.