Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Resolve Graphene Django Field with Dependency On Another Field
Is it possible to resolve two fields using the output of one field to generate the output of the other field? For example, I need to generate a refresh token with the access token, but I'm unsure how to get the access token in the refresh token resolver. class Tokens(graphene.ObjectType): accessToken = graphene.String() refreshToken = graphene.String() def resolve_accessToken(self, info, **kwargs): return "..." def resolve_refreshToken(self, info, **kwargs): return "..." -
OSError: [WinError 127] : The specified procedure could not be found
What does this error means? Im trying to use Django with Geodjango, i followed all documentation steps, but still got this error when trying to make migrations. The models.py its correct, im using from geodjango site, this is my settings import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ci3qd6ti+d+#-4pae7d*)^8nmmgb2j@cacivgt8rdvsngu2$mj' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'world', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'geodjango.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'geodjango.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test', 'USER': 'postgres', 'PASSWORD': '*********', 'HOST': '127.0.0.1', 'PORT': '5432', } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # … -
Django super save and #1062 duplicate entry for key "PRIMARY"
this follow is my model, class Problem(models.Model): pay_id = models.CharField(max_length=32, default=get_uuid_str) payer = models.ForeignKey(Profile, blank=True, null=True, related_name='pay_out_list') payee = models.ForeignKey(Profile, blank=True, null=True, related_name='pay_in_list') creation_datetime = models.DateTimeField(default=get_utc_now_with_tzinfo) expiry_datetime = models.DateTimeField(blank=True, null=True) status = models.CharField(max_length=2, default='I', choices=PAYMENT_STATUS) pay_type = models.CharField(max_length=2, default='C', choices=PAYMENT_TYPES) pay_symbol = models.CharField(max_length=10) pay_amt = models.FloatField(default=0.0) pay_qr_code = models.FileField(blank=True, null=True, upload_to=problem, storage=ca_public) return_url = models.CharField(blank=True, null=True, max_length=255) user_data_json = models.TextField(blank=True, null=True) objects = CAPayManager() And when i do save, this error was raised. obj = Problem(payer=payer,status="QI",user_data_json=user_data) obj.save(int(1)) The following is my save method, def save(self, *args, **kwargs): expiry_hrs = kwargs.pop('expiry_hrs', None) if not self.id: super(Problem, self).save(*args, **kwargs) self._create_save_qr_code() if expiry_hrs: try: expiry_hrs = int(expiry_hrs) except: expiry_hrs = -1 if expiry_hrs > 0: self.expiry_datetime = self.creation_datetime + timedelta(hours=expiry_hrs) super(Problem, self).save(*args, **kwargs) and this is my traceback FYI. Traceback (most recent call last): File "/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/rest_framework/views.py", line 466, in dispatch response = self.handle_exception(exc) File "/Users/boonyao/.virtualenvs/copa/lib/python2.7/site-packages/rest_framework/views.py", … -
Django 2.0: Generic detail view must be called with either an object pk or a slug
So I just added an update view to my detail view. However, when I try to load the page after I add the 'Edit' button below, I am getting a Generic Detail View error. What is going on? Template Page: <td><a href="{% url 'thing:update' thing_id=thing_id%}" class="btn btn-primary" class>Edit</a></td> urls.py path('update/<slug:thing_id>/', ThingUpdateView.as_view(), name='update'), views.py class ThingUpdateView(LoginRequiredMixin, UpdateView): model = ThingUser form_class = ThingUserFormSet template_name = "thing/update.html" Traceback File "C:\myapp\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\myapp\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\myapp\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\myapp\lib\site-packages\django\views\generic\base.py" in view 69. return self.dispatch(request, *args, **kwargs) File "C:\myapp\lib\site-packages\django\contrib\auth\mixins.py" in dispatch 52. return super().dispatch(request, *args, **kwargs) File "C:\myapp\lib\site-packages\django\views\generic\base.py" in dispatch 89. return handler(request, *args, **kwargs) File "C:\myapp\lib\site-packages\django\views\generic\edit.py" in get 189. self.object = self.get_object() File "C:\myapp\lib\site-packages\django\views\generic\detail.py" in get_object 47. % self.__class__.__name__) Exception Type: AttributeError at /thing/update/8bv4tyrkyy/ Exception Value: Generic detail view ThingUpdateView must be called with either an object pk or a slug. -
Python virtual environment package install issue
I'm building a Python project requiring Django. I have created a project directory and virtual environment using virtualenv. But I can't install django using PIP and I have to use easy_install in order to install it into the virtual environment. Note - I only have this problem with Django. I am able to successfully install other packages into the virtual environment using PIP without issues. I'm running the following sequence... cd projectfolder virtualenv venv venv\Scripts\activate pip install django And I get the following error message: Could not install packages due to an EnvironmentError: [WinError 5] Access is denied: 'C:\\Users\\xxxx\\AppData\\Local\\Temp\\pip-unpack- kc0_p8wh\\Django-2.1-py3-none-any.whl' Consider using the `--user` option or check the permissions. Again - if I run the same block of code, but end it with: easy_install django Then the package installs fine. Any thoughts? -
Using django-oauth-toolkit with Django 2.x
I've built a web application using django 2.0 and django-rest-framework. In my web app, I've been using django-rest-framework's SessionAuthentication. I'm in the early stages of building out a supporting mobile app and based on my findings so far, there's a lot of value in doing the extra work to implement some sort of OAuth authentication: - django swift login system - https://yeti.co/blog/oauth2-with-django-rest-framework/ I was hoping to use django-oath-toolkit for this, but I noticed in the docs that there's no django 2.x support. I want to avoid refactoring my app using django 1.x, so two questions: Has anyone used django-oath-toolkit successfully for django 2.x? (It appears that at least some people have tried it.) Am I exposing my app to security risks if I go this route? Are there any alternatives to django-oath-toolkit? Or am I wrong in my conclusion that a secure mobile application needs to use OAuth for authentication? (That conclusion was primarily drawn via this Stack Overflow answer.) -
How to Count All Objects of a Database Table in Django?
I have a model as below, I would like to filter a user's all work_times in Table Work with Django 2.0.4, thanks in advance for any advice. class Work(models.Model): name = models.CharField(max_length=800) date = models.DateField(auto_now=False, null=True, blank=True) time = models.TimeField(auto_now=False, null=True, blank=True) work_times = models.FloatField(default=1, verbose_name="work times(hours)") user = models.ManyToManyField(User, related_name="works", blank=True) -
django Models getting user info
trying to create a model that has an artist and song and lets you know what user name typed it in. so far I have in my models.py from django.contrib.auth.models import User class Song(models.Model): uesrname = models.ForeignKey(User,on_delete=models.CASCADE) artist = models.CharField(max_length=30) song=models.CharField(max_length=30) I added a form that works with user input data but the form lets me select one of all exciting Users and input artist, song how can I change it so I will have only my own loged in user in the form? -
Nginx + Gunicorn + Django high latency
I'm trying to adjust my WS to support ~ 20k concurrent users. No matter what configuration I change I still get the same 6 secs avg response time / per endpoint when my tests hit 2(two)k users and various 502 / 504 errors. WebService: CloudFlare <--> Nginx <--> Gunicorn <--> Django/DRF <--> Memcache <---> Postgres Here's what I tried: Increase gunicorn workers from 4 to 10 Increase service(pod) instances from 3 to 10 Increase gunicorn worker timeout to 120 Increase Nginx proxy_pass timeout to 120 Most endpoints hit the database once every 100 seconds and the other requests get the data from memcache. Could any one help by pointing out what kind of configuration should I be changing? Where should I be looking for delays/bottlenecks? Gunicorn workers clearly are timming out, which I dont undersdand since theres no logic in the WS views. It should be only getting a query from memcache and returning it. Nginx logs: latforms/android HTTP/1.1", upstream: "http://10.0.1.17:9090/endpoints/platforms/android", host: "myhost.co" 2018/08/13 23:43:25 [error] 8893#8893: *2809163 upstream timed out (110: Connection timed out) while connecting to upstream, client: 200.211.198.133, server: myhost.co, request: "GET /endpoints/store/products/729 HTTP/1.1", upstream: "http://10.0.1.18:9090/endpoints/store/products/729", host: "myhost.co" 200.211.198.133 - [200.211.198.133] - - [13/Aug/2018:23:43:25 +0000] "GET /endpoints/store/categories/?cat_pk=13081 … -
Creating buttons in a column of a table created by django tables2
I have an extended admin model that creates action buttons. I have created a view to do pretty much the same thing. I have used tables2 and everything is just fine except for the actions column. I cannot find a way to generate the same button in the table. Is there a way to do this at all? tables.py from .models import Ticket import django_tables2 as tables '''from .admin import river_actions, create_river_button''' class TicketTable(tables.Table): class Meta: model=Ticket template_name='django_tables2/table.html' fields = ('id','subject','request_type','material_type','productline','business','measurement_system', 'created_at','updated_at','status','river_action','project') # fields to display attrs = {'class': 'mytable'} '''attrs = {"class": "table-striped table-bordered"}''' empty_text = "There are no tickets matching the search criteria..." admin.py (the part that includes the model etc) # Define a new User admin to get client info too while defining users class UserAdmin(BaseUserAdmin): inlines = (UserExtendInline, ) def create_river_button(obj,proceeding): return """ <input type="button" style=margin:2px;2px;2px;2px;" value="%s" onclick="location.href=\'%s\'" /> """%(proceeding.meta.transition, reverse('proceed_ticket',kwargs={'ticket_id':obj.pk, 'next_state_id':proceeding.meta.transition.destination_state.pk}) ) class TicketAdmin(admin.ModelAdmin): list_display=('id','client','subject','request_type','material_type','productline','business','measurement_system', \ 'created_at','updated_at','created_by','status','river_actions') #list_display_links=None if has_model_permissions(request.user,Ticket,['view_ticket'],'mmrapp')==True else list_display #list_display_links=list_display #use None to remove all links, or use a list to make some fields clickable #search_fields = ('subject','material_type') list_filter=[item for item in list_display if item!='river_actions'] #exclude river_actions since it is not related to a field and cannot be filtered #Using fieldset, we … -
How to use values passed by jquery/ajax in django view
How do I use data passed to view via ajax/jquery? In this example I'm trying to implement a reddit like upvote/downvote system html/js: {% for post in posts %} <h2>{{ post.title }}</h2> {{ post.upvotes }}<button data-id="{{post.id}}" data-vote="up" class="vote" type="submit">Upvote</button> {{ post.downvotes }}<button data-id="{{post.id}}" data-vote="down" class="vote" id="downvote" type="submit">Downvote</button> {% endfor %} <script> $(".vote").click(function () { var id = $(this).data("id"); //get data-id var vote_type = $(this).data("vote"); //get data-vote }; $.ajax({ url: '/ajax/upvote/', data: { 'id': id, 'vote_type':vote_type, } }); </script> view: def upvote(request): #how do i use 'id' and 'vote_type' values here -
django project form not valid?
I have been trying to implement a way to post a project post where the user can upload multiple images. The multiple image upload works but posting the post itself does not work. I am not sure what to do with the project_form. My code is: views.py class CreateProjectsView(View): def get(self, request): p_photos = P_Images.objects.all() #project_form = ProjectsForm(initial=self.initial) project_form = ProjectsForm context = { 'p_photos': p_photos, 'project_form': project_form, } return render(self.request, 'projects/forms.html', context) def post(self, request): project_form = ProjectsForm(request.POST or None, request.FILES or None) p_formset = P_ImageForm(request.POST, request.FILES) # Checks if the project_form is valid before save if project_form.is_valid(): instance = project_form.save(commit=False) instance.user = request.user instance.save() # Checks if multiple image upload is valid before save if p_formset.is_valid(): #if project_form.is_valid() and p_formset.is_valid(): #instance = project_form.save(commit=False) #instance.user = request.user #instance.save() images = p_formset.save(commit=False) images.save() data = { 'is_valid': True, 'name': images.p_file.name, 'url': images.p_file.url } else: data = { 'is_valid': False, } return JsonResponse(data) -
How to retrieve a queryset using any/exists/all logic across foreign key relationships in Django?
Assuming I have two models: from django.db import models class Parent(models.Model): active = models.BooleanField() class Child(models.Model): parent = models.ForeignKey(Parent) active = models.BooleanField() How might I go about getting a query set of parents that have at least 1 active child? In other words, how would I get a query set of parents that excludes those without any active children? If using model properties in filters was feasible, this would be a trivial task, but that is not possible. This is also a simple operation using list comprehensions, but it's important here for the queryset to be the end result. -
How to auto save current logged in user when saving a wagtail Page
I am testing wagtail to see if it suits our needs and was wondering how to auto save a user field with current logged in user? eg, I want to auto save the author field: class HomePage(Page): body = RichTextField(blank=True) author = models.ForeignKey(User) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), ] Before using wagtail I would override save methods to achieve this but it's not working with the wagtail Page, the author field saves blank. def save_model(self, request, obj, form, change): instance = form.save(commit=False) instance.author = request.user instance.save() form.save_m2m() return instance def save_formset(self, request, form, formset, change): def set_user(instance): instance.author = request.user instance.save() if formset.model == Homepage: instances = formset.save(commit=False) map(set_user, instances) formset.save_m2m() return instances else: return formset.save() Could anyone point me in the right direction? -
Django get a value from a .all() query without re-querying the DB
Quick caveat - I am quite new to Django, web development, and programming in general. I am running into an issue where I am querying the DB far too many times, resulting in 50 duplicates. I want to be able to do one large query, that fetches all results, and then be able to pull from that query as needed. I have tried to make this happen, but I cannot seem to figure out how to specify a value in my prefetched query without recalling the query again. My understanding is that .all() doesn't necessarily call the query at the point of declaration, and I'm guessing that is my issue, but I'm not sure. Here is my code: qs = Employees.objects.all().select_related( 'employee', 'team', 'department', 'manager') for p in periods: period, range, score, subject = p current_team = current_department = current_manager = None try: user = qs.get(employee_id=subject) current_team = user.team current_department = user.department current_manager = user.manager.username subject = user.employee.username except (User.DoesNotExist, Employees.DoesNotExist): subject = User.objects.get(id=subject).username -
Adding ImageFields to models
I want to add ImageField to my model name of "models", But admin panel is failing.... I am beginner...My fail is very basic exception I know but I can't solve. What should I do? (sorry for my bad english,ı am high school student) Model Code from django.db import models # Create your models here. #create a model and some models class posting (models.Model): title=models.CharField(max_length=120,verbose_name='Başlık') content=models.TextField(verbose_name="İçerik") publishing_date=models.DateTimeField(verbose_name="Yayınlanma tarihi") photo=models.ImageField() #herposta title ına göre indexliyor def __str__(self): return self.title Exception descr: OperationalError at /admin/posting/posting/ no such column: posting_posting.photo Request Method: GET Request URL: http://127.0.0.1:8000/admin/posting/posting/ Django Version: 1.10 Exception Type: OperationalError Exception Value: no such column: posting_posting.photo Exception Location: C:\Users\Lenovo\Desktop\blog\venv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 337 Python Executable: C:\Users\Lenovo\Desktop\blog\venv\Scripts\python.exe Python Version: 3.7.0 Python Path: ['C:\\Users\\Lenovo\\Desktop\\blog', 'C:\\Users\\Lenovo\\Desktop\\blog\\venv\\Scripts\\python37.zip', 'C:\\Users\\Lenovo\\Desktop\\blog\\venv\\DLLs', 'C:\\Users\\Lenovo\\Desktop\\blog\\venv\\lib', 'C:\\Users\\Lenovo\\Desktop\\blog\\venv\\Scripts', 'c:\\users\\lenovo\\appdata\\local\\programs\\python\\python37-32\\Lib', 'c:\\users\\lenovo\\appdata\\local\\programs\\python\\python37-32\\DLLs', 'C:\\Users\\Lenovo\\Desktop\\blog\\venv', 'C:\\Users\\Lenovo\\Desktop\\blog\\venv\\lib\\site-packages'] Server time: Sal, 14 Ağu 2018 02:01:09 +0300`enter code here` -
Place the uploaded image (illustration) within Zinnia Blog Post text
Hello friends of the SO Community, Our team has decided to utilize Zinnia's library for building out our site blog. Lovin' the quick integration and how there's lots of structure preset saving some upstart time, but I am still left trying to customize. I have 2 questions. The first pertains to the code below. With Zinnia's structure, they serve you all of the content via their invisible view & preset variables, which is nice. Although our content creator wants to take the separate img from the entry-image block and place that image within specific paragraph breaks into the {{ object_content|safe }} portion of the entry-content block. How would one go about achieving this? My first hunch is that we will have to override the view and intercept that variable, but I was not sure exactly how to accomplish this. {% block entry-image %} {% if object.image %} <div class="entry-image"> {% if continue_reading %} {% endif %} <figure itemprop="image" itemscope itemtype="http://schema.org/ImageObject"> <img onerror="this.style.display='none';" style="max-height:300px;" class="img-fluid" src="{{ object.image.url }}" alt="{{ object.image_caption|default:object.title }}" itemprop="contentUrl" /> {# <img class="" src="http://placehold.it/750x300" alt="Card image cap"> #} {% if object.image_caption %} <figcaption itemprop="caption">{{ object.image_caption }}</figcaption> {% endif %} </figure> {% if continue_reading %} {% endif %} </div> … -
Django; display problems for image of model object passed to template from view
Created new item with name, description and an image with django admin and attached image and I saw the image pop into the media folder on the server as it was uploaded. I passed the item from view to template. The item name, description showed up in the website but the image ('image.jpg') did not. Any ideas? Maybe nginx is causing the image to stay concealed? I'm using nginx, gunicorn, django. note: on Chrome, it shows a torn image icon. The source code on the browser shows <img src="image.jpg/">. I noticed that the static files are in the format : <img src="static/app1/image123.jpg and display fine. Perhaps my problem image should have media/app1/...? My ultimate goal is to disaply a graph/image BUT this image is frequently overwritten, with changes, in the media folder from a separate app on the server. This way the viewer can get the latest image. abridged file structure, for easy viewing: -website1 -media image.jpeg +static -app1 -templates -app1 index.html layout.html -website1 settings.py .. website1 urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls import include, url from django.conf.urls.static import static from website1 import settings urlpatterns = [ path('admin/',admin.site.urls), path('app1/',include('app1.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) app1's … -
Sort divs in django template
I new in Django, help in my problem, please. class Article(models.Model): articlecategory = models.ForeignKey(ArticleCategory) Articlecategory can by Big_news(1 news in a row) or Small_news(3 news in a row) I want this logic in template: 1)sort all article by date 2)if last 3 news = Small_news => create row with 3 div 3)if in last 3 news we have Big_news => create row with Big_news-> then create row with small news(if all 3 news after big_news are small_news) How can I get this(paragraph 3) in Django? -
How to specify typings for dynamic fields similar to django Model/Field?
For example: # field base class class F: pass # represent integer class AF(F): pass # represent string class BF(F): pass class M: a = AF() b = BF() def __init__(self): pass # generate dynamic attrs based on specified static attrs m = M() # m.a should have inferred type integer Maybe it is just IDE (PyCharm) feature with all these type hint, and this feature is hard-bind to django's Model class? -
Django adding objects to other objects in a many to many relationship
I am biulding a Django backend and I have two models like this class A(models.Model): name = models.Charfield(max_length=20) class B(models.Model): title = models.Charfield(max_length=20) a = models.manytomanyfield(A) I have created several objects of both and when I go to create a new B object all of the class A objects created before are already listed in the relationship. How can I fix this so that There are no A objects in the relationship for a new B object until I add one? Thanks for the help! -
Accessing Docker Instance on Centos Server
I've managed to deploy a Django app inside a docker container on my personal Mac using localhost with Apache. For this, I use docker-compose with the build and up commands. I'm trying to run the same Django app on a CentOS server using a docker image generated on my local machine. Apache is also running on the server on port 90. docker run -it -d --hostname xxx.xxx.xxx -p 9090:9090 --name test idOfImage How can I access this container with Apache using the hostname and port number in the URL? Any help would be greatly appreciated. Thanks. -
How to filter based on the last element in ArrayField in django
I'm using postgresql database which allows having an array datatype, in addition django provides PostgreSQL specific model fields for that. My question is how can I filter objects based on the last element of the array? class Example(models.Model): tags = ArrayField(models.CharField(...)) example = Example.objects.create(tags=['tag1', 'tag2', 'tag3'] example_tag3 = Example.objects.filter(tags__2='tag3') I want to filter but don't know what is the size of the tags. Is there any dynamic filtering something like: example_tag3 = Example.objects.filter(tags__last='tag3') -
How to take slice of string when serializing a field (Django/DRF)
First time asking here, I'll try to sound smart! So, I've got a model called 'Article', and I've populated its 'text' field with 1000+ chars of text. How can I make it so I only send the first 200 chars of the 'text' field when I send an 'Article' serialized object through an endpoint? views.py class ArticleScrape(generics.ListAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer def list(self,request): serializer = ArticleSerializer(queryset, many=True) return Response(serializer.data) serializers.py class ArticleSerializer(serializers.ModelSerializer): authors = EachAuthorSerializer(many=True,read_only=True) tags = EachTagSerializer(many=True,read_only=True) text = serializers.CharField(max_length=200) class Meta: model = Article exclude=('id',) Do I need to perform this operation in the queryset? in the serializer? Do I annotate a field? I've tried many of this with no succes. Thanks in advance for the help! -
unable to display form inside modal dialog
I am having trouble displaying password change from inside modal window. I can see the modal window but I don't see the call happening to def change_password even though I have mentioned it in the action of my modal. Views.py def change_password(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! messages.success(request, 'Your password was successfully updated!') return redirect('change_password') else: messages.error(request, 'Please correct the error below.') else: form = PasswordChangeForm(request.user) return render(request, 'usermgmt/change-password.html', { 'form': form }) modal dialog: <div id="passwordChangeModal" class="modal fade" role="dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Change Password</h4> </div> <div class="modal-body"> <form action="{% url 'usermgmt:change_password_page' %}" method="post" id="changepassword" class="form"> {% csrf_token %} {{ form }} </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> template: {% extends 'base.html'%} <h1>Hello From Change Password</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save changes</button> </form>