Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Value returned by property method in django not getting stored in database. How to make this possible?
In my models.py file I have a property method which returns a value and I need to store that value in the database field. ` class bug(models.Model): ...... ....... id_of_bug = models.CharField(max_length=20, blank= False, null= False) @property def bug_id(self): bugid = "BUG{:03d}".format(self.pk) self.id_of_bug = bugid return bugid Tried to store the value in database using self method, but not working. -
Error : strptime() argument 1 must be str, not int
I am trying to substract two times and getting an error. In below total error is coming up if result[0]['outTime'] != None: type = "bothPunchDone" FMT = '%H:%M:%S' total= datetime.strptime(result[0]['outTime'], FMT) - datetime.strptime(result[0]['inTime'], FMT) I tried but not able to solve the issue. -
Cannot use serializer when ManyToManyField is empty
I am utilizing PrimaryKeyRelatedField to retrieve and write M2M data. My models.py: class Task(MP_Node): ... linked_messages = models.ManyToManyField('workdesk.Message', blank=True, related_name='supported_tasks') (MP_Node is an abstraction of models.Model from django-treebeard). My serializers.py: class TaskSerializer(serializers.ModelSerializer): ... linked_messages = serializers.PrimaryKeyRelatedField(many=True, required=False, allow_null=True, queryset=Message.objects.all()) class Meta: model = Task fields = [..., 'linked_messages'] My api.py: class TaskViewSet(ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer def create(self, request): serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): print(serializer.data) With other fields, if the field is set to null=True in the models, or required=False on the serializer, I don't need to include them in the data to instantiate the serializer. However, these fields do not seem to work this way, instead returning KeyError: 'linked_messages' when serializer.data is called. As a workaround I tried adding setting allow_null, as indicated by the docs, and then manually feed it a null value: request.data['linked_messages'] = None but this returns as 404: "linked_messages":["This field may not be null."] If I set it to a blank string: "resources":["Expected a list of items but got type \"str\"."] If I set it to an empty list, serializer.data again gives me an error: `TypeError: unhashable type: 'list'` It seems to have me any way I turn. What am I not understanding … -
Django: data from Views.py not displaying in HTML page
My home.html in div where I called the { data } to display in HTML <div id= "main"> <h1> DATA SCRAPPER</h1> <h2>Header Data from html Page</h2> { data } </div> The local host shows But in terminal it is showing the scrapped data Views.py where def home(request): soup= None URL = 'https://www.abc.html' page = requests.get(URL) soup = bs(page.content, 'html.parser') print(soup.h1.text) head=soup.h1.text return render(request, 'home.html', {'data': head}) -
Django - How to filter ID to post to specific item
I am trying to update only one item and one field at a time in my DB. Whenever I update the item, it updates all but I am struggling with getting the ID (to set the ID equal to the DB ID). I am using Crispy Forms. A user will add a new issue and I am only trying to update the "issue_status" field one item at a time. Issue status is the only item being updated in the form. views.py get_issues = DevIssues.objects.get(id=pk) if request.method == 'POST' and 'updateissue' in request.POST: update_issue_form = UpdateProjectIssues(request.POST, instance=get_issues) if update_issue_form.is_valid(): content = request.POST.get('issue_status') content2 = request.POST.get('issueid') DevIssues.objects.filter(pk=content2).update(issue_status=content) return redirect('/projects') templates <form name="updateissue" class="row g-3" method="post"> {% csrf_token %} <hr> <div class="col-6"> <label style="margin-bottom: 8px;">Project ID</label> <input class="form-control" type="text" name="issueid" value="{{issue.id}}" aria-label="Available" disabled readonly> </div> <div class="col-6"> <label style="margin-bottom: 8px;">Project ID</label> <input class="form-control" type="text" value="{{issue.issue}}" aria-label="Issue" disabled readonly> </div> <div class="col-10"> <label style="margin-bottom: 8px;">Project ID</label> <input class="form-control" type="text" value="{{issue.issue_desc}}" aria-label="Available" disabled readonly> </div> <div class="col-6"> <label style="margin-bottom: 8px;">Project ID</label> <input class="form-control" type="text" value="{{issue.issue_code}}" aria-label="Available" disabled readonly> </div> <div class="col-6" name="updateissue"> {{ update_issue_form.issue_status|as_crispy_field }} </div> <div class="col-10"> <button type="submit" name="updateissue" class="btn btn-primary">Update</button> </div> </form> Whenever I set DevIssues.objects.filter(pk=17).update(issue_status=content) to a specific number, I can … -
psycopg2.errors.DuplicateTable: relation "django_celery_beat_solarschedule" already exists
While deployment django project I see the following error and not clear what is missing. We deleted previous migrations too before deploying but no change in the result: Apply all migrations: admin, auth, captcha, contenttypes, django_celery_beat, django_celery_results, hitcount, sessions, watson Running migrations: Applying django_celery_beat.0002_auto_20161118_0346...Traceback (most recent call last): File "/home/jenkins/workspace/dev-jk-project/env/lib/python3.10/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "django_celery_beat_solarschedule" already exists Please let me know if you are able to fix this? -
Get First and Last Related Object for Django Rest API
I have Django Rest API serializers based on 2 models, Book and Chapter In the Book serializer I want 2 custom fields first_chapter last_chapter Each having objects of model Chapter as you can understand from the field name first and last objects order by published_at field I tried something like below to get the last chapter class LastChapterField(serializers.RelatedField): def get_queryset(self): return core_models.Chapter.objects\ .filter(comic=M.OuterRef("pk"))\ .select_related("number")\ .order_by("-published_at")[:1] But I don't see the last chapter included in my results even though it is explicitly mentioned in fields of Book Serializer I want the complete object in returning result and I want to be able to use order by on one of these nested fields (first_chapter or last_chapter) of Chapter model object. -
Hey is it possible to call one serializer class insider another in drf? Without having any foreign key relationship
class AuthorSerializer(ModelSerializer): class Meta: model = Author fields = "__all__" class BookSerializer(ModelSerializer): class Meta: model = Book fields = "__all__" I want to get data of AuthorSerializer in BookSerializer. Is it Possible? -
CKEditor doesn't save data
I'm using CKEditor for a form. In the admin it works fine, but when using it in the ModelForm of a CreateView the editor doesn't save data. As in the official docs, with this code: class EventForm(forms.ModelForm): description = forms.CharField(widget=CKEditorWidget()) image = forms.ImageField(widget=forms.ClearableFileInput(), required=False) class Meta: model = Event fields = ['title', 'description', 'type', 'start_date', 'end_date', 'fee'] And this html: <div> <form hx-post="{{ request.path }}" enctype="multipart/form-data" class="modal-content"> {% csrf_token %} <div class="modal-header"> <h1>Create new event</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> {{form.media}} {{form.as_p}} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button> <input type="submit" value="Submit"> </div> </form> </div> It won't let me submit the form as it will keep saying that the description field is required. Trying to add the CKEditor widget field in the init method, with this code: class EventForm(forms.ModelForm): image = forms.ImageField(widget=forms.ClearableFileInput(), required=False) class Meta: model = Event fields = ['title', 'description', 'type', 'start_date', 'end_date', 'fee'] def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) self.fields['start_date'].widget = forms.SelectDateWidget() self.fields['end_date'].widget = forms.SelectDateWidget() self.fields['description'].widget = CKEditorWidget() The form will be sent, and the instance created. However, the 'description' field will be empty even if I enter some content. This is my view: class CreateEvent(LoginRequiredMixin, CreateView): model = Event form_class = … -
Page not found (404) upon Heroku Deployment
I have been having difficulties getting to deploy my Heroku app with my Django and React app. The error is as follows: Page not found (404) Request Method: GET Request URL: https://true-friends-404.herokuapp.com/login/ Using the URLconf defined in truefriends.urls, Django tried these URL patterns, in this order: admin/ ^authors/$ [name='authors-list'] ^authors\.(?P<format>[a-z0-9]+)/?$ [name='authors-list'] ^authors/(?P<pk>[^/.]+)/$ [name='authors-detail'] ^authors/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='authors-detail'] ^$ [name='api-root'] ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] ^posts/$ [name='posts-list'] ^posts\.(?P<format>[a-z0-9]+)/?$ [name='posts-list'] ^posts/(?P<pk>[^/.]+)/$ [name='posts-detail'] ^posts/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='posts-detail'] ^$ [name='api-root'] ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] swagger/ [name='schema-swagger-ui'] api/ api/auth/ friendrequest/ [name='friend_request_list'] friendrequest/accept/<int:fr_id>/ [name='friend_request_accept'] friendrequest/reject/<int:fr_id>/ [name='friend_request_reject'] friendrequest/<int:author_id>/ [name='friend_request_to_user'] authors/<int:author_id>/ authors/<int:author_id>/ posts/<int:post_id>/ comments/<int:comment_id>/ authors/<int:author_id>/inbox/ followers/ [name='followers_list'] following/ [name='following_list'] unfollow/<int:user_id>/ [name='unfollow_by_user_id'] unfriend/<int:user_id>/ [name='unfriend_by_user_id'] withdraw/<int:user_id>/ [name='withdraw_by_user_id'] truefriends/ [name='true_friends_list'] posts/<int:post_id>/ authors/<int:author_id>/ currentauthor/ ^media/(?P<path>.*)$ The current path, login/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Here is the urls.py file # import ... post_router = routers.DefaultRouter() post_router.register(r'posts', PostView, 'posts') logged_in_post_router = routers.DefaultRouter() logged_in_post_router.register(r'posts', LoggedInPostView, 'my-posts') author_router = routers.DefaultRouter() author_router.register(r'authors', AuthorView, 'authors') post_like_router = routers.DefaultRouter() post_like_router.register(r'likes', PostLikeView, 'post-likes') author_like_router = routers.DefaultRouter() author_like_router.register(r'likes', AuthorLikeView, 'author-likes') post_comment_router = routers.DefaultRouter() post_comment_router.register(r'comments', PostCommentView, 'post-comments') author_comment_router = routers.DefaultRouter() author_comment_router.register(r'comments', AuthorCommentView, 'author-comments') schema_view = get_schema_view( openapi.Info( # add your swagger doc title … -
Why my conditional statement does not return true?
I'm getting input from html <form class="form" action="{% url 'search' %}" method="POST"> {% csrf_token %} <input type="text" name="input" id="input" style="height: 40px" /> <button type="submit" style="height: 40px; width: 110px; margin-left: 40px" > Filter post </button> and in the views.py def search(request): ... if request.method=='POST': input=int(request.POST.get('input')) # print(type(input)) for field in posts_data: if (input == field['id']): print(field['id']) output['post'] = field return render(request, 'post.html', {'post':output}) else: return render(request, 'post.html', {'posts': posts_data}) so I printed in terminal input got same as I entered and also the type is confirmed integer. I also did print field['id'] and got range of numbers( including same number as I input) so what possibly be the problem? -
ImportError: cannot import name 'Celery' from partially initialized module 'celery' (most likely due to a circular import)
With latest version of celery, in python 3.10.6, I am getting the above error, trace back is as follows. Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/home/biju/Desktop/trial/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/biju/Desktop/trial/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/biju/Desktop/trial/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/biju/Desktop/trial/lib/python3.10/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/home/biju/Desktop/trial/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/biju/Desktop/trial/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/biju/Desktop/trial/lib/python3.10/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/biju/Desktop/trial/lib/python3.10/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/biju/Desktop/trial/lib/python3.10/site-packages/django_celery_beat/models.py", line 10, in <module> from celery import current_app, schedules File "/home/biju/Desktop/trial/celery.py", line 3, in <module> from celery import Celery ImportError: cannot import name 'Celery' from partially initialized module 'celery' (most likely due to a circular import) tried to installing importlib-metadata==4.13.0, but error persists, Django version is … -
login wrong show the messages error but not show out
login wrong username the messages error no show out here is code python def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') try: user = User.objects.get(username=username) except: messages.error(request, 'User does not exist') context = {} return render(request, 'base/login_register.html', context) here is html code {% if messages %} <ul class="messages"> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} -
How to pass URL parameters and get the values with GET request method in Django rest framework
I want to pass url parameters in this format http://localhost:8000/api/projects/?id=2021&a=2&b=3&c=4 and get the values in view function -
Where should I put my sqlalchmey engine/connection object in django?
I have already created a lot of models and query methods by sqlalchemy and now I want to build a website on it to provide services. The problem is I am not sure where to put my engine in django code structure: engine = create_engine("postgresql+psycopg2://scott:tiger@localhost:5432/mydatabase") -
AttributeError: 'NoneType' object has no attribute 'is_nightly'
I've got an error on the expression with below defined function on serializer.py and i have an ordering items with different calculation with posting on nightly basis and once posting. if special_order_item.special_item.is_nightly == True: AttributeError: 'NoneType' object has no attribute 'is_nightly' the error was referred to "if special_order_item.special_item.is_nightly == True:" models.py class SpecialsItem(models.Model): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, related_name="special_items", null=False, blank=False) code = UpperCaseCharField(max_length=50, blank=True, null=True) desc = models.CharField(max_length=100, blank=True, null=True) pms_tran_code = UpperCaseCharField(max_length=50, blank=True, null=True) unit_price = models.DecimalField(max_digits=20, decimal_places=10, default=0) is_nightly = models.BooleanField(default=True) inventory = models.IntegerField(default=0) image = models.ImageField(upload_to='img', blank=True, null=True, default='') serializers.py class SpecialsOrderItemsSerializer(serializers.ModelSerializer): special_item = SpecialItemSerializer(many=False, read_only=True) amount = serializers.SerializerMethodField(method_name='sub_total') class Meta: model = SpecialOrderItems fields = [ 'id', 'reservation', 'special_item', 'qty', 'amount', 'created_by', 'updated_by' ] def sub_total(self, special_order_item:SpecialOrderItems): # definedname : model_object if special_order_item.special_item.is_nightly == True: items_total = special_order_item.qty * special_order_item.special_item.unit_price * special_order_item.reservation.night return items_total else: items_total = special_order_item.qty * special_order_item.special_item.unit_price return items_total Looking a expertise for who have experiencing to figure out a solution -
Is it possible somehow without refreshing the pages on Django to send a request via SSH to a virtual machine running Ubuntu?
Good afternoon, I have a frequently asked question, for example, <button>Check</button> Is it possible somehow without refreshing the page to send a request via SSH to a virtual machine running Ubuntu? For example: The csgo server is on a permanent machine, it has possible options: IP: 192.168.44.122/94.32.143.84 PORT for SSH: 44 USER NAME: test PASSWORD: test Django is on local machine 127.0.0.1:8000 or localhost:8000. The csgo server is started with "./csgoserver start". Is it possible somehow to send a request with "./csgoserver start" to the local machine, on the click of a button on the page, to start the server? I searched for information and did not find it. With the help of ajax, if I understand correctly, it is possible to send a request only if there are servers on the same machine, right? I would be grateful for the answer where should I look, what to study, so that I can implement this idea. One guy suggested that you can look towards REST, but I can't figure out how to implement what I need through REST. -
Why I cannot connect my order error page to my Django website?
I'm trying to build an ecommerce site, but I don't understand how you can connect the order error page to the website. I've tried adding a window.location.replace to the JavaScript file after the .then function in the result.error section. }).then(function(result) { if (result.error) { console.log('payment error') console.log(result.error.message); window.location.replace("http://127.0.0.1:8000/payment/error/"); } else { if (result.paymentIntent.status === 'succeeded') { console.log('payment processed') window.location.replace("http://127.0.0.1:8000/payment/orderplaced/"); } } }); }, error: function (xhr, errmsg, err) {}, I've also tried adding an if else function beneath the succeeded. }).then(function(result) { if (result.error) { console.log('payment error') console.log(result.error.message); } else { if (result.paymentIntent.status === 'succeeded') { console.log('payment processed') window.location.replace("http://127.0.0.1:8000/payment/orderplaced/"); } else { if (result.paymentIntent.status === 'failed') { console.log('payment error') window.location.replace("http://127.0.0.1:8000/payment/error"); } } } }); }, error: function (xhr, errmsg, err) {}, I've tried editing the Error class to a define, but it didn't work out within the payment views.py. I've tried creating a new define called error and made the orders urls.py connect to the new error defined, but nothing happened when I try to put a declined credit card information. My payment views.py: @csrf_exempt def stripe_webhook(request): payload = request.body event = None try: event = stripe.Event.construct_from( json.loads(payload), stripe.api_key ) except ValueError as e: print(e) return HttpResponse(status=400) if event.type == … -
How to get raw value of the QuerySet
I'm trying to return the raw value "Alberto Santos", but in my HTML, the function returns a array. <QuerySet [<Funcionarios: Alberto Santos>]> My function "funcionarios_nome" class ListaFuncionariosView(ListView): model = Funcionarios template_name = '../templates/funcionarios/lista_funcionarios.html' paginate_by = 10 ordering = ['FuncionarioCartao'] queryset = Funcionarios.objects.filter(EmpresaCodigo=1) def funcionarios_nome(self): funcionarios = Funcionarios.objects.filter(FuncionarioNome='Alberto Santos') return funcionarios MY HTML <p>{{ view.funcionarios_nome }}</p> I Tried to use .values() function, but i'dont know how to use -
In Haystack logical operators give unexpected results
How to use logical operators in the solr + haystack bundle? At the moment, the search in my system is done something like this: I get the field from the post data I give them to the filter(text=post[query]) function It doesn't work, I tried additionally giving it to the Auto Query function, which also didn't work. request example "covid OR coronavirus” I tried additionally giving it to the Auto Query function, which also didn't work. request example "covid OR coronavirus” -
Celery not working on EC2 instance in production
i've been trying to deploy a django appllication on aws ec2, i've been successfull at deploying it so far except getting celery to work,i tried testing the celery worker by trying to run it on the shell temporarily with this command: celery -A ReelShopBackend worker -l INFO which works in locally and also in docker but when i run it on the ec2 instance it gives this error: Traceback (most recent call last): File "/home/ubuntu/Renv/bin/celery", line 8, in <module> sys.exit(main()) File "/home/ubuntu/Renv/lib/python3.10/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/home/ubuntu/Renv/lib/python3.10/site-packages/celery/bin/celery.py", line 217, in main return celery(auto_envvar_prefix="CELERY") File "/home/ubuntu/Renv/lib/python3.10/site-packages/click/core.py", line 1130, in __call__ return self.main(*args, **kwargs) File "/home/ubuntu/Renv/lib/python3.10/site-packages/click/core.py", line 1055, in main rv = self.invoke(ctx) File "/home/ubuntu/Renv/lib/python3.10/site-packages/click/core.py", line 1657, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/ubuntu/Renv/lib/python3.10/site-packages/click/core.py", line 1404, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/ubuntu/Renv/lib/python3.10/site-packages/click/core.py", line 760, in invoke return __callback(*args, **kwargs) File "/home/ubuntu/Renv/lib/python3.10/site-packages/click/decorators.py", line 26, in new_func return f(get_current_context(), *args, **kwargs) File "/home/ubuntu/Renv/lib/python3.10/site-packages/celery/bin/base.py", line 134, in caller return f(ctx, *args, **kwargs) File "/home/ubuntu/Renv/lib/python3.10/site-packages/celery/bin/worker.py", line 343, in worker worker = app.Worker( File "/home/ubuntu/Renv/lib/python3.10/site-packages/celery/worker/worker.py", line 99, in __init__ self.setup_instance(**self.prepare_args(**kwargs)) File "/home/ubuntu/Renv/lib/python3.10/site-packages/celery/worker/worker.py", line 120, in setup_instance self._conninfo = self.app.connection_for_read() File "/home/ubuntu/Renv/lib/python3.10/site-packages/celery/app/base.py", line 808, in connection_for_read return self._connection(url or self.conf.broker_read_url, **kwargs) File "/home/ubuntu/Renv/lib/python3.10/site-packages/celery/app/base.py", line 867, in … -
Can I get auto-generated signin forms in dj-rest-auth, instead of manually writing an html form?
I'm adding dj-rest-auth to my django application. It's a traditional Django app rather than an SPA -- no react etc. I looked to the demo app hoping to basically use those patterns. However, I'm disappointed to see that the templates have hard-coded forms, for example https://github.com/iMerica/dj-rest-auth/blob/master/demo/templates/fragments/signup_form.html . These forms should be obtainable from django rest framework serializers, right? For example in my own app, with no custom templates, if I go to http://127.0.0.1:8000/dj-rest-auth/registration/ I get an autogenerated API form: Is it possible to build my signin view form from that drf serializer? Maybe there's already a view I can use? Basically I want to take this API endpoint and make it work for GET... Update: Update: I'm able to generate the form by getting RegisterSerializer from from dj_rest_auth.registration.app_settings, adding it to template context, and rendering it using {% render_form RegisterSerializer %}, so I think I'm on the right track. -
How to run django manage.py commands when using docker compose to avoid issues with permissions
I have created a Django, Docker, Postgres project, based on the example on Docker's Github. On my Linux machine I have 2 Docker containers, one for Django and one for Postgres. When I run manage.py commands using docker compose, such as docker compose run web django-admin startapp auth, the directory and files created are owned by root. This means I need to change the ownership each time I do this. I use sudo chown -R. If I don't change ownership, when I try to edit a file generated by manage.py, I get an error message saying I have insufficient privileges and that I need to retry as superuser. When I try to run this command without docker compose, e.g. python3 manage.py startapp auth, I get ModuleNotFoundError: No module named django. Did you forget to activate a virtual environment? Is it possible for the output of the manage.py commands to be owned by me? I know that the docker process is owned by root... -
DRF display verbose message in error message for a custom exception handler
Here is my custom exception handler: def my_exception_handler(exc, context): response = exception_handler(exc, context) if response is not None: error_code = 'unknown' if hasattr(exc, 'default_code') : error_code = exc.default_code message = '' if hasattr(exc, 'default_detail'): message = exc.default_detail error = { "error":response.data, "code":error_code, 'message':message, } response.data = error return response The problem here is whenever I send bad data I get a response like this: { "error": { "email": [ "Enter a valid email address." ], "phone_number": [ "asd is not a valid phone" ] }, "code": "invalid", "message": "Invalid input." } As you can see the message is just "Invalid input." But I want to get a verbose message here. Any idea about it? -
Is there a way to load avatar of each user using static method in Django?
I'm looping through each message which has a particular user which in intern as an image associated with it. <img src="{{message.user.avatar.url}}" /> I want to convert it something like this (which I know is obviously very wrong) <img src="{% static {{message.user.avatar.url}} %}" /> Is there a way to do so where I can find the equivalent working command of the above code?