Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending audio AND text using django to android app
So I have an android app that uses MediaPlayer to load audio from a Django view/URL (by setting the content type to audio/mpeg). However, now I need to get both audio and a json from the view. Is there any way I can achieve this? I tried using multipart but turns out that wasn't the way to go. -
Django rest api expected string or buffer on PATCH
I'm making a Django application, where I am sending requests through rest API. I am using POST and GET and all works pretty well, but when I am trying to use PATCH (as I must firstly upload field "start_time", and then add field "time"), I'm getting following error: match = time_re.match(value) TypeError: expected string or buffer Surely it is about views.py, but I cannot find clear recipe how to do that, thus I don't know where I am wrong. Thank you. Views.py ... elif request.method = 'PATCH': serializer = TABLESerializer(data=request.data, partial=True) if serializer.is_valid(): obj = TABLE.objects.get(start_time=request.data['start_time']) obj.time = serializer['time'] obj.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializers.py class TABLESerilizer(serializers.serializer): start_time = serializers.DateTimeField(format = None, allow_null=True) time = serializers.TimeField(format=None, required=False) models.py class TABLE(models.Model): start_time=models.DateTimeField(primary_key=True) time = models.TimeField(null= True, blank= True, default = '00:00:00') -
Debug Django app on Heroku
How can I debug django app deployed on Heroku. I can not reproduce the issue on local setup and want to drop to pdb in handling request code. Is there a way to connect to the web dyno and step thru the code handling request. Please suggest if there is any alternate way was well. Thanks!! -
'User' object has no attribute 'is_valid'
def register(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] email = request.POST['email'] user = User(email=email, username=username, password=password) if user.is_valid: user.save() context = {'message_good': "god" } else: context = {'message_bad': "bad." } else: context = {'message_bad': "bad" } return render(request, 'register.html', context) please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help -
Django admin add model page. Display objects with only foreign key
I have a Django admin page that displays a list of my model, Event, and allows me add an Event. My Event model has a field with a one to many relationship with a field from another model, Church. My problem is that when I go to add an Event, it allows me to add any church I want. Instead I would like to only return churches filtered by id. This is what I have so far: class EventAdmin(admin.ModelAdmin): exclude = () list_display = ('title', 'start_time', 'end_time') def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "church": kwargs["queryset"] = models.Event.objects.filter(church__parish=request.user.userprofile.associated_parish) return super(EventAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) request.user.userprofile.associated_parish is the id I'm searching on. This returns me an empty list of churches so I am affecting the field, but I'm not sure where it's failing. -
Django - multiple static file directories javascript not loading
I have a Django project consisting of 3 apps - Survey, Django-admin and Chartsjs (installed through nodejs). The directory structure is: Project survey/ (urls, admin...) views/ analytics_view.py models/ static/ templates/ survey analytics.html ...etc/ Bootstrap_admin/ static/ admin/ css/ boostrap_admin img/ js/ templates/ ...etc node_modules chart.js/ dist/ Chart.js chartjs-color/ ....etc/ When I built Boostrap-Admin, I was left with the following in my settings.py file: MEDIA_URL = '/media/' STATIC_URL = '/bootstrap_admin/static/' MEDIA_ROOT = os.path.join(ROOT, 'media') STATIC_ROOT = os.path.join(ROOT, 'static') STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) STATICFILES_DIRS = [ os.path.normpath(os.path.join(ROOT, '..', "survey", "static")), In analytics_view.py I have a class: class AnalyticsView(TemplateView): template_name = "survey/analytics.html" And in analytics.html I have the code example provided by chartsjs: {% block extrahead %} <script src="../../../node_modules/chart.js/dist/Chart.js" type="text/javascript"></script> <script> var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, … -
How to fix problems with querystring in show_more tag?
I use pagination on scroll of django-el-pagination application in my own project. django==django==1.11.5 django-el-pagination==3.1.0 When user scroll to the last page in terminal I notice next Traceback. It seems to me that something wrong with querystring which in show_more tag. Do you have any ideas how to fix it?! P.S. As I said this Traceback happens only when user scroll to the last page. Lets say I have 5 page, so this Traceback happens only when user at last page: http://127.0.0.1:8000/documents/?page=5&querystring_key=page ERROR: Time: [25/Jan/2018 08:37:38] | LevelName: DEBUG | Module: base | Process: 1148 | Thread: 123145435922432 | Message: Exception while resolving variable 'querystring' in template 'documents/documents.html'. Traceback (most recent call last): File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/template/base.py", line 903, in _resolve_lookup (bit, current)) # missing attribute VariableDoesNotExist: Failed lookup for key [querystring] in u"[{'False': False, 'None': None, 'True': True}, {'csrf_token': <SimpleLazyObject: <function _get_val at 0x109034ed8>>}] views.py: from el_pagination.views import AjaxListView class DocumentListView(AjaxListView): context_object_name = 'documents' template_name = "documents/main.html" page_template = 'documents/documents.html' def get_queryset(self): documents = Document.objects.all() return documents documents/main.html: <div class="list-group"> {% include page_template %} </div> documents/documents.html: {% load el_pagination_tags %} {% paginate 20 documents %} {% for document in documents %} {% include "documents/list_template.html" %} {% endfor %} {% show_more %} documents/list_template.html: … -
Djanog Override Default ModelForm Input Wrapper
There are many questions and answers out there for override the widgets and other field properties on a Django Form. My answer is slightly different from what I have been able to find by searching. Inside my form template, I load the form UI elements like this: <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <a class="button icon fa-cancel" href="{% url 'advertising:my-ads' %}">Cancel</a> <button type="submit" class="button icon fa-save">Save</button> </form> All form elements are rendered wrapped in a <p> element. Like this: <p><label for="id_title">Title:</label> <input id="id_title" maxlength="100" name="title" type="text" value="Flamingo T-Shirt Corporation"></p> So my question is: how to change that <p> element to something else? For example i'd like to change it to <div class='some-class'>. Instead of just hard-coding my own HTML template, I would rather override some aspect of the form class. Here is my current form class defnintion: class AdForm(forms.ModelForm): class Meta: model = Ad fields = "__all__" exclude = ['created','modified'] I'm been reading through the docs and still haven't quite found what I am looking for. Any help is greatly appreciated. -
can not remove field from serializer with .pop('field') in create() method - DRF
I'm using Django rest framework. I want to create admin endpoint where the user can add the member with project permission. following is the data coming from the user. { "email" : "name@yopmail.com", "first_name" : "asd", "last_name" : "asd", "projects":[{ "project_id" : 1, "project_role" : 1 }, { "project_id" : 1, "project_role" : 1 }], "position" : "something something" } following is serializer I created to validate and save the data. class ProjectPermissionSerializer(serializers.Serializer): """ Serialiser to hold permissions pair of project_id and role """ project_id = serializers.IntegerField(allow_null=False) project_role = serializers.ChoiceField(PROJECT_ROLES) def create(self, validated_data): print(validated_data) def update(self, instance, validated_data): pass class ProjectMemberSerializer(serializers.ModelSerializer): """ serializer to add new member with projects """ projects = ProjectPermissionSerializer(many=True) email = serializers.EmailField() class Meta: model = User fields = ('first_name', 'last_name', 'email', 'position', 'projects') def create(self, validated_data): permission_data = validated_data.pop('projects') emailstatus = {"email_id": validated_data.pop('email')} emailobj, created = EmailStatus.objects.get_or_create(**emailstatus) validated_data['email'] = emailobj project_member = User.objects.create(**validated_data) return project_member still, after popping the projects from validated_data, I'm getting following error. AttributeError: Got AttributeError when attempting to get a value for field `projects` on serializer `ProjectMemberSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object … -
Django test - models.DoesNotExist: matching query does not exist
I have two test files, test1.py and test2.py. Individually they run fine, but when I try to run them using 'django manage.py test' I get the following error: post.models.DoesNotExist: Post matching query does not exist. One more thing I notice is that, whichever file runs first will work well while the other throws this error (tested this by renaming files). I am using django.test.TestCase. This is the relevant code - test1.py: def setUpTestData(cls): Post.objects.create(...) Post.objects.get(id=1) #Works fine since this file runs first test2.py: def setUpTestData(cls): Post.objects.create(...) Post.objects.get(id=1) #Throws above error I am new to testing in django so I think I'm missing something basic here. -
How to close a site for django?
I want to restrict access to a django site, how to restrict it to an IP adress or make it to open by login and password should I use htaccess or code it inside django itself? -
Invalid block tag: 'bootstrap_icon', expected 'elif', 'else' or 'endif'
I tried a lot but couldn't able to fix this error. TemplateSyntaxError at /myrestaurants/restaurants/1/ Invalid block tag: 'bootstrap_icon', expected 'elif', 'else' or 'endif' Request Method: GET Request URL: http://127.0.0.1:8000/myrestaurants/restaurants/1/ Django Version: 1.8.7 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag: 'bootstrap_icon', expected 'elif', 'else' or 'endif' Exception Location: /usr/lib/python2.7/dist-packages/django/template/base.py in invalid_block_tag, line 395 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/vaibhav/Desktop/projects/myrecommendations', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/vaibhav/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/gtk-2.0'] Server time: Thu, 1 Feb 2018 16:53:44 +0000 Actually I wanted to display a table in which 1st column should should stars given by the customers.Here is my part of code where I m getting error :- {% if restaurant.restaurantreview_set.all != 0 %} <table class="table table-striped table-bordered"> <thead> <tr> <th>Rating</th> <th>Comment</th> <th>User</th> <th>Date</th> </tr> </thead> <tbody> {% for review in restaurant.restaurantreview_set.all %} <tr> <td>{% if review.rating == 1%}{% bootstrap_icon "star" %} {% elif review.rating == 2%}{% bootstrap_icon "star" %}{% bootstrap_icon "star" %} {% elif review.rating == 3%}{% bootstrap_icon "star" %}{% bootstrap_icon "star" %}{% bootstrap_icon "star" %} {% elif review.rating == 4%}{% bootstrap_icon "star" %}{% bootstrap_icon "star" %}{% bootstrap_icon "star" %}{% bootstrap_icon "star" %} {% elif review.rating == 5%}{% bootstrap_icon "star" %}{% bootstrap_icon "star" %}{% bootstrap_icon "star" %}{% bootstrap_icon "star" … -
Why my Foreign keys are not working they should be?
I am trying to write some queries which fetch average and count of ratings which are in my ConsumerServicerequestFeedback class Model. These rating should be based on some parameters such as BrandName, ProductName, ServiceCentre Names and Cities. I joined each of these models by Foreign keys but they aren't working they should be. Models.py from __future__ import unicode_literals from django.db import models class Brand(models.Model): bbrandid = models.BigAutoField(db_column='BrandID', primary_key=True) # Field name made lowercase. bbrandname = models.CharField(db_column='BrandName', max_length=50, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'brand' def __str__(self): return self.bbrandname class ConsumerProduct(models.Model): cpconsumerproductid = models.BigAutoField(db_column='ConsumerProductID', primary_key=True) # Field name made lowercase. cpconsumerid = models.BigIntegerField(db_column='ConsumerID', blank=True, null=True) # Field name made lowercase. cpbrandid = models.ForeignKey(Brand, on_delete=models.CASCADE, db_column='BrandID', related_name='cpbrand') # Field name made lowercase. cpproductid = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='ProductID', related_name='cpproduct') # Field name made lowercase. class Meta: managed = False db_table = 'consumer_product' def __str__(self): return str(self.cpconsumerproductid) class ConsumerServicerequest(models.Model): csrconsumerservicerequestid = models.BigAutoField(db_column='ConsumerServiceRequestID', primary_key=True) # Field name made lowercase. csrsource = models.CharField(db_column='Source', max_length=50, blank=True, null=True) # Field name made lowercase. csrconsumerid = models.BigIntegerField(db_column='ConsumerID', blank=True, null=True) # Field name made lowercase. csrconsumerproductid = models.ForeignKey(ConsumerProduct, on_delete=models.CASCADE, db_column='ConsumerProductID', related_name='csrconsumerproduct') # Field name made lowercase. csrsoldplanid = models.BigIntegerField(db_column='SoldPlanID') # Field name … -
django page_attribute in view.py
Hi i need get slug and others parameters of Django Page: In the template the matter is simple: {% page_attribute "slug" %} But I need get this value from the view.py How can I do it. Thank you for help. My views.py from django.shortcuts import render from django.shortcuts import render,render_to_response from django.template import RequestContext def index(request): return render_to_response('template.html', locals(), context_instance=RequestContext(request)) -
Installing python-ldap and django-auth-ldap on windows 10
Hi there I am trying to pip install python-ldap module and django-auth-ldap modules using pip I am using python version 2.7.12 I keep getting the following error: ...... \python-ldap\modules\errors.h(7) : fatal error C1083: Cannot open include file: 'lber.h': No such file or directory error: command 'C:\\Users\\donallane\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2 Previously I was getting errors saying that I needed C++ Compiler for Python so installed that I did not get that error .. However, now I am getting the one above. Any suggestions on how to get around this would be great -
Django: Add queryset to inlineformsets
I want to make a queryset on a field in an inline formset.. I have Inovice and Product models and InvoiceDetails model to link the manytomany relation between them. here are the models: class Invoices(models.Model): """The Invoice Creation Class.""" invoice_number = models.CharField( _('invoice_number'), max_length=100, unique=True, null=True) .... class Products(models.Model): """Product Creation Class.""" company = models.ForeignKey(Company, default=1) barcode = models.CharField(_('barcode'), max_length=200, null=True) .... class InvoiceDetail(models.Model): invoice = models.ForeignKey(Invoices, related_name='parent_invoice') product = models.ForeignKey(Products, related_name='parent_product') quantity_sold = models.IntegerField(_('quantity_sold')) ... when crearting an invoice i have inline formsets for the products which create an invoice details for every product.. now i want to filter the products that appear for the user to choose from them by the company. i searched a lot on how to override the queryset of inline formsets but found nothing useful for my case. my forms: class InvoiceForm(forms.ModelForm): class Meta: model = Invoices fields = ('customer', 'invoice_due_date', 'discount', 'type') def __init__(self, *args, **kwargs): self.agent = kwargs.pop('agent') super(InvoiceForm, self).__init__(*args, **kwargs) def clean_customer(self): ..... def clean(self): ...... class BaseDetailFormSet(forms.BaseInlineFormSet): def clean(self): ...... DetailFormset = inlineformset_factory(Invoices, InvoiceDetail, fields=('product', 'quantity_sold'), widgets= {'product': forms.Select( attrs={ 'class': 'search', 'data-live-search': 'true' })}, formset=BaseDetailFormSet, extra=1) and use it in the views like that: if request.method == 'POST': invoice_form … -
Avoiding redundant write operations with Django ORM
I have a periodically running task that performs a lot of write calls to the database on existing data. In most cases, records that are written don't contain a change, so the update queries are redundant. The redundant write calls do put an unnecessarily high load on our database replication, though. This is roughly the algorithm: Fetch existing row from database Potentially modify a lot of fields based on parameters that were passed to the algorithm Save the updated row to database using instance.save() Since it's easier to scale our task processors than our database replication, I thought I'd shift some of the processing load towards code by doing this: if original_instance != possibly_updated_instance: possibly_updated_instance.save() Thing is: Django ORM's equality operator only seems to compare primary keys, so we'd incorrectly be dropping changes. Is there a better way to handle this? -
Post_save doesn't triggers when instance is changed and saved in Django admin site
My goal is to trigger some function, when object is changed via Django admin site. Here is my code: @receiver(post_save, sender=Business) def segment_biz_promoted_change(sender, **kwargs): from lib.segment_analytics import get_segment_api instance = kwargs.get('instance') if not instance: return dirty_fields = instance.get_dirty_fields() if dirty_fields.get('promoted'): segment_api = get_segment_api(instance) segment_api.merchant_promoted() This post_save works perfectly when I change Business object manually in my code with .save(), but it doesn't trigger when I change it via django admin site. Should I use something else then post_save? -
django how to automate functions inside views.py file
Well, this question will surely make the delights of the downvotes brigade and may be tagged as" too broad etc", but it is not!, but precisely because it requires "general" knowledge of how things work, I cannot find an answer in the books I have to ask it. Having my Django application, yes, I can make it interactive by means of the MVC flow. The issue that I have is when I have methods that are not in connection with an html page (that the user sees) but are methods that are supposed to be running constantly in the background. For example, just to illustrate, imagine a code snippet that queries a DB and sends an email with news every 2 hours. It is just not doing anything because I dont know how to "wake that code snippet up". I dont have that problem if I am writing a desktop application in just python without Django. If I right click and say, run this file, the code will running in the background alright. Yes, naturally I have heard of cron jobs etc, but so far I see that you can cron-tab a file but how do I crontab a method … -
Overriding render of RadioSelect in django forms gives unexpected results
I want to override the render for RadioSelect in django. (I have done a similar thing for checkboxes and I want both to look the same). The general workflow for this would be to write a custom renderer, and then change the render in the ChoiceInput, BUT when I copy the existing code and run it the html output is not safe and the escaped html string is shown. This is not making any sense as I didn't do any changes to the class yet, other than change the name: In my widgets.py: class ButtonRadioFieldRenderer(ChoiceFieldRenderer): choice_input_class = OtherRadioChoiceInput class OtherRadioChoiceInput(OtherChoiceInput): input_type = 'radio' def __init__(self, *args, **kwargs): super(OtherRadioChoiceInput, self).__init__(*args, **kwargs) self.value = force_text(self.value) @html_safe @python_2_unicode_compatible class OtherChoiceInput(SubWidget): """ An object used by ChoiceFieldRenderer that represents a single <input type='$input_type'>. """ input_type = None # Subclasses must define this def __init__(self, name, value, attrs, choice, index): self.name = name self.value = value self.attrs = attrs self.choice_value = force_text(choice[0]) self.choice_label = force_text(choice[1]) self.index = index if 'id' in self.attrs: self.attrs['id'] += "_%d" % self.index def __str__(self): return self.render() def render(self, name=None, value=None, attrs=None, choices=()): if self.id_for_label: label_for = format_html(' for="{}"', self.id_for_label) else: label_for = '' attrs = dict(self.attrs, **attrs) if attrs else … -
How to know if a model form is among the submitted forms in Django
I have a situation where I make don't at all show a form when the settings.py specifies it. Now I need to handle this form being submitted with along with some other forms and not being there in the template at all. I wrote the logic as it is and did not get any errors at all even though I called myForm.is_valid() and myForm.save() But I'm afraid that this may lead to problems. This is the code in my template <form method="post" accept-charset="utf-8">{% csrf_token %} {{ threadForm|crispy }} {{ postForm|crispy }} {% if SHOW_WIKI %} {{ wikiFrom|crispy }} {% endif %} <input type="submit" class="btn btn-primary btn-sm" value="Submit"/> </form> This is my View for the form @login_required def createThread(request, topic_title=None): if topic_title: try: if request.method == 'POST': topic = Topic.getTopic(topic_title) threadForm = ThreadSUForm(request.POST, prefix='thread') postForm = PostForm(request.POST, prefix='post') show_wiki = getattr(settings, "REFORUMIT_ALLOW_WIKI_FOR_THREADS", False) and topic.is_wiki_allowed wikiForm = WikiCreateForm(request.POST, prefix='wiki') if threadForm.is_valid() and postForm.is_valid() and wikiForm.is_valid(): thread = threadForm.save(commit=False) post = postForm.save(commit=False) wiki = wikiForm.save(commit=False) thread.op = post thread.wiki_revision = None post.setMeta(request) wiki.setMeta(request) if is_authenticated(request): post.created_by = request.user wiki.author = request.user thread.save() wiki.wiki_for = thread wiki.save() post.save() thread.wiki_revision = wiki thread.save() return HttpResponseRedirect(thread.get_absolute_url) else: topic = Topic.getTopic(topic_title) threadForm = ThreadSUForm(prefix='thread', initial={"topic": topic}) … -
authenticate django built in user using custom field
I have model that has one to one relation with django's built in User model. Due to some reason i have added a custom field in my model with name "password_crypt" that supports "pbkdf2_sha512" which is longer than django's built-in field that is i guess 128. So i want to authenticate my user using my custom field but want the rest of the things to work in the same way django's built-in User provides. Token etc How can i authenticate model Object that has one to one relation with django built-in User using custom field "password_crypt" in new model. I am using python 2.7, django 1.10 -
Django / postgresql 'column "type_id" cannot be cast automatically to type integer'
I have an Django app that is working locally, but when I try to deploy it to production it fails with the following error: django.db.utils.ProgrammingError: column "type_id" cannot be cast automatically to type integer HINT: You might need to specify "USING type_id::integer". The main difference between my local setup and production is that I am using SQLite3 and production is using postgres The migration it fails on is migration 10, which looks like this. class Migration(migrations.Migration): dependencies = [ ('speakers', '0009_auto_20180117_1335'), ] operations = [ migrations.AlterField( model_name='speaker', name='type', field=models.ForeignKey(to='speakers.Type'), ), ] The preceding migration, its dependency and the last working migration look like this: class Migration(migrations.Migration): dependencies = [ ('speakers', '0008_auto_20180117_1309'), ] operations = [ migrations.CreateModel( name='Type', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=200)), ], options={ 'verbose_name': 'Type', 'verbose_name_plural': 'Types', }, ), migrations.RenameField( model_name='speaker', old_name='speaker_categories', new_name='type', ), ] To make things I'll also include the models (as they look at the end) class Type(models.Model): name = models.CharField(max_length=200) def __unicode__(self): return self.name class Meta: verbose_name = _("Type") verbose_name_plural = _("Types") class Speaker(models.Model): VIDEO_SRC_TYPES = ( ('yt', 'Youtube'), ('vm', 'Vimeo'), ) status = models.CharField( max_length=40, choices=STATUSES, verbose_name=_("Status"), default=DEFAULT_STATE) type = models.ManyToManyField(Type) (most fields from the 'Speaker' model have been removed to … -
Django REST: Passing extra fields from connected models
I need to add additional fields that are not part of my model to the json response. Is this possible? The models are connected using multiple tables, but do not have a direct connection. models.py class Message(models.Model): body = models.TextField(max_length=500, blank=False) sender = models.ForeignKey(User) timestamp = models.DateTimeField(auto_now_add=True) conversation = models.ForeignKey(Conversation) serializers.py class MessageSerializer(serializers.ModelSerializer): conversation = serializers.ReadOnlyField(source='conversation.id') sender = serializers.ReadOnlyField(source='sender.id') # task = TaskSerializer(source='conversation__task_worker__task.id') # This commented code above is not working, but this is what I need. class Meta: model = Message fields = '__all__' So what I need, is to pass the value of task, which can be found by going back a few tables. E.g. if the current model is Message, I need to: Message -> Conversation -> Task_worker -> Task (Get this) My current json response is: { "count": 2, "next": null, "previous": null, "results": [ { "id": 1, "conversation": 1, "sender": 2, "body": "Hello There", "timestamp": "2018-01-31T17:48:19.680113Z" }, { "id": 3, "conversation": 1, "sender": 2, "body": "Can you do the task", "timestamp": "2018-02-01T09:39:24.797218Z" } ] } Ideally, I would like the following response: { "count": 2, "next": null, "previous": null, "conversation": 1, "task": 5, "any_extra_fields_key": 'value', "results": [ { "id": 1, "sender": 2, "body": "Hello There", … -
Django: Context processors for error pages (or request in simple_tag)
In my Django project, there are several django apps. I want to write custom error pages, and I want them to contain correct links to the application that the errors happened in, for example, if a 500-error happened in my app a, I want the error page contain a link to /a/index.html, and if a server error happened in app b, I want the page to contain the link to /b/index.html. And I want to create only one copy of each of the error page files, which means I need to get the name of the app from within the template. To that end, I have written a custom context processor that adds the app_name var to the templates. I tested it on my normal pages, but when I went on to test it on the error pages, turns out that the context processor isn't firing. Similarly, I have written a template tag app_aware_url which takes the name of the url pattern and tries to resolve it, but again, turns out that for the error pages the simple_tag(takes_context=True) receives a context that does not contain the request (which is needed for telling which app I am in). Is there a …