Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
reset form to initial data in invalid_form and display error in Django
I have a profile form that shows email, user name and first name. user only allowed to change first name field and the others are read only, if user change HTML value in email and username then submit it, it returns error but fill the fields with invalid value entered. I tried create a new instance of form and render it but it no longer shows the error. The thing I want is to reset invalid data then display the error. forms.py class UserEditForm(forms.ModelForm): email = forms.EmailField( label='Account email (can not be changed)', max_length=200, widget=forms.TextInput( attrs={'class': 'form-control mb-3', 'placeholder': 'email', 'id': 'form-email', 'readonly': 'readonly'})) user_name = forms.CharField( label='Username', min_length=4, max_length=50, widget=forms.TextInput( attrs={'class': 'form-control mb-3', 'placeholder': 'Username', 'id': 'form-username', 'readonly': 'readonly'})) first_name = forms.CharField( label='First name', min_length=4, max_length=50, widget=forms.TextInput( attrs={'class': 'form-control mb-3', 'placeholder': 'Firstname', 'id': 'form-firstname'})) class Meta: model = UserBase fields = ('email', 'user_name', 'first_name',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['user_name'].required = True self.fields['email'].required = True def clean_user_name(self): username = self.cleaned_data['user_name'] if username != self.instance.user_name: raise forms.ValidationError('Sorry, you can not change your username') return username def clean_email(self): email = self.cleaned_data['email'] if email != self.instance.email: raise forms.ValidationError('Sorry, you can not change your email') return email views.py class ChangeUserDetail(SuccessMessageMixin, LoginRequiredMixin, FormView): … -
Testing Updateview in Django won't update an object
I'm writing tests for my views and I'm stuck with the UpdateView and the POST request. For this simple test I try just to change first_name but assertion fails. What am I doing wrong? The test: class TestEmployeesUpdateView(TestCase): def setUp(self): self.test_user = User.objects.create_user( username='test_user', email= 'testuser@test.com', password='Testing12345') self.test_employee = Employee.objects.create( first_name='Bob', last_name='Smith', user=self.test_user, position='SM', birthday=date(year=1995, month=3, day=20), hire_date=date(year=2019, month=2, day=15), address='...', ) self.client = Client() def test_updateview_post(self): self.client.force_login(user=self.test_user) response = self.client.post(reverse('employees:employee-update', kwargs={'pk': self.test_employee.pk}), {'frist_name': 'John'}) self.test_employee.refresh_from_db() self.assertEqual(self.test_employee.first_name, 'John') The view: class EmployeesUpdateView(LoginRequiredMixin, UpdateView): model = Employee template_name = 'employees/employee_details.html' form_class = EmployeeUpdateForm And the error: FAIL: test_updateview_post (employees.tests.test_views.TestEmployeesUpdateView) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/main/dev/project1/employees/tests/test_views.py", line 63, in test_updateview_post self.assertEqual(self.test_employee.first_name, 'John') AssertionError: 'Bob' != 'John' - Bob + John -
how can i customize auto generated django form?
i've created a form on django app with its builtin forms class. here is my forms.py file. # import form class from django from dataclasses import field from django import forms from .models import #MYMODEL# class myForm(forms.ModelForm): class Meta: model = #MYMODEL# fields = "__all__" and my view function in views.py def index(request): context = {} form = myForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() context['form'] = form return render(request, "index.html", context) and finally the page (index.html) that shows the form <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Kaydet"> </form> So, what i need to do is to set custom input types like text or select box since the auto-generated form includes only text inputs. -
Uboundlocal error in django on my polls app on views. Py
From django. Shortcuts import get_object_or_404, render From django.http import HttpResponse def detail(request, question_id): Question = get_object_or_404(Question, pk=Question_id) return render(request, 'polls/detail.html', {'question':question } ) Full code: In my view.py -
Django custom login form validation with AJAX
I am not that experienced writing Python/Back-end, but trying to improve. In development/localserver I am trying to validate a user's email and password in my login form... right now almost 100% of things work, for example, alert messages for mandatory inputs; however, from the Utils.py file if user "elif not object_user.allow_private_access:" validation is not working and, most importantly, validation is not checking user's password (also commented out in Utils.py). The "post" part in Views.py might have to be updated. I have included my custom Login form from Forms.py, Views.py (for Login page) and Utils.py (which does the validation and sends error messages to the front-end) and Urls.py. I did not add my AJAX because that is working well. Forms.py class UserLoginForm(forms.ModelForm): helper = FormHelper() helper.add_input(Submit('login_form_submit', numeratio_static_textLanguage['global_input_alert_maxCharacters_32'], css_class='global_component-button')) class Meta: model = CustomUser fields = ['email', 'password'] widgets = { 'email': forms.EmailInput(attrs={ 'maxlength': '256', 'style': 'text-transform: lowercase', 'id': 'input-email', 'class': 'global_component-input box'} ), 'password': forms.PasswordInput(attrs={ 'type': 'password', 'maxlength': '128', 'id': 'input-password', 'class': 'global_component-input box'} ) } def __init__(self, *args, **kwargs): super(UserLoginForm, self).__init__(*args, **kwargs) self.helper.form_action = '' self.helper.form_method = 'post' self.helper.form_id = 'login_form' self.helper.form_class = 'login_form' Views.py @csrf_exempt @anonymous_required(redirect_url='page__home') @require_http_methods(["GET", "POST"]) def view_userLogin(request, *args, **kwargs): template_name = '../frontend/templates/frontend/templates.user/template.page_login.html' form_class = UserLoginForm if … -
can't run a Django function from html template using ajax
I'm trying to run a Django function after a click event from user using Ajax inside a JS code in Django template HTML file. javascript block kml_layer.addListener('click', (kmlEvent) => { setMapOnAll(null); var clickedPoint = kmlEvent.latLng; newPoint.postMessage(clickedPoint.lat() + "," + clickedPoint.lng()) console.log("layer id is " + "{{ single_layer.id }}"); runKmOnSource("{{ single_layer.id }}", kmlEvent); //Here is where I called the ajax jquery function }); Ajax call function runKmOnSource(theID,kmlEvent,){ console.log("started ajax") $(document).ready(function () { $.ajax({ type: "POST", url: "{% url 'get_km_from_source' %}", data: { csrfmiddlewaretoken: '{{ csrf_token }}', layer_id: theID, the_element_string_id: kmlEvent.featureData.id, clicked_lat: kmlEvent.latLng.lat, clicked_lng: kmlEvent.latLng.lng }, /* Passing the text data */ success: function (response) { console.log("ajax success"); kmOnSource.postMessage(response) } }); }); } urls.py path('get_km_from_source/', get_km_from_source, name='get_km_from_source'), and finally Django/python view def get_km_from_source(request): """ A function that takes data from the ajax function parsing it then ending back the result """ print("xxxxxxxxxxxxxxxxsssssssssss started kmonsource") #This line to test if function executed layer_id = request.POST['layer_id'] the_element_string_id = request.POST['the_element_string_id'] clicked_lat = request.POST['clicked_lat'] clicked_lng = request.POST['clicked_lng'] layer_object = models.MapLayers.objects.get(id=layer_id) print(f"layer object is {layer_object}") water_element_object = None nearest_cord = None first_cord = None last_cord = None for water_element in layer_object.waterelement_set.all(): if water_element.id_string == the_element_string_id: water_element_object = water_element break for single_cord in water_element_object.cordsforwaterelement_set.all(): if nearest_cord is None: … -
How to use foreign keys in django?
I can't seem to be able to use foreign key in django. I have a rental spaces network website that offers books. I've created a "Rental" model and a "Book" model and I've created a foreignkey for book model to be attached to a rental space. In admin panel everything works as it should, but I can't get it to show on website. I want to have several books in rental space 1 and none in rental space 2. I don't know how to manage it in views.py my models : class Rental (models.Model): rental_name=models.CharField(max_length=50) rental_number=models.IntegerField(default=0) rental_adress=models.CharField(max_length=100, default='') def __str__(self): return "{} {}".format(self.id, self.rental_name) class Book(models.Model): # autor, tytul gatunek, isbn, id w wypozyczalni book_author=models.CharField(max_length=50) book_title = models.CharField(max_length=100) book_isbn= models.CharField(max_length=17, unique=True) BOOK_GENRE= ( ('SF', "Sci-Fi"), ("ROM", "Romance"), ("HIS", "Historical"), ("HOR", "Horror"), ("THR", "Thriller"), ("BIO", "Biography"), ("KID", "For kids"), ("FAN", "Fantasy"), ) book_genre=models.CharField(max_length=3, choices=BOOK_GENRE) book_rental=models.ForeignKey(Rental, on_delete=models.CASCADE, default=1, related_name="display") class Meta: constraints =[ models.UniqueConstraint(fields=['book_author','book_title'], name='unique_book'), ] my views: class BookListView(ListView): model = Book template_name='book.html' class BookDetailView(DetailView): model = Book template_name='book_detail.html' class RentalListView(ListView): model = Rental template_name='rental_list.html' class RentalDetailView(DetailView): model = Rental template_name='rental_detail.html and my htmls look like this: <h1 style="font-size:11px; text-align:right;"><a href="{%url 'home' %}">Powrót do strony głównej</a></h1> {% block content %} {%for … -
JWT Tokens in Django Rest Framework
I am building a Django Rest Framework API which is using JWT authentication. I had created access tokens and refresh tokens and sent them to users. I also have a refresh token endpoint that will take old refresh token and generate new pair of tokens and send to user. I have doubt in its behavior related part. Currently what I can see that whenever I create new pair of access and refresh token using previous refresh token, the old access token is also working and new one is also working. However once when I was using OAuth2.0 (in different case), I observed that in that case the old access token won't work if we had created new refreshed tokens. But in case of my implementation of JWT in DRF this thing won't happens. I am not storing token in database. So I want to know that is this any implementation specific problem or is it the property of JWT only, and if it is property then please share some details over it with me. Thanks. -
How can i relaunch anaconda navigator without error
Navigator Error An unexpected error occurred on Navigator start-up Report Please report this issue in the anaconda issue tracker Main Error unacceptable character #x0000: special characters are not allowed in "C:\Users\Tokunbo.continuum\anaconda-client\config.yaml", position 0 Traceback Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\exceptions.py", line 74, in exception_handler return_value = func(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\app\start.py", line 137, in start_app window = run_app(splash) File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\app\start.py", line 60, in run_app window = MainWindow(splash=splash) File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\widgets\main_window_init_.py", line 224, in init for _ in anaconda_solvers.POOL.solve(): File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\utils\anaconda_solvers\core.py", line 72, in solve configuration: typing.Any = binstar_client.utils.get_config() File "C:\ProgramData\Anaconda3\lib\site-packages\binstar_client\utils\config.py", line 250, in get_config file_configs = load_file_configs(SEARCH_PATH) File "C:\ProgramData\Anaconda3\lib\site-packages\binstar_client\utils\config.py", line 242, in load_file_configs raw_data = collections.OrderedDict(kv for kv in itertools.chain.from_iterable(load_paths)) File "C:\ProgramData\Anaconda3\lib\site-packages\binstar_client\utils\config.py", line 242, in raw_data = collections.OrderedDict(kv for kv in itertools.chain.from_iterable(load_paths)) File "C:\ProgramData\Anaconda3\lib\site-packages\binstar_client\utils\config.py", line 222, in dir_yaml_loader yield filepath, load_config(filepath) File "C:\ProgramData\Anaconda3\lib\site-packages\binstar_client\utils\config.py", line 206, in load_config data = yaml_load(fd) File "C:\ProgramData\Anaconda3\lib\site-packages\binstar_client\utils\yaml.py", line 12, in yaml_load return safe_load(stream) File "C:\ProgramData\Anaconda3\lib\site-packages\yaml_init.py", line 125, in safe_load return load(stream, SafeLoader) File "C:\ProgramData\Anaconda3\lib\site-packages\yaml_init_.py", line 79, in load loader = Loader(stream) File "C:\ProgramData\Anaconda3\lib\site-packages\yaml\loader.py", line 34, in init Reader.init(self, stream) File "C:\ProgramData\Anaconda3\lib\site-packages\yaml\reader.py", line 85, in init self.determine_encoding() File "C:\ProgramData\Anaconda3\lib\site-packages\yaml\reader.py", line 135, in determine_encoding self.update(1) File "C:\ProgramData\Anaconda3\lib\site-packages\yaml\reader.py", line 169, in update self.check_printable(data) File "C:\ProgramData\Anaconda3\lib\site-packages\yaml\reader.py", line 143, in check_printable … -
Why can't i see the text of description in my url?
In home category i have elf as a description : image I tried this code in my views to be able to display elf in my templates: def home(request ): p=get_object_or_404(category,pk=1) return render(request,'home.html',{'p':p}) and in templates i used this code <p id="id">{{p.description}}</p> to display it but it is not working i can not see the description or elf in this path path('',views.home), models: class category(models.Model): name=models.CharField(max_length=255, db_index=True) def __str__(self): return self.name class product(models.Model): category = models.ForeignKey(category, related_name='products',on_delete=models.CASCADE) image=models.CharField(max_length=500) description=models.CharField(max_length=500) price=models.CharField(max_length=50) buy=models.CharField(max_length=100) urls: urlpatterns = [ path('api/', include(router.urls)), path('',views.home), path('admin/',admin.site.urls), ] Why can't i see the text of description in my url? -
GCP/Django - Server cannot serve a simple htmlresponse
So while I've successfully got the django app to locally serve and use the GCP SQL as backend, I'm having a hard time trying to get successful requests out of the django app using Google App Engine (Standard). Even a simple htmlresponse message doesn't work. Any advice here? Some odd things to note: there are 500 requests about the "favicon.ico" even though I don't use an ico file but a png. Removing the use of the favicon entirely yields similar results but now says "GET / HTTP/1.1 500" (Don't know what this is about) views.py (abbreviated) def index(request): return HttpResponse("Congratulations!") app.yaml runtime: python39 env_variables: BUCKET_NAME: "mystoragebucket" APPENGINE_URL: https://my-project-123456789101.uk.r.appspot.com/ handlers: - url: /static static_dir: static/ - url: /.* script: auto settings.py (abbreviated) DEBUG=False APPENGINE_URL = os.getenv('APPENGINE_URL') ALLOWED_HOSTS = [APPENGINE_URL[8:]] CSRF_TRUSTED_ORIGINS = [APPENGINE_URL] SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True STATIC_URL = "https://storage.googleapis.com/mypublicstaticbucket/static/" SECRET_KEY = 'django-insecure-randomstringhere' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': '/cloud_sql/my-project-123456789101:us-east4:MYSQLInstanceNameHere', 'PORT' : 5432, 'NAME': 'MyDBNameHere', 'USER': 'myUsername', 'PASSWORD': 'MyPassword', } } -
Implementation of info in a web form
Im making a website for applying to jobs using django. The home page will display the different offers. I have 2 search bars, one for looking up a country or city and one for looking up job titles. The respective searches will come up. I want a drop down menu where you can pick a salary. The thing is when the person presses the salary i dont want a request to be sent just for the salary to be saved to a form. When a search is made I want both the salary and whatever is in the search bar to be sent to the backend -
how to authentication using react native and django
Hi I'm new to a react native I used to build full-stack pages using react js and Django in the backend but with react native I am facing a lot of problems with expo is there good documentation for that? -
Django '>' not supported between instances of 'NoneType' and 'int' Overlapping Checking
I am trying to make the code to check the overlapping in django forms , my code in form.py is , a = [] if count > 1: for i in range(count): first_number = self.data.get(f'newevent_set-{i}-first_number', []) last_number = self.data.get(f'newevent_set-{i}-last_number', []) new_run = self.data.getlist(f'newevent_set-{i}-new_run', []) a.append((i, first_number, last_number, new_run)) for i, base_data in enumerate(a): for check_data in a[i + 1:]: if float(base_data[1]) > float(check_data[0]): raise ValidationError ("Overlap Happening") -
How to stop scrapy from paginating the pages with repetitive records?
I tried to crawl a website whit pagination by scrapy, and it was ok! But, as this website gets update and new posts are added to this website, I need to run my code every day, so each time I run my code, it crawls all the pages. Fortunately, I'm using django and in my django model, I used unique=True So there are no duplicate records in my database, but I want to stop the pagination crawling as soon as it finds a duplicate record. how should I do this? here is my spider snippet code: def parse(self, response, **kwargs): next_page = response.xpath('//a[@class="next page-numbers"]/@href').get() news_links = response.xpath('//div[@class="content-column"]/div/article/div/div[1]/a/@href').getall() # print('*'*50) for link in news_links: yield scrapy.Request(url=link, callback=self.parse_item) if next_page: yield scrapy.Request(url=next_page, callback=self.parse) def parse_item(self, response): item = CryptocurrencyNewsItem() ... return item -
How to insert a variable from some premises created previously with the django query?
I'm building a query and I would like when the student is present and the justification is rejected that the value_x be placed, but the "Value" does not allow me to place a variable in it. Does anyone know a way to do this in django? Here's code below: inscritos = Inscricao.objects.all().annotate(valor_x=(Subquery(CursoValores.objects.filter(Q(curso__id_curso=OuterRef('Turma__Curso__id_curso'))&Q(data_inicio__lte=OuterRef('Turma__dt_hr_inicio'))&Q(data_fim__gte=OuterRef('Turma__dt_hr_inicio')) ).annotate(Max('valor')).values('valor__max'),output_field=FloatField())), valor_t=Case(When(Q(Presente=False)&Q(justificativa__situacao='I'), then=Value(valor_x)), default=Value(0), output_field=IntegerField(), ) -
Access to django filter data on view
I want to display information regarding the filter criteria received in the form, in the template. What is the best way to access this data in the view? -
Python subprocess doesn't find the PYTHONPATH
I'm using subprocess to call a python script but it doesn't work because it doesn't find my PYTHONPATH. I have a my PYTHONPATH put and it goes inside my folder. let's say my PYTHONPATH contains this path: /home/myproject. My architecture is this one: /myproject/djangoView/view_x.py from my view_x.py I use subprocess to launch a script that is on /myproject/scripts/script.py Then I start my server django, I have to click on a button and it should launch my script.py, to be clear it does work in local, but it doesn't work in preprod which is a server ubuntu. The error I have is ModuleNotFoundbecause in my script I call/utils/utils.py` So I just don't really understand why I have an error, my PYTHONPATH is set and correct, all the imports calling /utils/utils.py are working except when I'm using subprocess in my preprod server. I can't reproduce it in local. Is someone have an explanation for this behavior ? Here is my call: subprocess.run(["nohup python3 /home/myproject/scripts/script.py &"], shell=True) Thanx. -
how can i create a html file template in django application?
I'm learning Django and I have a problem that there is no answer for it on internet here is the problem, I created a folder as 'app', and I create another folder in app as 'challenges' (in VS Code in a Django application), so we have 2 nested folders now I want to create an HTML page, and I create a file as 'index.html', but VS Code cannot know this file as an HTML file -
how to send multi args to Django custom templates from JS code inside HTML template
I'm trying to use a custom template tag to run a specific function on a variable that I get in JS inside my HTML template. here is a sample of what I tried : python template tag def calculate_km(value, arg): """ Calculate the km from the source """ args_list = eval(arg) layer_id = value return f"layer_id_is:{layer_id}, args_list:{args_list}" then am using it inside my HTML js block like this : const args_data = "[" + kmlEvent.featureData.id + "," + kmlEvent.latLng.lat + "," + kmlEvent.latLng.lng + "]"; console.log(`{{single_layer.id|calculate_km: ${args_data} }}`); The problem here is in adding the JS variable inside the template tag , as you see using args_data inside the string that should return syntax for normal Django template so what is expected is that the console.log line renders as follows : {{12|calculate_km:[12,Foo,123,456]}} But the problem is that it is not reading the value of the variable args_data and it is being rendered as : {{12|calculate_km: ${args_data}}} and of course, that returns an error which is : django.template.exceptions.TemplateSyntaxError: calculate_km requires 2 arguments, 1 provided so it seems like not even reading the value of args_data -
Django annotation + filtering
I've some data that I've loaded from SQLite to PSQL using pgloader, it works more or less but some types are a bit clunky, so that's why my dates are in string, but I don't think that's the issue ( might be wrong here) Consider the following models: class User(models.Model): hash_id = models.TextField(primary_key=True) first_name = models.TextField(blank=True, null=True) last_name = models.TextField(blank=True, null=True) class Education(models.Model): hash_code = models.ForeignKey('Users', models.CASCADE) startdate = models.TextField(blank=True, null=True) enddate = models.TextField(blank=True, null=True) class Job(models.Model): hash_code = models.ForeignKey('Users', models.CASCADE) jobends = models.TextField(blank=True, null=True) jobstarts = models.TextField(blank=True, null=True) I'm trying to get all the jobs after X years from the user's first Education. So far I've got a Subquery, to get the first education's start date for each user: # This should return a date eg: '2000-01-01' mba_start_subq = Educations.objects.filter(hash_code=OuterRef('hash_code')) .order_by('startdate') .values('startdate')[:1] ) Then I append this to each Job via: jobs = (Job.objects.all() # .distinct('hash_code') .order_by('hash_code') .annotate(mba_start = Subquery(mba_start_subq)) ) So far so good, the issue is when I try to add a .filter() afterwards it takes ages to get the response (basically an infinite loop kind of thing) # Filtering with date strings works jobs.filter( Q(jobstarts__lt = '2000-01-01'), Q(jobends__gt = '2002-01-01') ) # this is the desired … -
how to get object position in a queryset without for loop?
i have a queryset with length = 10000 users sorted_users = User.ojbects.all().order_by("-money") and i need to get a position of a particular user in this sorted query set, i can do it with foor loop: user_position = 1 for account in sorted_users: if account.username == "admin": break my_position += 1 print(user_position) it works fine, but in case of growing user numbers for example to 100 000, it would take a long time to count users position every time, for loop is slow how can i make it faster, without a for loop? -
Nginx raising 403 Forbidden when accessing Staticfiles in Django app on Digital Ocean
having completed a django project on local development in my system, i followed the Digital Ocean tutorial to deploy a django app here Digital Ocean Django ASGI setup Tutorial. i configured gunicorn according to the tutorials and all tests and confirmations are passed But when i load my site from its Public IP address the site loads without any styles or designs and no images...just as plain text (just html content) my nginx configuration is as follows server { listen 80; server_name XXX.XX.XXX.XX; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/username/projectdir/staticfiles; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } and my django Project setting is as follows # The absolute path to the directory where collectstatic will collect static files for deployment. STATIC_ROOT = BASE_DIR / 'staticfiles' # The URL to use when referring to static files (where they will be served from) STATIC_URL = '/static/' # extra places to find static filed outside static folder inside installed apps STATICFILES_DIRS = [ BASE_DIR/"static" ] MEDIA_ROOT = BASE_DIR/"media" can any solution be suggested. i have seen all the other related stackoverflow questions that had similar issues but their solutions did not work for … -
DRF : 'DemoView' should either include a `queryset` attribute, or override the `get_queryset()` method
I want to create a serializer without model. myproject/myapp/views.py : from rest_framework import viewsets from rest_framework.response import Response from .serializers import DemoSerializer class DemoView(viewsets.ModelViewSet): def get(self, request): my_data = [{"name": "Harsha"}, {"name": "Harsha"}] results = DemoSerializer(my_data, many=True).data return Response(results) myproject/myapp/urls.py from django.urls import path, include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register('demo', views.DemoView, basename='Demo') urlpatterns = [ path('', include(router.urls)), ] myproject/myapp/serializer.py from rest_framework import serializers # from .models import Demo class DemoSerializer(serializers.Serializer): name = serializers.CharField() When I goto URL: http://localhost:8000/demo/, it is giving me following error: DemoView should either include a queryset attribute, or override the get_queryset() method. How can I resolve this error? -
DRF SerializerMethodField ignoring result
I have 2 serializers (one nested in the other). I need to pass context so that I can get an absolute url. I can see it works based on printing as it runs. But the actual result ignores the method and just returns standard (im assuming because it doesnt think it has a context). class ProjectNoteFileSerializer(serializers.ModelSerializer): thumb = serializers.SerializerMethodField() def get_thumb(self, obj): try: print(self.context.get("request")) #this actually prints like it does have it thumbnail = get_thumbnailer(obj.path)["big"].url return self.context.get("request").build_absolute_uri(thumbnail) except: return None class Meta(object): model = models.ProjectNoteFile fields = ("id", "path", "thumb") class ProjectQuestionnaireSectionSerializer(serializers.ModelSerializer): note_files = serializers.SerializerMethodField() def get_note_files(self, obj): serializer_context = {"request": self.context.get("request")} serializer = ProjectNoteFileSerializer( obj.note_files.all(), many=True, context=serializer_context, ) print(serializer.data) #prints results as expected return serializer.data class Meta(object): model = models.ProjectQuestionnaireSection fields = ( ... "note_files", ... ) My actual result is "note_files": [ { "id": 1, "path": "/media/project_notes/project_note_d5c598da-d4e8-480e-a50a-c474d57a7d44.png", "thumb": null } ], I have other versions of this working across the app. Maybe I am missing something basic?