Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: filter by Date and time
I want to filter the queryset by date and time... I want to return all queryset that grater than or equal todays dateTime I try to do this and nothings happening self.request.user.date_created.filter(date_time__date__gt=datetime.datetime.now()) -
Getting manager of manager of an employee using django-auth-ldap
i need some help if someone run into the same problem i am having right now, as i have been asked to add support a login using Active Directory, i have managed to succeed the login process and the models creations of users, and now i want to populate some details from AD into the app database, i want to get the manager of manager of an employee, as i have been searching i found that the team lead N+1 field is named "manager" on ad so i have queried this using this command AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "Name", "email": "mail", "employee_manager": "manager", "employee_office": "physicalDeliveryOfficeName", "employee_cost_center": "extensionAttribute8" } The problem here is i got this in my database CN=TeamLeadName,OU=Users,OU=Tunis,OU=Care,OU=Corporate,DC=domain,DC=net so know i don't have any idea how to get only the name of the team lead and not the rest and from there how i can get the team of the team lead or in other word the initial employee manager. Any help will be so much appreciated. -
Django STATIC_URL on requests
I have this Django project (https://github.com/chakki-works/doccano) that I'm trying to deploy using Apache + mod_wsgi. I set up my .conf file to work as a Daemon proccess where application is served under an alias (/doccano) path: Alias /media/ /var/www/doccano/media/ Alias /static/ /var/www/doccano/app/staticfiles/ WSGIDaemonProcess doccano user=apache group=apache python-home=/var/www/doccano/env WSGIProcessGroup doccano WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias /doccano /var/www/doccano/app/app/wsgi.py The application was doing fine while static files were not being served as I mapped /doccano alias: The Alias /static/ /var/www/doccano/app/staticfiles/ fixed static files problem. But I still want to serve other applications in this server, so mapping /static/ may not be a good idea. So I want to know what is the best approach for this situation. I was trying to add /doccano/ at the beginning of the static requests url setting STATIC_URL=/doccano/static/ but I think this property is not for doing this type of setting. -
http to https django project in nginx and port masking
I have server running in ngnix with host name https://mywebiste.com i have installed django project in folder(/home/mine/django_project/miniweb) and running in port 8090 by python manage.py runserver 0.0.0.0:8090 my service is working with http://mywebiste.com:8090 In my settings.py file i have added SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') How do i make it as https://mywebiste.com/miniweb i have 2 files ssl and default in /etc/ngnix/sites-enabled(i have proper ssl certificate and key file) and /etc/ngnix i have folders conf.g and other files. gone through few post and materials. added below code in ssl file and even tried in default file also but its not working. server { listen 80; server_name mywebiste.com:8090; rewrite ^ https://mywebiste.com/miniweb$request_uri? permanent; } server { listen 443; ssl on; ssl_certificate /etc/nginx/ssl/xxxxxxxxx.pem; ssl_certificate_key /etc/nginx/ssl/xxxxxxxxx.key; server_name mywebiste.com:8090; location / { uwsgi_pass mywebiste:8090; include uwsgi_params; } } Please i am very new to this. can anyone guide what to do here please. -
Django. Como consultar dos tablas en un mismo formulario?
Estoy haciendo una pequeña app para el control de escrutinio de las elecciones en el cual cargo las mesas donde se van a votas y los partidos politicos participantes. Para cargar la votacion necesito seleccionar la mesa y que me muestre la lista de los partidos politicos con el numero de lista y el nombre del partido. Estoy utilizando Dajngo 2.2 para el desarrollo de la app web. el archivo models.py de la app mesa es: class Mesa(models.Model): num = models.IntegerField(primary_key=True) escuela = models.CharField(max_length=100) el archivo models.py de la app partido es: class Partido(models.Model): lista = models.CharField(max_length=5, primary_key=True) nombre = models.CharField(max_length=100) pres = models.BooleanField() dip = models.BooleanField() Como puedo hacer para que me muestre lo que necesito? Muchas gracias!!! -
Django - split view.py to small files
I have big views.py where I have class based views and def views. It is possible to split it somehow to seal small files, so, for example, in one file I have only class based views, and in other file - functions -
submitting a form with multiple different buttons
I am trying to make a form that has three different submit buttons or inputs. I read that to do that I have to provide a name and a value attribute to the button. I already tried the button tag and input tag. But when I try to submit them and then print the POST request from within Django. nothing is printed. Only the csrf token is included with the POST request. This is the code I am trying. It only works when there is an input tag other than the submit type. but then I can't seperate them because any button will post everything in the form. THanks! <input type="submit" name="first_choice" value="first" class="btn btn-danger" > <input type="submit" name="first_choice" value="second" class="btn btn-info" > <input type="submit" name="first_choice" value="third" class="btn btn-success" > -
having the full field object instead of it's ID in django model
with these two models TblPhoto class TblPhoto(models.Model): #path = models.CharField(max_length=256) type = models.ForeignKey('TblPhotoTypes', models.DO_NOTHING, blank=True, null=True) path = models.ImageField(upload_to='images') def __str__(self): return str(self.id) class Meta: managed = False db_table = 'tbl_photo' verbose_name = "Photo" verbose_name_plural = "Photos" and TblCustomer class TblCustomer(models.Model): name = models.CharField(max_length=32) email = models.CharField(max_length=32) password = models.CharField(max_length=32) token = models.CharField(max_length=64, blank=True, null=True) firebase_token = models.CharField(max_length=64, blank=True, null=True) registration_date = models.IntegerField(blank=True, null=True) last_login_date = models.IntegerField(blank=True, null=True) about = models.TextField(max_length=128, blank=True, null=True) active = models.BooleanField(blank=True, null=True) photo = models.ForeignKey(TblPhoto, models.DO_NOTHING) def __str__(self): return str(self.id)+' : '+self.name class Meta: managed = False db_table = 'tbl_customer' verbose_name = "Customer" verbose_name_plural = "Customers" the api response is... { "response_status": { "code": 200, "internalMessage": "", "message": "" }, "user": { "id": 1, "name": "deya", "email": "3denator@gmail.com", "password": "e10adc3949ba59abbe56e057f20f883e", "token": null, "firebase_token": null, "registration_date": null, "last_login_date": null, "about": "hello, i'm Deya !", "active": true, "photo_id": 4 } } notice the field photo_id, how can I alter the TblCustomer model to show the photo object instead of the photo id? Disclaimer : I can do this easily out of the model, but I want it to be in the model class. -
Nested get or create functionality - DRF
There have been some posts about nested create functionalities however none seem to have helped me out. You can see here what my json post request looks like: { "games": [ { "company": { "name": "Google", "website": "https://google.com", "trustedpilot": "5" }, "genres": [], "formats": [], "platforms": [], "title": "Call of duty modern warfare", "cover": "https::cover.jpg", "link": "https://google.com", "prev_price": "60.00", "price": "40.00" } ], "company": { "name": "Google", "website": "https://google.com", "trustedpilot": "5" }, "name": "Bundle name", "prev_price": "50.00", "price": "20.00" } The game serializer seems the work fine when creating a single game: class GameSerializer(serializers.HyperlinkedModelSerializer): company = CompanySerializer(many=False) genres = GenreSerializer(many=True) formats = FormatSerializer(many=True) platforms = PlatformSerializer(many=True) class Meta: model = Game fields = '__all__' def create(self, validated_data): # Many to one company_data = validated_data.pop('company') # Many to Many genres_data = validated_data.pop('genres') formats_data = validated_data.pop('formats') platforms_data = validated_data.pop('platforms') # Company company, created = Company.objects.get_or_create(**company_data) # Get the game or created a new one if it doesn't exist yet game, created = Game.objects.get_or_create(**validated_data, company=company) # Platform for platform_data in platforms_data: platform, create = Platform.objects.get_or_create(**platform_data) game.platforms.add(platform) # Format for format_data in formats_data: format, create = Format.objects.get_or_create(**format_data) game.formats.add(format) # Genre for genre_data in genres_data: genre, create = Genre.objects.get_or_create(**genre_data) game.genres.add(genre) return game This is the … -
Passing List as Parameter in Python Requests
I generate a list of IDs, x = [1,2,3] from a set of records pulled from an API request. I then take this list and pass it as a parameter in a second API request which returns a set of records, y = [1,2] which are related to the first by foreign key. The problem I am having is that I need to return or assign a value for each ID in the list, as not every ID in the list has a corresponding record. Therefore, my two lists differ in size when I need them to be 1:1 for when I iterate through the data. How can I return some default value for when the query is false or how can I assign a value for when there is no corresponding record for a given ID? So as, x = [1,2,3] and y = 1,2,3] or x == y. Please let me know if any further information is needed. views.py def do_something(self, request): try: r = requests.get( self.URL + 'domain/endpoint in (' + request + ')', headers=self.Header) r.raise_for_status() except: print(r.text) raise return r.json() y = obj.do_something(x) -
Ubuntu server with Postgres - django.db.utils.OperationalError: fe_sendauth: no password supplied
I am deploying my Django website using Linode (using ubuntu for the server). I manage to create a virtual environment on my Linode server and push my application into it. Now, I want to test if it works, so I run on my server (not local machine): python manage.py runserver 0.0.0.0:8000 However, I get the error: django.db.utils.OperationalError: fe_sendauth: no password supplied On my localmachine, I used postgres: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'cocdb', 'USER': 'name', 'PASSWORD': '', # Yes, there is NO password 'HOST': 'localhost', 'PORT': '', } } I think the error is due to the fact that I did not create the postgres database on my Linode server. Is it correct? In order to do so, I plan to follow this guide: https://www.linode.com/docs/databases/postgresql/how-to-install-postgresql-on-ubuntu-16-04/ Access my linux server from Bash and activate my virtual enviroment sudo passwd postgres su - postgres psql -d template1 -c "ALTER USER postgres WITH PASSWORD 'newpassword';" I do not understand what 'template1' refers to createdb cocdb psql cocdb I am not sure if this is correct. What else should I do? a) Change the DATABASES in settings.py? If yes, how? b) My postgres USER in my localmachine is called name … -
How to view OpenCv in Django's Screen
Im planning to create a Web app system where i'm going to detect the vehicle's license plate no. using django and openv. The problem is, how to use django to livestream OpenCv? -
Many to Many in two directions
I have a friend that requested something that I was thinking would be simple and quick. It never turns out that way. Quick disclaimer, model design is a krux of mine. I often spend too long perfecting it only to have to rework it several times. Anyway, here is the current state of my model. For everything, it works, except when creating 'raids'. from django.db import models # Create your models here. class PlayerRole(models.Model): """ PlayerRole Model """ role = models.CharField(max_length=20) # this function will be invoked when this model object is foreign key of other model(for example Employee model.). def __str__(self): return self.role # this is a inner class which is used to define unique index columns. You can specify multiple columns in a list or tuple. class Meta: unique_together = ['role'] class PlayerClass(models.Model): """ PlayerClass Model """ name = models.CharField(max_length=100) color = models.CharField(max_length=6) # this function will be invoked when this model object is foreign key of other model(for example Employee model.). def __str__(self): return self.name # this is a inner class which is used to define unique index columns. You can specify multiple columns in a list or tuple. class Meta: unique_together = ['name'] class Player(models.Model): """ … -
When I run python manage.py migrate I'm getting a Error
when i try to run python manage.py migrate I always get a traceback error. Help me to solve this problem. I have deleted a model called Program. Operations to perform: Apply all migrations: admin, auth, ca, contenttypes, courses, index, languages, online_courses, sessions Running migrations: Applying courses.0007_auto_20190816_2209...Traceback (most recent call last): File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: new__courses_courses.program_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) return executor(sql, params, many, context) File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: new__courses_courses.program_id -
How to interact with client side without finding any request from client
Scenario; 1. Creating QRCODE and displaying it to the client. 2. Client scanning the code from the browser by using its mobile and responding to our server by using callback uri. 3. We find the response from the qr scanner application. 4. But how we can interact with the client side on the behalf of this response, actually client is not requesting directly. I am waiting for your kind response, Thanks. -
Django App using Celery Beat + Worker as Windows Service
I created a Django app that runs tasks using Celery as specified in tasks.py. Currently, I'm running it with 2 command prompts windows, one for beat and one for worker with the following commands as per this post: celery -A main worker -l info -P gevent celery -A main beat -l info I read about supervisor but that is for Linux. I have to make this work on a Windows server. I looked at several posts and many of them are old articles with deprecated libraries. This is the most current one I found. I'm following the instructions, but I don't understand where the beat and worker commands go. How does it know to go to my tasks.py and run? I would have commented to the actual post, but I'm not allowed to post because I have less than 50 reputation. This is the script from the post with my path and directory: '''Usage : python celery_service.py install (start / stop / remove) Run celery as a Windows service''' import win32service import win32serviceutil import win32api import win32con import win32event import subprocess import sys import os import shlex import logging import time # The directory for celery.log and celery_service.log # Default: … -
Django crispy-forms how to create a 2 separated column form
I dug into the crispy forms Layout documentation as well as some stackOverflow threads, trying to create a 2 separated column form. I created this layout on a forms.Form: class BasicForm(forms.Form): label_1 = forms.CharField(label='label1') label_2 = forms.CharField(label='label2') label_3 = forms.CharField(label='label3',help_text='This is help text', widget=forms.Textarea) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Field('label_1', wrapper_class='col-md-6', css_class='row-fluid'), ), Row( Field('label_2', wrapper_class='col-md-6', css_class='row-fluid'), Field('label_3', wrapper_class='col-md-6') ) ) And what i get in the browser is: You can see that the TextArea block is not aligned to top. I wanted it to be near label1. When i try this layout: self.helper.layout = Layout( Row( Field('label_1', wrapper_class='col-md-6', css_class='row-fluid'), Field('label_3', wrapper_class='col-md-6') ), Row( Field('label_2', wrapper_class='col-md-6', css_class='row-fluid') ) ) Putting the textarea on the first row, i get this: Which also does not look OK. I wanted the label2 block to be right under label1, and not under the TextArea -
How to render a bound Django model form as HTML-safe?
I am trying to return a bound form modified to insert some text and HTML into it. I have done some research and have been able to successfully insert some arbitrary text into a bound form but I haven't found any way render the injected HTML as HTML. It renders as plain text. How can I achieve my goal? Here is the code: # views.py def multi_text(request): if request.method == 'POST': data = request.POST.copy() form = MultilineForm(data=data) if form.is_valid(): cd = form.cleaned_data form.data['text'] = '<i>Hello hello</i>' return render(request, 'multi_text.html', {'form': form}) else: form = MultilineForm() return render(request, 'multi_text.html', {'form': form}) # forms.py class MultilineForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['text'].widget.attrs.update({'class': 'form-control'}, verbose_name='Text', placeholder='Type your text here...') self.data['text'] = '...' class Meta: model = Multiline fields = ['text'] widgets = { 'text': Textarea(attrs={}), } # template.html <form method="post" action="" class="form"> {% csrf_token %} {{ form.text.as_widget }} <span class="input-group-btn"> <input type="submit" value="Check" class="form-control btn btn-primary"> </span> </form> -
How to add more columns to pivot table in many to many relations in Django?
I have 2 models united by a Many to Many relationship, in this case is Policies and Coverages so far it works fine, but I want to add another column to the pivot table since it wont work on any of the modeled tables (I want to add a IntegerField with the name 'amount' so I can store how much money are we covering for that specific coverage in that specific Insurance Police) class Policy(models.Model): """Insurance Policies Model""" number = models.CharField(max_length=25, unique=True) company = models.OneToOneField(Company, on_delete=models.CASCADE) client = models.OneToOneField(Client, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() comission = models.PositiveIntegerField() salesperson = models.ForeignKey(Salesperson, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) rif = models.CharField(max_length=50) phone = models.CharField(max_length=100) class Meta: db_table = 'policies' class Coverage(models.Model): """Coverage of the different types of policies""" name = models.CharField(max_length=55) policies = models.ManyToManyField(Policy) class Meta: db_table = 'coverages' I made the migrations and the pivot table was made without problems, but I don't know how to add another field to the pivot table -
Django model won't update using .update()
I am trying to update a record in my database using info provided by my website's front-end using Model.objects.update(**kwargs) however on running the code I get the following error: "'Record' with this Id already exists." I would have expected that using the "update" method instead of the "create" method would mean that it shouldn't matter / should be expected that there is already a record with the same ID. def find_patient(request): my_form = ExampleForm() if request.method == "POST": my_form = ExampleForm(request.POST) if my_form.is_valid(): UserInfo.objects.update(**my_form.cleaned_data) else: print(my_form.errors) context = { 'form': my_form, 'data_input': DataInput.objects, 'sections': SECTION_CHOICES } return render(request, 'example.html', context) The resulting error looks tike this: idUser info with this Id already exists. Am I misunderstanding the use case for "update" and if so, how would I go about using kwargs to update all fields for a given record in my db? -
Displaying Django templates in a VueJS template
I have the following django index page: {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/MaterialDesign-Webfont/3.8.95/css/materialdesignicons.css"> <meta charset="UTF-8"> <title>My test</title> </head> <body> <div id="app"> <h1>TEST</h1> </div> {% render_bundle 'main' %} </body> </html> This template is supposed to call my VueJS frontend, so that i can use Vue on my Django templates, this is the Vue template being called: <template> <v-app id="sandbox"> <v-navigation-drawer v-model="primaryDrawer.model" :clipped="primaryDrawer.clipped" :floating="primaryDrawer.floating" :mini-variant="primaryDrawer.mini" :permanent="primaryDrawer.type === 'permanent'" :temporary="primaryDrawer.type === 'temporary'" app overflow ><v-switch v-model="$vuetify.theme.dark" primary label="Dark" ></v-switch></v-navigation-drawer> <v-app-bar :clipped-left="primaryDrawer.clipped" app > <v-app-bar-nav-icon v-if="primaryDrawer.type !== 'permanent'" @click.stop="primaryDrawer.model = !primaryDrawer.model" ></v-app-bar-nav-icon> <v-toolbar-title>TRADIFY</v-toolbar-title> </v-app-bar> </v-app> </template> Which is just a simple Vuetify default template, really similar to this. Until now, it's alright, i can see the page but i don't see the Django part in my template. To debug it, i added that <h1> TEST </h1> to my index page, so when i open http://127.0.0.1:8000/ i should see the Vue template + the Django template. The problem is that i don't see the <h1>. I think that somehow the Vue/Vuetify components are hiding it, because if i remove everything from the Vue part, except <template></template> i will see the <h1>TEST</h1> appearing. I need to fix this … -
Django and VueJS. Response cookies are not being saved on browser
I have some trouble with cookies in Django. VueJS Frontend makes Django a POST request and in Django POST response I send a cookie and in the browser dev tools I see: Response headers But when I go to DevTools/Application/Cookies, the cookie does not appears. -
Django Methods in Model Not Updating Properly
I created some functions within my models.py in Django that tracks the users' money but for some reason, they only update once Profile is reloaded or when I add transactions. When I try to delete, it does not update until I refresh the page and when I try to search the tags, the method values completely disappear from the page. I have no idea why this happens nor what I can do to fix it. views.py def profile(request): if request.method == 'GET': return render(request, 'users/profile.html', { 'transactions': Transaction.objects.all(), 'balance':Profile.total_balance(request.user), 'income':Profile.total_income(request.user), 'expense':Profile.total_expenses(request.user)}) if request.method == 'POST': form = TransactionForm(request.POST) if form.is_valid(): tag = form.cleaned_data.get('tag') amount = form.cleaned_data.get('amount') category = form.cleaned_data.get('category') user=request.user Transaction.objects.create( user=user, tag=tag, amount=amount, category=category ).save() elif request.method == 'DELETE': id = json.loads(request.body)['id'] transaction = get_object_or_404(Transaction,id=id) transaction.delete() return HttpResponse('') return HttpResponseRedirect(reverse('profile')) def search(request): query = request.GET.get('q') if query and query!="": results = Transaction.objects.filter(Q(tag__icontains=query)) else: results = Transaction.objects.all() transactions = { 'transactions' : results, } return render(request, 'users/profile.html', transactions,{ 'balance':Profile.total_balance(request.user), 'income':Profile.total_income(request.user), 'expense':Profile.total_expenses(request.user)}) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def total_balance(User): transaction_list = Transaction.objects.filter(user=User) total_balance_amount = 0 for transaction in transaction_list: if transaction.category=='Income': total_balance_amount += transaction.amount elif transaction.category=='Expense': total_balance_amount -= transaction.amount return total_balance_amount def total_income(User): transaction_list = Transaction.objects.filter(user=User) total_income_amount = 0 … -
How to handle django regex url with vue.js?
I am trying to link vue.js with my Django application but having trouble with URL, I have created my app using Django rest framework,I have a two models with one to many relationship and used regex in url to link each other . I am new to vue.js and it's getting more complicated for me to find a way to connect URL to my Django app models.py: class TreatmentGiven(models.Model): id = models.AutoField(primary_key = True) patient = models.ForeignKey(Ipd,on_delete = models.CASCADE,default = None) medicine_name = models.CharField(max_length = 100,null = True) types_of_doses = models.CharField(max_length = 100,null = True) route = models.CharField(max_length = 100,null = True) number_of_days = models.IntegerField(null = True) views.py : class DischargeViewSet(viewsets.ModelViewSet): queryset = TreatmentGiven.objects.all() serializer_class = TreatmentGivenSerializer filter_backends = (filters.SearchFilter,) search_fields = ('ipd','medicine_name','types_of_doses','route','number_of_days') @login_required def discharge_detail(request,ipd_id): object = get_object_or_404(Ipd,pk=ipd_id) if request.method == "POST": formtwo = DischargeForm(request.POST) if formtwo.is_valid() : formtwo.save() return HttpResponseRedirect(reverse('dischargelist')) else: return HttpResponse(formtwo.errors.as_data()) else: formtwo = DischargeForm() return render(request, 'dischargedetails.html', {'object':object, 'form2': formtwo}) serializers.py: class TreatmentGivenSerializer(serializers.ModelSerializer): class Meta: model = TreatmentGiven fields = '__all__' routers.py: router = routers.DefaultRouter() router.register(r'^(?P<ipd_id>\d+)/dischargedetails/$', DischargeViewSet) urls.py urlpatterns = [ path('api/', include(router.urls)), re_path(r'^(?P<ipd_id>\d+)/dischargedetails/$', my_patient.discharge_detail, name='discharge_details'), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) vue.js : Vue.http.headers.common['X-CSRFToken'] = "{{ csrf_token }}"; new Vue({ el: '#starting', delimiters: ['${','}'], data: { treatmentgivens: … -
Add url to API response on serializers.Serializer
I have a django-application with the followin files models.py from datetime import datetime class Comment(object): def __init__(self, email, content, created=None): self.email = email self.content = content self.created = created or datetime.now() serializers.py from rest_framework import serializers class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() url = serializers.CharField(source='get_absolute_url', read_only=True) in views.py I now define a a ViewSet to return the serialized results. In this class I define a list of comments views.py from rest_framework import viewsets from .serializers import * from .models import Comment from rest_framework.response import Response class CommentViewSet(viewsets.ViewSet): lc = [Comment(email='jan@auto.com', content='hallo mike'), Comment(email='jan@auto.com', content='hallo jan'), Comment(email='jan@auto.com', content='hallo niklas')] def list(self, request): serializer = CommentSerializer(self.lc, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): user = self.lc[int(pk)] serializer = CommentSerializer(user) return Response(serializer.data) When I now call the api (http://127.0.0.1:8000/comments/?format=json) I get the following result [ { "email": "jan@auto.com", "content": "hallo mike", "created": "2019-08-16T16:53:56.371890Z" }, { "email": "jan@auto.com", "content": "hallo jan", "created": "2019-08-16T16:53:56.371890Z" }, { "email": "jan@auto.com", "content": "hallo niklas", "created": "2019-08-16T16:53:56.371890Z" } ] In this response I would have hoped to see a url for each dataset. The error ist probably that url = serializers.CharField(source='get_absolute_url', read_only=True) the source is undefined in the Comment class. However I have no …