Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Filter objects from child class with parent class primary key passed in URL
I'm a newbie in Django and I'm trying to pass all the Posts made for each vehicle in a vehicle detail html page. My vehicles/models.py: *vehicles/models.py* class Vehicle(models.Model): TESLA = 'TESLA' MAZDA = 'MAZDA' VOLVO = 'VOLVO' VEHICLE_CHOICES = ( (TESLA, "Tesla"), (MAZDA, "Mazda"), (VOLVO, "Volvo"), ) owner = models.ForeignKey(User, on_delete=models.CASCADE) model = models.CharField(max_length=9, choices=VEHICLE_CHOICES, default=TESLA) def __str__(self): return self.model class Meta: db_table = "vehicles" My Posts models.py: *blog/models.py* from django.db import models from django.contrib.auth.models import User class Post(models.Model): date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, default=None ) def get_absolute_url(self): return reverse('post-detail', kwargs ={'pk': self.pk} ) class Meta: db_table = "chargehistory" I am already passing in a html file all the Vehicles for each User and now i would like to get all the posts made for each User's vehicle. *vehicles/views.py* class UserVehicleListView(ListView): model = Vehicle template_name = 'vehicles/vehicles.html' # <app>/<model>_<viewtype>.html context_object_name = 'vehicles' def get_queryset(self): return Vehicle.objects.filter(owner_id= self.request.user.id) class UserVehicleDetailView(DetailView): model = Vehicle *vehicles/urls.py* urlpatterns = [ path('vehicles', UserVehicleListView.as_view(), name='vehicle-list'), path('vehicles/<int:pk>', UserVehicleDetailView.as_view() , name='vehicle-detail'), ] urlpatterns += staticfiles_urlpatterns() Since i'm passing the vehicle primary key in the path, is there any way for me to filter the posts based on that key and pass it … -
Unexpected Keyword argument using formset_factory
I'm working on a project in which a teacher can add marks to his students, I want to use formset_factory so the teacher can add many marks at the same time, but I want a teacher to see only his students, and not the students who are not in his class. I got it when using a single form, but when I try to use the formset_factory, I get this error: init() got an unexpected keyword argument 'request' This is my working code in views: class AddNotaBlock(FormView): template_name='notas/insertar_nota.html' form_class= NotaCreateFormTeacher success_url= reverse_lazy('home') def get_form_kwargs(self): """ Passes the request object to the form class. This is necessary to only display members that belong to a given user""" kwargs = super(AddNotaBlock, self).get_form_kwargs() kwargs['request'] = self.request return kwargs in forms: class NotaCreateFormTeacher(ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(NotaCreateFormTeacher, self).__init__(*args, **kwargs) usuario=self.request.user profe=Teacher_profile.objects.get(profesor=usuario) colegio=profe.colegio self.fields['Username'].queryset = Student_profile.objects.filter( colegio=colegio) class Meta: model = Nota fields = ('Username', 'nota', 'colegio') widgets= {'colegio':HiddenInput()} formset=formset_factory(NotaCreateFormTeacher, extra=2) when I use: form_class= NotaCreateFormTeacher Everything works (but only a form is displayed) If I use: form_class=formset I get the unexpected keyword argument error: init() got an unexpected keyword argument 'request' What I'm I doing wrong? Thanks for helping. -
How can I fix a 'ModuleNotFoundError' in django python?
I am trying to create a Django python API, and when I created the first app 'authentication' with 'python manage.py startapp authentication', I got the following error while running the server: generated error I did add the app name to the 'setting.py' file : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'authentication.apps.AuthenticationConfig', 'orders.apps.OrdersConfig',] I am pretty sure that I need to specify the path, but I don't know how !!! Note that my folder is organized as follows, and the main project is named 'pizza': folder content Can anyone help me please ??? -
Django: is not a valid view function or pattern name when trying to add a url using url tag in django
i want to add a url to my project that would get the id of a video and append it to url like this http://127.0.0.1:8000/course/learn-angular/contents/?lecture=1 <a href="?lecture={{v.serial_number}}" instead of the regular django {% url '?lecture={{v.serial_number}}' %}. when i do this <a href="{% url '?lecture={{v.serial_number}}' %}"> that is when i get this error Reverse for '?lecture={{v.serial_number}}' not found. '?lecture={{v.serial_number}}' is not a valid view function or pattern name.. NOTE: when i add the url as ?lecture={{v.serial_number}} is show this error when i click on the url Page not found (404) Directory indexes are not allowed here and all these are happening i think becuase i have this line <base href="{% static '/' %}"> in my base.html where i am extending all my static files from. And if you asking why i have this line base href="{% static '/' %}">, it's becuase my static files are not loading up as usual, it keep showing a MIME type not supoorted error, refused to apply 127.0.0.1:8000/assets/css/style.css so the only way i could fix this was to add that line to my base.html. Back to the main question, what is the right way to write tihs url withot getting this error Page not found (404) … -
Django / Model with ManytoManyField gives en entry by default
Models.py class Scenes(models.Model): name = models.SlugField('Scene name', max_length=60,unique=True) description = models.TextField(blank=True) fileGltf = models.FileField(null=TRUE, blank=False, upload_to="3dfiles/") record_date = models.DateTimeField('Scene date') manager = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) prev = models.ForeignKey( 'self', related_name='previous', blank=True, null=True, on_delete=models.SET_NULL) next = models.ManyToManyField( 'self', blank=True, ) Views.py (extract) if form.is_valid(): nextSceneSlug=form.cleaned_data.get('name') scenes=form.save(commit=False) scenes.manager = request.user scenes.record_date = now scenes.prev = ScenePrevious form.save() When I record a new entry with the models.py, there is a default value for this next field/ (World is the scene origine) But when I add it with the admin panel, there is not. How can I do it in my views.py so it leaves a blank field ? -
How can i display count of each column in django
Display I would like to count the number of students for each subjects but currently it only displays the number of students for one subject. it only counts the number of student for one subject but i would like to count the number of students in each subject views.py class SubjectView(TemplateView): template_name='subjects.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) username=self.request.user.id #filter subject taught by lecturer classdets=ClassDetail.objects.all().filter(teacher=username).values_list('subject_id') print(classdets) #filters all subjects from the class details subj=Subject.objects.filter(id__in=classdets) print(subj) #counts number of students subjID=Subject.objects.values('id') num_student=ClassDetail.objects.filter(id__in=subjID).count print(num_student) context['subjects'] = subj context['no_students'] = num_student return context template {% for subject in subjects %} <tbody class="list" style="text-transform: capitalize"> <tr> <th scope="row"> <div class="media align-items-center"> <a href="#" class="avatar rounded-circle mr-3"> {% if subject.thumbnail %} <img alt="Logo" src="{{subject.thumbnail.url}}" /> {% endif %} </a> <div class="media-body"> <span class="name mb-0 text-sm">{{subject}}</span> </div> </div> </th> <td class="budget">{{subject.code}}</td> <td> <div class="d-flex align-items-center"> <span class="completion mr-2">{{no_students}}</span> </div> </td> <td> {% comment %} <div class="d-flex align-items-center"> <span class="completion mr-2">{{attendace_code}}</span> </div> {% endcomment %} </td> </tr> </tbody> {% endfor %} {% endif %} -
server returns list of tuples to an ajax request but back in the html I need to work on it and html(data) doesn't give a proper structure
I manage to send the ajax request to the server, and the server replies with a list of tuples or it could be a dictionary too, but back in the html that sent the request, this list or dict gets sort of turned into a string and I can't iterate or work on it. This is because of the html(data), but I don't know any other variant other than text(data) but that doesn't solve the problem. So, once I have sent that list or dict, how can I work on it (like doing iterations) I am using DJANGO. I simplify the code because this is what matters, suppose I already have a dictionary that I turn into a list: SERVER (VIEW FUNCTION) RETURNS: dictionary = { "key1": "value1", "key2": "value2" } lista = list(dictionary.items()) return HttpResponse(lista) Then back in the html code that sent the request, this results don't keep the nature of the list, but seems like a string HTML PAGE: ... .. datatype:'html' }).done(function(data) { $("#received_answer").html(data); }); // closing ajax group console.log(value); }); // closing the click function });// closing document ready </script> I get this: ('key1', 'value1')('key2', 'value2') -
Is it safe to put .env file on AWS elastic beanstalk
I am fairly new to web app development. I am developing a web app using react+django. I am hosting django on AWS elastic beanstalk. My question is: is it save to put .env(contains important secret keys) elastic beanstalk? Can people read or download it once they have my elastic beanstalk url? -
remote rejected main -> main (pre-receive hook declined) Heroku
I'm trying to deploy my Django app on Heroku and when I do the command "git push heroku main" it seems to load successfully but I get this error. $ git push heroku main Enumerating objects: 834, done. Counting objects: 100% (834/834), done. Delta compression using up to 4 threads Compressing objects: 100% (736/736), done. Writing objects: 100% (834/834), 12.68 MiB | 394.00 KiB/s, done. Total 834 (delta 479), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: decd3fcfff0786fdab8daa8569c30886446ee4aa remote: ! remote: ! We have detected that you have triggered a build from source code with version decd3fcfff0786fdab8daa8569c30886446ee4aa remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are … -
how to filter a model in a listview
I have a page that displays a list of interviewers and some important info about each user. One of the things that I want it to show is the number of users who have been interviewed by that specific interviewer. I wrote a view like this: class ManagerUsers(ListView): model = User template_name = 'reg/manager-users.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['scientific_interviewers'] = User.objects.filter(role='theory_interviewer').all() context['interviewed_number'] = len(ScientificInfo.objects.filter(user__role='applicant', is_approved=True, interviewer=?????)) the interviewer field should be equal to that object's user but I don't know what to do exactly. the output should be something like this: object 1 : user's name, user's other info, user's interviewed_number .... -
Iterate over CSV rows using pandas in a faster way
I'm trying to read a CSV file through file upload from html template, and iterating over the rows and creating model object. views.py @login_required def uploadStudents1(request): if request.method == 'POST': uploaded_file = request.FILES['document'] ext = os.path.splitext(uploaded_file.name)[-1].lower() if ext == '.csv': data_file = pd.read_csv( uploaded_file, parse_dates=['date_of_birth']) data_file.fillna('-', inplace=True) for _, row in data_file.iterrows(): Sem1Students.objects.create( fname=row['first_name'], lname=row['last_name'], reg_no=row['reg_no'], gender=row['gender'], birth_date=row['date_of_birth'], ) messages.success(request, 'Uploaded student details successfully!') return redirect('/students') else: messages.error(request, "Invalid file type. Please upload again.") return render(request, 'students/upload1.html') return render(request, "students/upload/upload1.html") However this process is really slow, it takes like 5-6 seconds to read and create 74 records. Is there any better way to do this, i.e make the process faster? -
Many to many relationships-django
I want to build a student portal with a admin page and a client page with django. Every Student should be enrolled in classes and they should have a grade for that class. This is my models.py class Course(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=50) courses = models.ManyToManyField(Course, through='courseInfo') def __str__(self): return self.name class courseInfo(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) grade = models.IntegerField() In the template I want to show the classes the students are enrolled in and the grades for those classes. Eventually I am going to set up a dynamic template syestem Here is my views.py from django.shortcuts import render from main.models import Course, courseInfo, Student def home(request): student_id = 1 context = { 'student': Student.objects.get(id=student_id), 'courses': courseInfo.objects.all().student_set.all } return render(request, 'facultyUi/student.html', context) and here is my template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {% for course in courses %} {{ course.grade }} {% endfor %} </body> </html> I cant find any sulution so if anyone can show me what to do here I would very much apreciate it. Thank you. -
searchVector does not show errors but return empty post
i'm trying to add search bar in my django application using searchVector instead of showing the post of my model it return empty post in dashboard template. I'm using heroku postgres. i added this in to my INSTALLED_APPS 'django.contrib.postgres' the model: class Photo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.CharField(max_length=30,null=True, blank=False) image = CloudinaryField(blank=False, null=False) description = models.TextField(null=True) date_added = models.DateTimeField(auto_now_add=True) phone = models.CharField(max_length=12, null=False, blank=False) price = models.CharField(max_length=30,blank=False) location = models.CharField(max_length=20, blank=False) def __str__(self): return str(self.category) the dashboard template: <div class="container"> <div class="row justify-content-center"> <form action="" method="get"> <input name="q" class="form-control me-2" type="search" placeholder="Search" aria- label="Search"> <br> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> <br> <div class="container"> <div class="row justify-content-center"> {% for photo in photos reversed %} <div class="col-md-4"> <div class="card my-2"> <img class="image-thumbail" src="{{photo.image.url}}" alt="Card image cap"> <div class="card-body"> <h2 style="color: yellowgreen; font-family: Arial, Helvetica, sans-serif;"> {{photo.user.username.upper}} </h2> <br> <h3>{{photo.category}}</h3> <h4>{{photo.price}}</h4> </div> <a href="{% url 'Photo-view' photo.id %}" class="btn btn-warning btn- sm m-1">Buy Now</a> </div> </div> {% empty %} <h3>No Files...</h3> {% endfor %} </div> </div> the view: def dashboard(request): q = request.GET.get('q') if q: photos = Photo.objects.filter(category__search=q) else: photos = None photos = Photo.objects.all() context = {'photos': photos} return render(request, 'dashboard.html', {'photos': photos} ) -
How do I restart my backend server in ec2 instance using github actions
Pushed the code on master branch of git, the code inside ec2 is getting updated accordingly but now I need to restart my server how do I achieve it using github actions Here is my github workflow on: push: branches: [ master ] jobs: deploy: name: Deploying on EC2 instance runs-on: ubuntu-latest steps: - name: Checking the files uses: actions/checkout@v2 - name: Deploying to the Demo Server uses: easingthemes/ssh-deploy@main env: SSH_PRIVATE_KEY: ${{secrets.EC2_SSH_KEY}} REMOTE_HOST: ${{secrets.HOST_DNS}} REMOTE_USER: ${{secrets.USER}} TARGET: ${{secrets.TARGET_DIR}} -
Django display a dynamic json file content in template
I have a json file on Django server The file content is dynamically changing I don't want to store the json data as Django model in database My question is: is there a techinically low cost and efficient way to display the json content in Django template as a frontend webpage ? All I need is display the json data in Django app web page -
insert to the table inside loop or bulk insert with django
i need to insert all products in the Cart table to the table called (OrderItem), I have used this code: neworder.save() new_order_items = Cart.objects.filter(user=request.user) for item in new_order_items: OrderItem.objects.create( order=neworder, product=item.product, price=item.product.selling_price, quantity=item.product_quantity ) # decrease the product quantity from table order_product = Product.objects.filter(id=item.product_id).first() order_product.quantity = order_product.quantity - item.product_quantity order_product.save() this code above only inserted the first product from the cart inside the Item_orders table? Although I have used the loop? Thanks -
matching query does not exist Error in Django (OneToOneField)
Please help me I don't know what I am doing wrong I am getting an error Available_time matching query does not exist. I use here OneToOneField from the Available_time database from Sunday to Saturday. I don't understand why this error is showing. class Available_time(models.Model): timezone = models.TimeField(auto_now=False, auto_now_add=False) nickname = models.CharField(max_length=30, default='IST_time') def __str__(self): return str(self.nickname) class RMDatabase(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) date_at = models.DateTimeField(auto_now=True) country= models.CharField(max_length=100, blank=True) province = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=100, blank=True) contact = models.CharField(max_length=100, blank=True) countryCode = models.CharField(max_length=100, blank=True) motherTongue = models.CharField(max_length=100, blank=True) secondSpokenLang = models.CharField(max_length=100, blank=True) secondSpokenLangReason = models.CharField(max_length=100, blank=True) interstedIn = models.CharField(max_length=100, blank=True) skillLevel = models.CharField(max_length=100, blank=True) qualification = models.CharField(max_length=100, blank=True) qualificationAwardedBy = models.CharField(max_length=100, blank=True) qualificationFile= models.FileField(upload_to='folder/') videolink = models.CharField(max_length=100, blank=True) preferredDayTime = models.CharField(max_length=100, blank=True) sunday= models.ManyToManyField(Available_time,blank=True, related_name='sunday') monday = models.ManyToManyField(Available_time, blank=True,related_name='monday') tuesday= models.ManyToManyField(Available_time,blank=True, related_name='tuesday') wednesday = models.ManyToManyField(Available_time, blank=True,related_name='wednesday') thrusday= models.ManyToManyField(Available_time,blank=True, related_name='thrusday') friday = models.ManyToManyField(Available_time, blank=True,related_name='friday') saturday = models.ManyToManyField(Available_time,blank=True, related_name='saturday') def __str__(self): return self.motherTongue **My view.py here I simple takin input from the user and save the database. the problem I facing from **if request.POST.get('sunday-evening'): to till end if conditions. if remove those lines then working fine. def MNFRM(request): x= RMDatabase() # if request.user.is_active: # if x.objects.filter(user_id=request.user).exists(): # return render(request, 'relationshipmanager/userexists.html') if request.method … -
django-tinymce changes internal urls
tinymce to manage my contents. it's ok, works but there is a small thing that i a curious to know is that why tinymce changes urls by it's own. for example: i put a link and using url like /post/post1 but whenever i check my url, tinymce makes it like: ../../../../../post/post1 however, it's ok and does not break my link, but that feels bad to see! this also happens for images Django:3.2.12 django-tinymce: 3.4.0 tinymce (by it's own): TinyMCE 5.10.1 -
django date input format is not interpreted properly
I am trying to setup a Model and a corresponding ModelForm with django containing a DateField/Input. from django.db import models class MyModel(models.Model): myDate = models.DateField() from django import forms class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = "__all__" widgets = { 'myDate': forms.DateInput(format=("%d/%m/%Y")) } But sadly, when I enter a date in the form that results out of MyModelForm, the day and the month get exchanged. E.g. 1/2/22 will result in January 2nd 2022 instead of feburary 1st 2022. What else do I need to do, so the date gets interpreted properly? -
WARNING: The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8)
WARNING: The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested docker: Error response from daemon: could not select device driver "" with capabilities: [[gpu]]. I am facing this error on mac while trying to run this command docker run --rm --gpus all -v static_volume:/home/app/staticfiles/ -v media_volume:/app/uploaded_videos/ --name=deepfakeapplication abhijitjadhav1998/deefake-detection-20framemodel How to solve this error? -
I get an error when I install the SWITIFY package, does anyone know what it means?
when I install the package sweetify, I get the following error Does anyone know what the reason is? I went through all the steps that were in the main dock Traceback (most recent call last): File "C:\Program Files\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Program Files\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\django\apps\config.py", line 228, in create import_module(entry) File "C:\Program Files\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\sweetify\__init__.py", line 1, in <module> from .sweetify import * File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\sweetify\sweetify.py", line 5, in <module> from .encoder import LazyEncoder File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\sweetify\encoder.py", line 2, in <module> from django.utils.encoding import force_text ImportError: cannot import name … -
Fields of Nested serializers
In my nested serializer i want to show only movie name and exclude the other fields [ { "id": 2, "watchlist": [ { "id": 3, "platform": "Netflix", "title": "Martian", "storyline": "A lost astronaut of Mars survived", "average_rating": 4.1, "total_rating": 2, "active": true, "created": "2022-04-05T05:37:35.902464Z" }, { "id": 4, "platform": "Netflix", "title": "Intersteller", "storyline": "Finding new home", "average_rating": 0.0, "total_rating": 0, "active": true, "created": "2022-04-06T04:52:04.665202Z" }, { "id": 5, "platform": "Netflix", "title": "Shutter Island", "storyline": "Psycopath", "average_rating": 0.0, "total_rating": 0, "active": true, "created": "2022-04-06T04:52:51.626397Z" } ], "platform": "Netflix", "about": "streaming, series and many more", "website": "https://www.netflix.com" }, ] In the above data, "watchlist" is the nested serializer data i want to show only "title" and exclude all other data I have included WatchListSerializer class as "nested" serializer in the StreamPlatformSerializer class. I want that on "title should be shown, rest other fields should be excluded from nested serializer part" below is the code... class WatchListSerializer(serializers.ModelSerializer): # reviews = ReviewSerializer(many=True, read_only=True) platform = serializers.CharField(source='platform.platform') class Meta: model = WatchList fields = '__all__' # def to_representation(self, value): # return value.title class StreamPlatformSerializer(serializers.ModelSerializer): watchlist = WatchListSerializer(many=True, read_only=True) # watchlist = serializers.CharField(source='watchlist.title') class Meta: model = StreamPlatform fields = '__all__' after removing other fields it … -
Django middleware to check ios/android app version using request header
I have an app for both Android and iOS platforms which their backend is written with Django and Django-rest-framework . I've been asked to check header of requests are sent from Android/iOS apps which includes app version number and it should respond if it needs require to update the app or not. Because I have to check this for each request before it reaches the views, I guess I have to do it with the help of a middleware. Is there any middleware already written for this? Otherwise, how can I make a custom middleware for this purpose? -
Best way to provide admin role from Django REST to ReactJS
The default django user model has a is_superuser field. I would like to use this field to conditionally render components in react, i.e. get something like this: {isAdmin && <SomeReactComponent/> } What is the best way to do this? I have authentication through JWT-Tokens (SimpleJWT). Can I somehow use them for this purpose? -
i want to make a chained drop down of my django model
please i want a chained dropdown in such away that it is only when you click on country that state will also be displayed class PollForm(forms.ModelForm): class Meta: model = PollingUnitModel fields = ['name','country', 'state', 'lga','ward'] i have been thinking of using autocomplete but i don't understand how it works from dal import autocomplete from django import forms class PollinForm(forms.ModelForm): class Meta: model = PollingUnitModel fields = ('__all__') widgets = { 'country': autocomplete.ModelSelect2(url='country-autocomplete')