Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'NoneType' object has no attribute '_meta'
I'm trying to use elastic search in my django model. Currently, if I search with title only it works and returns correct records but when I tried to add a carparts filter it asked me to add index.FilterField('cartpart_id') which I did but now it throws an error that 'NoneType' object has no attribute '_meta' This is my code class IndexPage: def get_context(self, request): recipes = CarPage.objects.child_of(self).live().public() \ .select_related('listing_image') extra_url_params = '' s = get_search_backend() filter_name = request.GET.get("title") filter_carparts = request.GET.get('carparts') if filter_carparts: filter_carparts = filter_carparts.split(",") filter_carparts = [ int(x) for x in filter_carparts ] #Output = [1,2,3] if filter_name and filter_carparts: cars = cars.filter(carparts__carpart__in=filter_carparts).distinct() cars = s.search(filter_name, recipes) elif filter_carparts and not filter_name: cars = cars.filter(carparts__carpart__in=filter_carparts).distinct() extra_url_params = 'carparts={}'.format() elif filter_name and not filter_carparts: cars = s.search(filter_name, recipes) else: cars = cars return context @register_snippet class CarPart(models.Model): title = models.CharField(max_length=50) class Meta: verbose_name_plural = 'Car Parts' def __str__(self): return self.title class CarParts(model.sModel): source_page = ParentalKey( 'home.CarPage', related_name='carparts' ) carpart = models.ForeignKey( CarPart, null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) panels = [ SnippetChooserPanel('catpart'), ] class CarPage(BasePage): enter code here content_panels = BasePage.content_panels + [ InlinePanel('carparts', label="Car Part"), ] def get_context(self, request): context = super().get_context(request) return context class CarPage(BasePage): title= models.CharField(max_length=20) search_fields = … -
Django aggregated field error on returning
I'm stubbling on a problem where I'm no longer shure if I'm doing something wrong or there is something wrong with the package. I have a custom ordering filter of django-filter: class CustomOrderingFilter(OrderingFilter): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.extra['choices'] += [ ('trainingDates', 'Training Dates'), ('-trainingDates', 'Training Dates (descending)'), ] def filter(self, qs, value): if any(v in ['trainingDates', '-trainingDates'] for v in value): data = qs.annotate(first_date=Min('training_dates__date')).order_by('first_date') return data return super().filter(qs, value) When I add a debug point add the return statement I can see the field 'first_date' but when I continue I get the following error: ERROR 2020-02-20 14:00:45,047 utils 24233 Traceback (most recent call last): File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/promise/promise.py", line 487, in _resolve_from_executor executor(resolve, reject) File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/promise/promise.py", line 754, in executor return resolve(f(*args, **kwargs)) File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/graphql/execution/middleware.py", line 75, in make_it_promise return next(*args, **kwargs) File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/graphene_django/filter/fields.py", line 107, in connection_resolver **args File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/graphene_django/fields.py", line 164, in connection_resolver return on_resolve(iterable) File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/graphene_django/fields.py", line 118, in resolve_connection pageinfo_type=PageInfo, File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/graphql_relay/connection/arrayconnection.py", line 88, in connection_from_list_slice for i, node in enumerate(_slice) File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/query.py", line 274, in __iter__ self._fetch_all() File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/bart/projects/coursemanager/backend/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1087, in execute_sql sql, params = … -
How to show images from s3?
To concluindo uma aplicação com django que gera certificado em pdf.. Im finishing an application by django that generates pdf certificates it was working great before I pull it into heroke and set up S3 amazom to host static files. I have an html with the certificate template, and by HTML2PDF I render it to pdf. But it's not showing the background by css, it works just in the tag Weird that if we opent the image url in s3 amazom it's shown perfectly here the template css part <meta charset="utf-8" /> {% load static %} <style type="text/css"> @page { size: 1122.52px 1587.4px ; /*size: A4 landscape;*/ margin: 0cm; background-image: url({{bg_front}}); height: 1588; } </style> ``` Código em python class ViewPDF(View): def get(self, request, *args, **kwargs): data = {} pdf = True if kwargs['pk']: try: participant = Participant.objects.get(pk=kwargs['pk']) print(participant.cpf) if participant.name: certificate = Certificate.objects.get(pk=participant.certificate.pk) pathBack = str(certificate.template.template_back.url) pathFront = str(certificate.template.template_front.url) print(pathFront) # # CONFIGURA OS BACKGROUNDS E TEXTO # data['bg_front'] = pathFront data['bg_back'] = pathBack setting = certificate.template.settings start_date = datetime.strftime(certificate.start_date,'%d/%m/%Y') end_date = datetime.strftime(certificate.start_date,'%d/%m/%Y') data['text_front'] = setting.replace('<<nome>>',participant.name).replace('<<cpf>>',str(participant.cpf)).replace('<<ch>>',str(certificate.ch)).replace('<<instituicao>>',str(certificate.institution)).replace('<<DataInicio>>',start_date).replace('<<DataFim>>',end_date) data['cpf'] = participant.cpf pdf = render_to_pdf('app_certificates/body_front_pdf.html', data) return HttpResponse(pdf, content_type='application/pdf') except TypeError as e: return HttpResponse(e) -
Reactjs static file bundle, after spitting code, on AWS S3, is not working
My website has been working well before my recent change. The website front-end is on reactjs, and bundle is on aws s3. Everything is good till this point. Now because of webpack complains about the size of the bundle and also to optimize my code, I now have split code, via lazy loading and am using webpack-bundle-tracker to create bundle because my back-end is on django. This new setup is working well on my local environment <script type="text/javascript" src="/static/frontend/main.35952edee77e6e3f52e5.bundle.js" ></script> And this loads very well formatted code to load on my local environment: /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ … -
I am trying to migrate my model - but it's giving me error -
Error - client.Client.status: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. Here is the code: class Client(models.Model): client_name = models.CharField(max_length=300) address = models.CharField(max_length=300) start_date = models.DateField(default=datetime.now, blank=True) end_date = models.DateField(default=datetime.now, blank=True) created = models.DateTimeField(auto_now_add=True) ACTIVE = 'AC', TO_EXPIRE = 'TE', EXPIRED = 'EX', STATUS_CHOICES = [ (ACTIVE, 'Active'), (TO_EXPIRE, 'To Expire'), (EXPIRED, 'Expired'), ] status = models.CharField(max_length=2, choices=STATUS_CHOICES, default=ACTIVE) user = models.ForeignKey(User, on_delete=models.CASCADE) -
Group by annotated value in Django ORM
I want to get the number of elements by a category (mora_dias_categoria) that is a calculation of a model field but it doesn't group by correctly. This is what I have tried: metricasColombia = MetricasPrestamosColombia.objects \ .annotate(mora_cantidad =Sum(F('total_habia_que_recibir')-F('total_recibido'))) \ .annotate(mora_dias_categoria = Case( When(Q(mora_cantidad__gt=0) & Q(mora_dias__gt=0) & Q(mora_dias__lte=30),then=Value('mora_030')), When(Q(mora_cantidad__gt=0) & Q(mora_dias__gt=30) & Q(mora_dias__lte=60),then=Value('mora_3060')), When(Q(mora_cantidad__gt=0) & Q(mora_dias__gt=60) & Q(mora_dias__lte=90),then=Value('mora_6090')), When(Q(mora_cantidad__gt=0) & Q(mora_dias__gt=90),then=Value('mora_90')), default=Value('No mora'), output_field=CharField() )) \ .values('semana','idPrestamo_id__idContactoInfo_id__ciudad__nombreCiudad','mora_dias_categoria') \ .annotate(totalPrestamos=Count('idPrestamo_id')) But still get this output (has duplicates when it should be aggregated): [{'semana': '1-2020', 'idPrestamo_id__idContactoInfo_id__ciudad__nombreCiudad': 'Medellín', 'mora_dias_categoria': 'mora_030', 'totalPrestamos': 1}, {'semana': '1-2020', 'idPrestamo_id__idContactoInfo_id__ciudad__nombreCiudad': 'Medellín', 'mora_dias_categoria': 'mora_030', 'totalPrestamos': 1}... Many thanks! -
Relate child to parent on view dynamically
I have two models, Usermodel and Measurements model. The Measurements model is related to the Usermodel via a ForeignKey relationship. I have successfully created the form to allow create users, but would like that when you view these users, you can from there create measurements without indicating the relationship, as it should automatically use the Usermodel being currently displayed as the instance and relate it. This has been an issue. I tried writing the view like this.. def client_measurements(request, pk): measurement = UserModel.objects.get(id=pk) measurements = measurement.measurements_set.all() if request.method == 'POST': form = MeasurementsIForm(request.POST, request.FILES) if form.is_valid(): form.client_name.client_name = measurement.client_name measure = form.save(commit=False) measure.instance = measurement measure.save() return HttpResponseRedirect(reverse_lazy('client', args= [measurement.id])) else: form = MeasurementsIForm() return render(request, 'app/measurements.html', {'form':form, 'measurements': measurements, 'measurement': measurement}) This doesn’t save to database. I am new to django, please what am I doing wrong? -
how to center columns in a container by CSS html
I use border to display the container's edge, you can see the columns are not displayed in the center. I have tried using margin:auto; align:center; but, it does not work! which part should I fix it? I stuck on it for a long time. please help. and here is my html: <div class="container custom-container-width" style="border: 3px solid black; text-align=center;" > <div class="row" > {% for customer in Customer %} <div class="col-sm-3 p-3 gap-buffer " style="background-color:white;box-shadow: 10px 10px 5px grey; " > <h3 style="text-align: center;"> {{ customer.name }} </h3> <div> <div class="table-responsive" > <table > <thead class="thead-dark " > <tr > <th>Product</th> <th>Count</th> <th>Price</th> <th>Subtotal</th> </tr> </thead> <tbody > {% for cart in Cart %} {% if customer.id == cart.customer_id %} {% for good in Good %} {% if cart.id == good.cart_id %} <tr> <td>{{good.name}}</td> <td>{{good.count}}</td> <td>{{good.price}}</td> <td> XXX</td> </tr> {% endif %} {% endfor %} {% endif %} {% endfor %} </tbody> </table> <br> <P><strong>Total:</strong></P> </div> </div> </div> {% endfor %} </div> </div> gap-buffer css: .gap-buffer { margin:auto; align:center; } thanks in advance. -
Deploy Django app on Tomcat Apache server
I deployed Django app in Apache server using mod_wsgi. now i need to deploy Django application on Tomcat server using Jython. Suggest me the steps to host if you previously done it. For Production level deployment need to deploy in Tomcat server by creating war Thanks in Advance -
Django authenticate def not triggering loggedin_success and logged_in_fail signal
When i do authentication by function from django.contrib.auth import authenticate Djnago is not triggering success/fail signal, if i use the function from django.contrib.auth import login it will trigger as expected . basically i want to trigger the signal from following function user = authenticate(username=username, password=password) now i added extra line to my code login(request, user) after adding this , i am getting signal here from django.contrib.auth.signals import ( user_logged_in, user_login_failed, ) How can i get signal just from authenticate def ? i am using this for API -
Thread pools in Django
I have a text file comprising numbers in a format like : 1 2 3 4 5 3 4 5 6 7 I need to find product of sum of numbers i.e sum of numbers of each row and product of each row simultaneously in Django. -
Django mysql connection with options from read_default_file ignoring charset
I've found an odd issue with my Django 1.11/mysql project. If I indicate a specific charset in the OPTIONS section of the DATABASES settings, the db connection is created correctly. If I pass the connection OPTIONS from file with "read_default_file", the connection works but the charset is the default one, not the one I've indicated. Working example: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test', 'USER': 'test', 'PASSWORD': 'test', 'OPTIONS': {'charset': 'utf8mb4'}, } } The result of print connection.get_character_set_info() is: {'name': 'utf8mb4', 'collation': 'utf8mb4_0900_ai_ci', 'comment': 'UTF-8 Unicode', 'mbminlen': 1, 'mbmaxlen': 4} NOT working example: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': os.path.join(SECRET_DIR, 'mysql.cnf'), }, }, } mysql.cnf: [client] database = test user = test password = test default-character-set = utf8mb4 charset = utf8mb4 [mysql] default-character-set = utf8mb4 charset = utf8mb4 I've tried also without the [mysql] part, same result. The result of print connection.get_character_set_info() is: {'name': 'utf8', 'collation': 'utf8_general_ci', 'comment': 'UTF-8 Unicode', 'mbminlen': 1, 'mbmaxlen': 3} Any clues? -
Uploading multiple files and displaying progress bar
I'm working on a project (in Django) where I have created a page to add data information about a file and then add the file itself.Initial view of the page When 'More datasets' button is clicked, it adds another field to upload another file.Page after activating 'More datasets' This can be done to attach as many files as the end-user wants in one go. What I need is to upload all the attached files once 'Upload data-sets' is clicked and individual progress bar should be displayed. So far, I have run through multiple tutorials but came kinda close using Vitor Freitas's tutorial. JS code : $(function(){ /*$("#add_new_dataset").click(function(){ $(".file").click(); });*/ $(".file").fileupload({ dataType: 'json', sequentialUploads: true, /* Send the files one by one */ start: function(e){ /* When the upload process starts, show the modal */ $("#modal-progress").modal("show"); }, stop: function(e){ /* When the upload progress finalizes, hide the modal */ $("#modal-progress").modal("hide"); }, progressall: function(e, data){ /* Update the progress bar */ var progress = parseInt(data.loaded / data.total * 100, 10), strProgress = progress + "%"; $(".progress-bar").css({"width": strProgress}); $(".progress-bar").text(strProgress); }, done: function(e, data){ if(data.result.is_valid){ $("#gallery tbody").prepend( "<tr><td><a href='" + data.result.url + "'>" + data.result.name + "</a></td></tr>" ); } } }) }); Template code … -
Context error while testing RESTful API URL in Django
Dear community and forum, I am in charge of developing RESTful API URLs for a project I am in charge of. However, when it comes to testing I have got that error: self = HyperlinkedIdentityField('api:request') value = <ResourceRequest: JoKLLwwKqxrkrwWmcjOWzIscGzpsbgWJqRAOZabnwxQpiEDRfifeZhvzpRRp...ewyOFcaQVhchYNVIhUoiWBzKMrFYvYQBMNRZsLFfOZSjclHUXwyXZQHxjMtbHvWefMIlyZqvTvXqiu> def to_representation(self, value): assert 'request' in self.context, ( "`%s` requires the request in the serializer" " context. Add `context={'request': request}` when instantiating " "the serializer." % self.__class__.__name__ ) E AssertionError: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer. /usr/lib/python2.7/site-packages/rest_framework/relations.py:351: AssertionError The serialiser is (sorry for the ugly code so far): class ResourceRequestSerializer(serializers.ModelSerializer): # context = self.kwargs.get('context', None) # request = kwargs['context']['request'] # print(kwargs) view_name = 'api:request' url = serializers.HyperlinkedIdentityField(view_name) # print(self) # url = URLField(view_name=view_name, read_only=True, many=True) # url = serializers.SerializerMethodField() support_level = serializers.SerializerMethodField() originator = BriefUCLProfileSerializer(source='originator.ucl_profile') sponsor = BriefUCLProfileSerializer() versioned_dependencies = serializers.StringRelatedField(many=True) types_of_work = serializers.StringRelatedField(many=True) previous = serializers.SerializerMethodField() status_history = RequestStatusChangeSerializer(many=True) For the test: # Change the status through a POST request response = self.app.post( reverse( 'api:request', args=[request1.pk], ), params={ 'context': request1, 'format': 'json', 'status': ResourceRequest.STATUS_APPROVED, }, # context=request1, headers=self.auth_headers, ) I am still wondering if the context has to be passed from within the serialiser or from the test. Any help greatly … -
Method object is not subscriptable(django)
I have the following code in my tasks.py @shared_task(bind=True) def my_task(self, seconds, account_name): progress_recorder = ProgressRecorder(self) result = [] tweet_list = [] pprint(self) pprint(seconds) pprint(account_name) for i in range(seconds): # pprint(self) # pprint(seconds) # pprint(account_name) timeline = api.GetUserTimeline(screen_name=account_name, include_rts=True, trim_user=True, exclude_replies=True, count=2) time.sleep(1) result = result + timeline progress_recorder.set_progress(i + 1, seconds) if(result == []): return None else: pprint(type(result)) tweet_id = tweet['id'] tweet_id ='463440424141459456' embReqUrl = 'https://publish.twitter.com/oembedurl=https://twitter.com/Interior /status/'+tweet_id embResp = requests.get(embReqUrl) pprint(embResp.status_code) pprint(embResp.json()) pprint(tweet_id) This is the error in the traceback: [2020-02-20 21:53:13,951: WARNING/ForkPoolWorker-4] <@task: hello.tasks.my_task of tasks at 0x1048e5208> [2020-02-20 21:53:13,951: WARNING/ForkPoolWorker-4] 8 [2020-02-20 21:53:13,952: WARNING/ForkPoolWorker-4] 'alvin_tung' [2020-02-20 21:53:25,843: ERROR/ForkPoolWorker-4] Task hello.tasks.my_task[7ada7f14-a0c5-41e6-b987-6aad7161a6c3] raised unexpected: TypeError("'method' object is not subscriptable",) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery/app/trace.py", line 382, in trace_task R = retval = fun(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery/app/trace.py", line 641, in __protected_call__ return self.run(*args, **kwargs) File "/Users/alvintung/rndtwitr/hello/tasks.py", line 51, in my_task pprint(type(result)) TypeError: 'method' object is not subscriptable I can't figure out why exactly this error message is happening. Any help would be greatly appreciated! -
How to post data from google books API to your Book model using Django
I know this is my first question and I wouldn't be like writing it here, but I have problem which I couldn't handle for 2 days now. I am writing an app in Django, and my goal is to handle a requests from google books API and display books in template which I did. I wrote function like this services.py from googleapiclient.discovery import build import json def get_books_data(query): """Retriving data from google books API""" service = build('books', 'v1', developerKey=API_KEY ) request = service.volumes().list(q=query) response = request.execute() book_list = [response['items'][item]['volumeInfo'] for item in range(len(response['items']))] return book_list I get list of key:value paris representing ten books from API. I passed them into template like this views.py def search(request): query = request.GET.get('q') books = get_books_data(query) context = { 'books': books } return render(request, 'books_list.html', context) This is how book_list.html looks like. list_book.html {% extends 'base.html' %} {% load static %} {% block content%} {% for book in books %} <div class="row"> <div class="col-lg-8 mx-auto"> <ul class="list-group shadow"> <li class="list-group-item"> <div class="media align-items-lg-center flex-column flex-lg-row p-3"> <div class="media-body order-2 order-lg-1"> <h5 class="mt-0 font-weight-bold mb-2">{{ book.title }}</h5> <p class="font-italic text-muted mb-0 small">{{ book.subtitle }}</p> {% for identifier in book.industryIdentifiers %} <p class="font-italic text-muted mb-0 small">{{ … -
Query distinct values Django with MySql and keep foreign key relation
I have two tables in a MySQL database. One table with distinct vessels and one table with locations of that vessels with a foreign key relation (parents: vessels, children: locations). Now I want to show in a template al the distinct vessels from the table with the locations. Unfortunatally the distinct does not work with MySQL and if I use the values() then I lose the foreign key relation. How can I fix this? -
Django, exclude from main list, but viewable from django filter
I'm trying to add an archive section to my site, though when I say archive, I mean just not visible in the main list view that is the home page, the site is small and the projects are just small amounts of text so space and optimization are never going to be needed. I use django-filter to search through projects by department(Area in my code), and "Archive" is down as one of the departments. I've tried using exclude in the queryset, but of course that just removes any projects with area="Archive" completely so that the "Archive" section is empty. How can I get archived projects removed from the main list view but searchable via the filter. View: def project_list_view(request): project_list = Project.objects.annotate( display_date = models.Case( models.When(models.Q(staff_trials__isnull=True) | models.Q(timeline_switch=False), then=models.F('launch')), models.When(models.Q(staff_trials__isnull=False) & models.Q(timeline_switch=True), then=models.F('staff_trials')), output_field=models.DateField(), ) ).exclude(area='1').order_by('-slip', 'display_date') project_filter = ProjectFilter(request.GET, queryset=project_list) return render( request, 'project_portal/project_list.html', {'filter': project_filter} ) filter: class ProjectFilter(django_filters.FilterSet): class Meta: model = Project fields = ['area', 'user'] For clarity, Area has it's own Model with a foreign key to the Project model, and the departments are just entries in the database. The above code kind of does what I want, but as mentioned before makes archived projects … -
Extend Group model from django.contrib.auth.model, remove unique constarint on name and add unique_together name, organization fields
I'm trying to extend the django Group model and organization field to it for creating permission based roles specific to organization. Basically I want to remove the unique constraint on the name field, add a field called organization, and make name and organization unique together. I tried this class MyGroup(Group): name = models.CharField(max_length=200) organization = models.ForeignKey(Organization) class Meta: unique_together = ('name', 'organization',) I am getting error users.MyGroup.name: (models.E006) The field 'name' clashes with the field 'name' from model 'auth.group'. -
Django REST framework - Comment User Username
Im working on a django project, and I have a model that looks like this: class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1,on_delete=models.CASCADE) slug = models.SlugField(unique=True,null=True, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') parent = models.ForeignKey("self", null=True, blank=True,on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) objects = CommentManager() def __str__(self): return str(self.user.username) I use this serializer: class CommentDetailSerializer(ModelSerializer): user = SerializerMethodField() replies = SerializerMethodField() class Meta: model = Comment fields = [ 'user', 'content', 'replies', 'timestamp' ] def get_user(self,obj): return str(obj.user.username) def get_replies(self,obj): if obj.is_parent: return CommentChildSerializer(obj.children(),many=True).data for this view: class CommentDetailApiView(RetrieveAPIView): queryset = Comment.objects.all() serializer_class = CommentDetailSerializer lookup_field = 'slug' this is the PostSerializer I use, class PostSerializer(ModelSerializer): user = SerializerMethodField() comments = SerializerMethodField() class Meta: model = Post fields = [ 'user', 'title', 'content', 'comments' ] def get_user(self,obj): return str(obj.user.username) def get_comments(self,obj): comments_qs = Comment.objects.filter_by_instance(obj) comments = CommentSerializer(comments_qs, many=True).data return comments and this is what I get in the PostDetailAPIView: { "user": "abc", "title": "blabla", "content": "bla", "comments": [ { "user": 1, "content": "hey", "timestamp": "2020-02-18T00:07:29.932850Z" } ] } I get the username of the comment user only in the CommentDetailApiView. How do I get the comment user username instead of its id in the PostDetailView? … -
Django Model field choices
I have two models One is Organisation other is user I want add one field in Organisation suppose manager having choices gathered from the user model based on certain condition but user model itself has the Organisation as the foreign key How can I do this -
How to get the arguments of a test mock call
I want to loop through the calls and then the arguments of a call_args_list. So i am trying the following: @mock.patch('requests.post') def test_create(self, rp): .... for call in rp.call_args_list: # how to get the args of call object which is type of <class 'mock._Call'> If i print the call i get the following: call('http://localhost:800/api/v1/testcreate/', json={'id': 'd089a0a49407480dab9cc9bd8738f064', 'session_id': 'foo', 'user_id': 5, 'username': 'foo', 'tracking_ref': '96bc8d6a985642d08ff5e00e22bf0f5a', 'action_datetime': '2020-02-20T09:48:17.974435', 'status': 'S', 'field_change_records': [], 'entity_type': 'titlecomponentidentitycredential', 'entity_code': '77-1', 'action': 'CREATED'}, headers={'x-auth-secret': '659b2c4f604a4bf39114c73b3c1c828d'}, verify=False, timeout=5.0) How can i get the first arg which is 'http://localhost:800/api/v1/testcreate/' and the json args as well -
Redefining output of builtin loggers from console to file
I am trying to redefine django's built-in loggers output from console to file for this purpose in settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()':'django.utils.log.RequireDebugFalse', }, 'require_debug_true':{ '()':'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, 'null': { 'class': 'logging.NullHandler', }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'file': { 'level':'DEBUG', 'class':'logging.FileHandler', 'filename':os.path.join(BASE_DIR,'logs/log') } }, 'loggers': { 'django': { 'handlers': ['file'], }, 'django.request': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': False, }, 'django.security': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': False, }, 'py.warnings': { 'handlers': ['console','file'], }, } } for testing output i created in views.py file the following view import logging from django.http import HttpResponse logger = logging.getLogger(__name__) def main_view(request): logger.error('Test Error') logger.warning('Test warning') logger.info('Test Info') logger.debug('Test Debug') logger.critical('Test critical') return HttpResponse('Hello') Above view setup for main page. After running server python manage.py runserver and visit main page http://127.0.0.1:8000 i see in console (env) $ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). February 20, 2020 - 12:58:40 Django version 3.0.1, using settings 'authexample.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Test Error Test warning Test critical i didn't expect that … -
'LoginForm' object has no attribute 'cleaned_data'
I'm trying to make a Login but it doesn't work. the error is form.is_valid() return False and when I try if not form.is_valid(): ... then error showing 'LoginForm' object has no attribute 'cleaned_data' I can't figure out out is the problem. user/forms.py class LoginForm(forms.Form): email = forms.EmailField(widget=forms.EmailInput( attrs={'style': 'width:100%; height:100%;'})) password = forms.CharField(widget=forms.PasswordInput( attrs={'style': 'width:100%; height:100%;'})) def __init__(self, request=None, *args, **kwargs): self.request = request super(LoginForm, self).__init__(*args, **kwargs) self.fields['email'].label = "이메일" self.fields['password'].label = "비밀번호" def clean(self): super().clean() email = self.cleaned_data.get("email") password = self.cleaned_data.get("password") try: user = models.User.objects.get(email=email) if user.check_password(password): return self.cleaned_data else: self.add_error("password", forms.ValidationError( "비밀번호가 틀렸습니다.")) except models.User.DoesNotExist: self.add_error("email", forms.ValidationError( "존재하지 않는 계정입니다.")) users/views.py class LoginView(mixins.LoggedOutOnlyView, View): def get(self, request): form = forms.LoginForm(request.POST) return render(request, "users/login.html", {"form": form}) def post(self, request): form = forms.LoginForm(request.POST or None) print(form.is_valid()) if form.is_valid(): email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") get_user_name = user_models.User.objects.get(email=email) user = authenticate( request, username=get_user_name, password=password) if user is not None: login(request, user) return redirect(reverse("cores:home")) else: return render(request, "users/login.html", {"form": form}) -
DRF: Customising Exception Messages from the API
I'm starting to dive into DRF a little deeper of late, and I was wondering I would like to start customising the error messaging that gets return via the API for incorrect permissions, I'd like to wrap a little extra detail. For example, if authentication credentials were not provided for an endpoint that is permission restricted, the API returns: { "detail": "Authentication credentials were not provided." } Which comes from line 171 from the rest_framework.exceptions: https://github.com/encode/django-rest-framework/blob/master/rest_framework/exceptions.py. Really, I'd like this to be consistent with the { "success": false, "message": "Authentication credentials were not provided.", "data": null } So, I assume I now need to begin customising my own exceptions. How best should I go about doing this? Perhaps it has some tie in with default_error_messages = {} inside the serializer ...