Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Removing quotation marks from date in django template
Please this is what I have ['2020-03-03', 35.83483379334211] but I wanted [2020-03-03, 35.83483379334211] in my Django template so I can render it in highchart js.Any help? -
django oauth toolkit user registration
I implemented django oauth toolkit to my project so I can handle to login a user and get the access token, but I have no idea how to register a user and then create a new access token. Can anybody help me creating the registration view? client type: confidential grant type: password serializers.py class UserRegisterSerializer(serializers.ModelSerializer): confirm_password = serializers.CharField() class Meta: model = user_models.User fields = [ 'username', 'first_name', 'last_name', 'email', 'password', 'confirm_password', ] extra_kwargs = { 'confirm_password': {'read_only': True} } def validate(self, data): try: user = user_models.User.objects.filter( username=data.get('username')) if user.exists(): raise serializers.ValidationError(_('Username already exists')) except user_models.User.DoesNotExist: pass if not data.get('password') or not data.get('confirm_password'): raise serializers.ValidationError(_('Empty password')) if data.get('password') != data.get('confirm_password'): raise serializers.ValidationError(_('Password mismatch')) return data -
Can we run a python program on clicking an HTML button in a hosted Django Website?
How to run a python program on clicking a HTML button in a hosted Django Website ? I used the command 'out = run([sys.executable,'C:\python\Python38\code10.py', str(a), str(b)], shell=False , stdout=PIPE )' to run the python program before deploying the website and it worked. Can anyone suggest a way to run a python program in clicking a HTML button after hosting the Website. -
Customizing Django Forms
I have created a Model named Attendance. class Attendance(models.Model) : course_name = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) student_name = models.ManyToManyField(Student) instructor_name = models.ForeignKey(Instructor, on_delete=models.SET_NULL, null=True) published_date = models.DateTimeField(blank=True, null=True) When I pass it as a form, after selecting a particular course, I have to select students from the entire list of students enrolled for all courses. Instead I want to customize it such that only students enrolled in that particular course is displayed. I have tried using through fields for student_name field but in that case I need to pass Attendance as a Foreign Key in Student model and I need to create an instance of attendance before creating an instance of a Student. models.py: class Course(models.Model) : name = models.CharField(max_length=20, default='') course_code = models.CharField(max_length=10, default='') class Student(models.Model) : name = models.CharField(max_length=20, default='') rollno = models.CharField(max_length=10, unique=True, default='') course_name = models.ManyToManyField(Course) email_id = models.EmailField(max_length=40, default='') class Instructor(models.Model) : name = models.OneToOneField(User, on_delete=models.CASCADE) course_name = models.ForeignKey(Course, models.SET_NULL, blank=True, null=True) Also ,this is the template which contains the link to the Attendance form . I have passed the course for which attendance has to be taken as a parameter. {% block content %} Select the course for which attendance has to be taken {{ … -
I want to get the '' Alice " value from the parsed JSON in django template
I want to print Alice from this passed JSON as dict from views to the HTML file. this is my view file result = json.loads(JSON_DATA.content) return render(request, 'home.html', {'result' : result}) here is what I tried in HTML template {{ result.children[0].firstName }} this throws an error * TemplateSyntaxError* could not parse remainder '[0].firstName' from 'result.children[0].firstName' how can I access the value in HTML template ? -
raise MigrationError(selected.column) djongo.sql2mongo.MigrationError: id not getting any fixes
raise MigrationError(selected.column) djongo.sql2mongo.MigrationError: id not getting any fixes -
apply_async not work in celery and django
i have a shared_task to sending mail @shared_task def run_auto(): # Creata context for templates display top_article = Article.objects.all()[0] article1 = Article.objects.all()[1:3] article2 = Article.objects.all()[3:5] last_article = Article.objects.all()[5:8] context = { 'top_article': top_article, 'article1': article1, 'article2': article2, 'last_article': last_article, } for x,y in zip(user_list,time_list): msg_plain = render_to_string('timeset/email_templates.txt') msg_html = render_to_string('timeset/index3.html', context) subject = "NEWS" recepient = x sending.apply_async((subject,msg_plain,EMAIL_HOST_USER,recepient,msg_html), eta=y) @shared_task def sending(subject,msg_plain,EMAIL_HOST_USER, recepient, msg_html): send_mail(subject, msg_plain, EMAIL_HOST_USER, [recepient], html_message=msg_html,fail_silently=False) and in the settings.py in django i schedule the run_auto task 'send_mail_at_spe_time': { 'task': 'crawldata.tasks.run_auto', 'schedule': crontab(hour=10,minute=28), } The task run_auto work when i run celery -beat and -worker but the run_auto not call apply_async in the function , how i can call the apply async to send mail -
Django LoginRequiredMixedIn doesnn't let users sign in
I am building an app that allows users to view posts. However, every time I try to log in if I do not set the LoginRequiredMixin the user will still be able to view posts after logging out. But when I set the LoginRequiredMixin everytime user puts info it keeps going back to main page and nothing happens. my home/views.py @login_required def home(request): posts = Post.objects.all() context = {'posts':posts} return render(request, 'home/home.html', context) class PostListView(ListView): model = Post template_name = 'home/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] my home/urls.py: path('',views.PostListView.as_view(), name='home'), my main/urls.py urlpatterns=[ path('signup/',views.signup,name='signup'), path('signin/',views.user_login, name='user_login'), path('signout/', views.user_logout, name='user_logout'), path('',views.main_page,name='main_page'), path('edit/', views.edit_profile, name='edit_profile'), path('', include('django.contrib.auth.urls')), ] my main/views.py: def main_page(request): return render(request,'main/user_login.html') @login_required def user_logout(request): logout(request) return redirect('main:main_page') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) return redirect('main:main_page') else: form = SignUpForm() return render(request, 'main/signup.html', {'form': form}) def user_login(request): if request.method == 'POST': username = request.POST.get('username', '') password = request.POST.get('password', '') user = authenticate(request, username=username, password=password) if user is not None: return redirect(reverse('home:home')) else: messages.error(request,'Sorry, the username or password you entered is not valid please try again.') return HttpResponseRedirect('/') else: form=AuthenticationForm() return render(request, 'main/user_login.html', … -
File request to open not working in Django
I am new to django-JSON-Python. Please help! the code written works perfectly fine when I run in browser, though I have left out certain parts of HTML code here(some textfields,forms etc)for better readability. It works perfectly fine in browser but when I run the HTML as part of Django project in venv it simply refuses to get the file DOC_JSON.json(already created and available in the same folder). Is there anything I need to add for XMLHttpRequest() to work in Django. It doesn't throw any error. <html lang="en" xmlns="http://www.w3.org/1999/html"> <head> <meta charset="UTF-8"> <body> <script> function myFunction() { alert("Please Fill The Mandatory Fields !"); } var xmlhttp = new XMLHttpRequest(); var file_name = "Doc_JSON.json"; xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); document.getElementById("fname").value= myObj.FirstName; document.getElementById("lname").value= myObj.LastName; document.getElementById("addr").value= myObj.Address; document.getElementById("phno").value= myObj.PhoneNumber; document.getElementById("email").value= myObj.EmailAddress; document.getElementById("ed").value= myObj.Education; document.getElementById("techskill").value= myObj.TechnicalSkillset; document.getElementById("wrkexp").value= myObj.WorkExperience; document.getElementById("Empauth").value= myObj.EmploymentAuthorization; //Validating Mandatory Fields if ((document.getElementById("fname").value == null) || (document.getElementById("fname").value == "") || (document.getElementById("lname").value == null) || (document.getElementById("lname").value == "") || (document.getElementById("addr").value == null) || (document.getElementById("addr").value == "" ) || (document.getElementById("phno").value == null) || (document.getElementById("phno").value == "" ) || (document.getElementById("email").value == null) || (document.getElementById("email").value == "") || (document.getElementById("ed").value== null) || (document.getElementById("ed").value=="") || (document.getElementById("techskill") == … -
Django / Python broken imports
I'm having several problems when trying to import modules across the app and project settings. This is my directory tree, 2 levels deep ``` ├── README.md ├── WAD2 │ ├── __init__.py │ ├── __pycache__ │ ├── sc.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── WAD2app │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── filters.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py ├── requirements.txt └── templates └── wad2App ``` I tried to import two variables fromsc.py into settings.py and the module imports fine. I say this because when I do print out sys.modules.keys() the following is present 'WAD2.sc' When trying to access the variables via sc.x I get a NameError stating that sc is not defined, and I can only access the variables if I import them explicitly one by one i.e from .sc import x as y Why is this happening? Also, why is it that any imports in WAD2app must be imported from .moduleName only. I have a separate project with the very same structure and I'm able to use appName.moduleName -
Django Prefetch across multiples tables
I know there are a lot of prefetch question in Stackoverflow, but I think my case is a little "weird". So I have 3 Tables with FK. So each Reservation has a Shift and a Shift has a Nurse. What I'm trying to do is a Queryset where I get the Reservation.family_name field through Nurse.Shift.Reservation but using prefetch to not hit duplicated queries. Nurse-->Shift-->Reservation Nurse.objects.prefetch_related(Prefetch('shift_set', queryset=Shift.objects.filter( start__range=dates_range).order_by('reservation_id').distinct('reservation_id')), Prefetch('shift_set__reservation', to_attr='family_name')) What I'm trying to accomplish with this Query is get the family_name in a to_attr='family_name'. I'm using distinct because we filter 10 days from today to future, so we have some reservation duplicated and I just want the family name that are 10 days on the range. Any help will be appreciated. -
Django tests are not running on a test database
After running tests where I am creating rows in the database, I noticed that the current database is used instead of a test database like I think is the default behavior of django. Unfortunately, I haven't been able to figure out how to fix this behavior. This is currently in the settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": os.environ["POSTGRES_NAME"], "USER": os.environ["POSTGRES_USER"], "PASSWORD": os.environ["POSTGRES_PASSWORD"], "HOST": os.environ["POSTGRES_HOST"], "PORT": os.environ["POSTGRES_PORT"], } } but when adding "TEST": {"NAME": "test_database"}, it still seems to run on the main database. DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": os.environ["POSTGRES_NAME"], "USER": os.environ["POSTGRES_USER"], "PASSWORD": os.environ["POSTGRES_PASSWORD"], "HOST": os.environ["POSTGRES_HOST"], "PORT": os.environ["POSTGRES_PORT"], "TEST": { "NAME": "test_database", } } } How can I get it so the tests write to a fresh test database? -
Django got MySQL exception 2014: Commands out of sync; you can't run this command now
A web application of Django on RHEL7, Gunicorn service got a MySQL exception #2014, saying "Commands out of sync; you can't run this command now". This error happens only when get one attribute element ("/api/admin/eav/attribute/24/"), and all the other elements are OK, e.g. the logs below shows "/api/admin/eav/attribute/28/" is OK. This web application has been working fine for years before, and we noticed this error only recently. The versions of Django, Python, and MySQL are pretty old now. Many thanks in advance to any suggestion on fix. I will also highly appreciate general debugging advice, on for example: how to configure Django to print SQL query statement into log? (I suspect there is something wrong with the query, and want to manually try it out in MySQL Workbench. I'm still new to Django.) Is there anything to check on MySQL side? See details below, and let me know if you need more information. Thank you for your help. Version: Python: 2.7.5; Django: django.VERSION (1, 8, 13, 'final', 0); MySQL: '10.1.9-MariaDB' ** Logs:** [2020-03-20 18:17:37 +0000] [29744] [DEBUG] GET /api/admin/eav/attribute/ - - [20/Mar/2020:18:17:38 -0600] "GET /api/admin/eav/attribute/ HTTP/1.0" 200 56843 "https://domain.under.test/api/admin/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 … -
Django Custom User Model Encrypt Email Field
I would like to encrypt a user's email every time they sign up. The error I am getting is: "Error: EncryptedEmailField 'iexact' does not support lookups". I am using django-fernet-fields which uses the SECRET_KEY for encryption and decryption symmetrically. The user gets created and the email encryption works if I add a user from admin or the command line but when I try to add it from my form, it does not work. I am using allauth for the sign up process. Is the error above a problem with the django-fernet-fields package? Or could it be this line: email = self.normalize_email(email) How would I fix this problem? Code: https://dpaste.org/ODL3 -
How to validate multiple field uniqueness constraint on field that is not in form?
I have a model which has a uniqueness constraint across two fields (each user must have distinct profile names): class Profile(Model): user = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) name = CharField(max_length=50) description = TextField(blank=True) class Meta: constraints = [ models.UniqueConstraint(fields=['user', 'name'], name='profile_unique_user_name') ] When a user adds a new Profile, I do not want to give them access to change the user, so the form only has two fields: class ProfileForm(ModelForm): class Meta: model = Profile fields = [ 'name', 'description', ] In the view, I assign the user once the form is validated: @login_required def profile_add(request): if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): form = form.save(commit=False) form.user = request.user form.save() return redirect('home') else: form = ProfileForm() return render(request, 'profile_add.html', {'form': form}) However, the problem seems to be that the uniqueness validation doesn't happen. Presumably because the user field is not in the form. How should I change my code so that any uniqueness errors are fed back to the form's errors? My current idea is add the user field to the form, and leave it out of the template, then manually add the value in the view. Though this seems slightly hacky. Would that even work, and is there a … -
How can I login as a specific user with Django?
I would like to login to my application as a specific user without having to ask for their username or password. I use React on the frontend, and django-rest-framework-simplejwt for authentication. I know Django has a login() function, but I'm not sure how I would use this along with JWT tokens, has someone figured out how to do this? Ideally I enter a "Master Password" along with the users email to specific what user I would like to login as. -
Django login and logout not functioning as required
I have a custom user in Django and when I logout the user can still see the main page by going to the url. I do not know which part is incorrect as I am using decorators already. I ave two apps, main and home. this is my urls.py: urlpatterns = [ #Has to be included for Forgot Password funcitonality on main page path('', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), path('',views.main_page,name='main_page'), #path('profile/logout', views.user_logout, name='logout'), path('',include('main.urls'),name='main'), url(r'^home/',include(('home.urls','home'), namespace='home')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is my main/views.py def user_login(request): if request.method == 'POST': username = request.POST.get('username', '') password = request.POST.get('password', '') user = authenticate(request, username=username, password=password) if user is not None: return redirect('home:home') else: messages.error(request,'Sorry, the username or password you entered is not valid please try again.') return HttpResponseRedirect('/') else: form=AuthenticationForm() return render(request, 'main/user_login.html', {"form":form}) And my logout view in main/views.py @login_required def user_logout(request): logout(request) return HttpResponseRedirect('main/user_login.html') This is my home/views.py @login_required def home(request): posts = Post.objects.all() context = {'posts':posts} return render(request, 'home/home.html', context) class PostListView(ListView): model = Post template_name = 'home/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] My home/urls.py path('',views.PostListView.as_view(), name='home'), I am also facing an issue that I have to click the login button twice otherwise it … -
Inability to Toggle a Sidebar Using JS
I've all my CSS and Javascript inside my HTML file on Django which looks as follows: <!doctype html> <html lang="en"> <head> <title>Dashboard</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script> function toggleSidebar(){ document.getElementsByClassName("sidebar"); } </script> <style type="text/css"> .toggle-btn { position:absolute; left:180px; top:70px } .toggle-btn span { display:block; width:30px; height:5px; background:#000000; margin: 5px 0px; } .sidebar { height:100%; width:160px; position: fixed; z-index:1; top:0; let:0; background-color:#111; overflow-x: hidden; padding-top:70px; } .sidebar.active { left:0px } .sidebar a { padding:6px 8px 6px 16px; text-decoration: none; font-size:18px; color: #818181; display:block; } .sidebar a:hover { color:#ffffff; } </style> </head> <body> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <div class="toggle-btn"> <span></span> <span></span> <span></span> </div> <div class="sidebar"> <a href="/categories">Categories</a> <a href="#">Test 1</a> <a href="#">Test 2</a> <a href="#">Test 3</a> <a href="#">Test 4</a> </div> </body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="#">Home.com</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> <a class="nav-item … -
Why does my django view function never return even though all code executes?
Ok this is a long shot but I am hoping someone, somewhere has experienced this. When executing a django query that requires a long list of ids to be used, my backend function never returns. I have to cast these ids as a list because I'm using ids from one database to get at data in another. The ENTIRETY of my function executes, including a print statement right before it's supposed to return but IT NEVER RETURNS. And it grinds my local environment to a halt. I cannot make any other requests or load any other pages while it's spinning. Even if I simplify the code so that I'm only returning a string saying 'returning' the return part of my function never fires. Here is some sample code, and just know that this crashes out on me (i.e. never returns if the list of ids is longer than, say 6,000). @action(detail=False, methods=['post',]) def view_function(request): profiles = Profile.objects.filter(some_filter).values_list('id', flat=True) print('i got the profiles') the_data_i_need = Profile.objects.using('different_db').filter(profile_id__in=list(profiles)) print('i got the data i need') print('returning') return response.Response({ 'success': 'success!' }) For a small queryset (less than 6000), this executes flawlessly. In the case of a large queryset (over ~6000) ALL of my print … -
Django model update based on json url request and unique values
I made a method to request a json from a url, get some values from and after this populate my objectidServer field from my ImagemServer() Django model. The main purpose is to populate new fields every time this json update. So for example: If someone for any reason delete a a value from this the field the method will request and populate the field again, based on the objectidServer value (if the same value exists do nothing, if not, create). Same to get new values and populate new fields every json update. models.py class ImagemServer(models.Model): objectidServer = models.CharField(max_length=255, null=True, blank=True) views.py def GIS(request): response = requests.get('url') geodata = response.json() id_obj = [(data['attributes']['OBJECTID']) for data in geodata['features']] try: for lista in id_obj: ImagemServer.objects.get(objectidServer=lista) return HttpResponse('OK') except ImagemServer.DoesNotExist: for lista2 in id_obj: imagemServer_list = ImagemServer() obj = ImagemServer(objectidServer=lista2) #print(lista2) #print(imagemServer_list.objectidServer) if imagemServer_list.objectidServer != lista2: for lista3 in id_obj: print(lista3) obj = None obj = ImagemServer() obj.objectidServer = lista3 obj.save() return HttpResponse("UPDATED") else: return HttpResponse("OK") The script works well and I can populate all the fields, but I got a problem when I delete any field: when I request the json again the method not check if values exists and populate everything again, … -
Django | Create table raw query execution with query param
Can please somebody tell me whats wrong about my Syntax? I try since 2 days to get a decent answer on this matter, but wether people just give me minus points or refer me to to the Django docs I already read https://docs.djangoproject.com/en/3.0/topics/db/sql/ tablename = '2020-10-table' v_col = ["userID int(11)", "TID varchar(128)", "CID varchar(128)", "SID varchar(255)", "Timestamp bigint(20)", "LX int(10)", "LocY int(10)", "Width int(10)", "Height int(10)", "Tag varchar(512)"] connection.execute("""CREATE TABLE IF NOT EXISTS `%s` %s""", [tablename, '( '+str(', '.join(v_col))+' )']) I keep receiving this: MySQLdb._exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''( userID int(11), TI ...... Can anyone please point out my issue? -
How can do django framework to back-end and react js to front-end
based application using django framework for back-end and I like to code react js for front-end is it possible? -
Why is my database table empty after Heroku deployment?
I have a django app that runs perfectly well on my local server. Unfortunately, when I deploy it onto Heroku, the behaviour doesn't work as expected. I can see that it's a database related issue as my dropdowns which are supposed to load a list of values from my database are empty on production. I have checked on Heroku in the 'Ressources' section of my application and there is a database; it also contains all my project tables (django default tables + my main table). All the django default tables are properly populated (I compared them with my local postgres tables and it matched). Unfortunately, my main table is empty on Heroku, whereas it is populated as expected locally. I really don't understand what has gone wrong, especially considering that the table itself has been recognized, yet it is empty. I've applied the command 'heroku run python manage.py migrate' but it didn't fix the issue. Has anyone faced a similar issue? Not sure if the code would help here, but if you need some specific bits, please let me know. Thanks! -
Best practice to pass attribute from ModelForm.clean() to Model.save()
class MyModel(models.Model): def save(self, *args, **kwargs): super().save(*args, **kwargs) if getattr(self, 'my_attr', False): # do things class MyForm(forms.ModelForm): def clean(self) cleaned_data = super().clean() if self.has_changed(): self.instance.my_attr = self.get_the_needed_info() return cleaned_data class Meta: model = MyModel fields ='__all__' @admin.register(MyModel) class MyAdmin(admin.ModelAdmin) form = MyForm During MyModel.save(), I need to check for a condition that is evaluated in ModelForm.clean(). During clean(), I assign the attribute my_attr to self.instance. It is working it seems to be thread-safe (within an atomic transaction). Is there any reason I miss, that urges a refactoring? -
how to trigger push notification for specific endpoint? in fcm_django lib
I used fcm_django and want to push notification on specific endpoint to be trigged I already test it from python shell all works, but how to add it to my endpoint? wanna see best practice! if I use this one it will pushed notifications? Thanks for your time! @action(detail=True, methods=['post']) def add_server(self, request, pk=None): booking = self.get_object() booking.add_server(request.user) device = FCMDevice() device.send_message() return Response("Server added")