Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I connect Django to MySQL database and server in windows?
I am having problems connecting Django to MySQL to create my database. Note I have MySQL workbench downloaded and also the package for MySQL connector. Thanks. -
GraphQL support with django-saleor Ecomm platform
I need to know to what degree saleor supports GraphQL? My understanding is that the front end is just django templates, but I see a graphql folder there, so what is it? I was told by the moderators to take a look into the demo branch. I need to know how different is it compared to the master branch. -
Django custom filter not registering in tag library
I've written the following filter (in templatetags/custom_errors.py): from django import template from django.utils.safestring import mark_safe register = template.Library() @register.filter def custom_errors(bound_field): return mark_safe(f'<span id="{bound_field.id_for_label}-error" class="error">{", ".join(bound_field.errors)}</span>' if bound_field.errors else '') which I'm trying to use in a template as follows: {% load widget_tweaks %} {% load custom_errors %} {% load label_with_classes %} {% csrf_token %} <div class="row"> <div class="input-field col s12"> {{ form.session_number|add_error_class:"invalid" }} {{ form.session_number|custom_errors }} {{ form.session_number|label_with_classes }} </div> </div> However, I'm getting a TemplateSyntaxError: 'custom_errors' is not a registered tag library: What puzzles me, however, is that some of the tags that are registered, such as label_with_classes, are done so in the same way. Here is a tree view of dashboard/templatetags: dashboard/templatetags ├── active_page.py ├── custom_errors.py ├── edit_view_family_heading.py ├── google_analytics.py ├── label_with_classes.py ├── order_link.py ├── paginator.py └── profile_badge.py showing that label_with_classes.py is in the same directory as custom_errors.py. Here are the contents of label_with_classes.py: from django import template from django.forms import ChoiceField, BooleanField, DateField from titlecase import titlecase register = template.Library() def pretty_name(name): """Convert 'first_name' to 'First Name'.""" return titlecase(name.replace('_', ' ')) @register.filter(is_safe=True) def label_with_classes(bound_field, contents=None): '''Extend Django's label_tag() method to provide the appropriate Materialize CSS classes''' # The field should have the 'active' class if it … -
Pycharm can't find path to template after django upgrade
Recently I upgraded my project from Django 1.11.6 to Django 2.0. It all works like a charm after little editing, but there is one thing that makes me mad. Pycharm can't find a path to templates and highlights them on: render function, {% extend ... %} etc., and in settings.py on INSTALLED_APPS it can't find app. Here are some examples from my project: return render(request, 'panel/central_stock.html', {'stocks': stocks}) INSTALLED_APPS = [ 'panel.apps.PanelConfig', ] It did not happen in 1.11. I searched google for that, but no solution. Maybe there is some new way to adress it? -
Weird Django requests - is someone trying to hack my server?
I just saw my logs for a site on staging and I saw some weird requests: django-configurations version 2.0, using configuration 'Local' Performing system checks... System check identified no issues (0 silenced). February 21, 2018 - 16:30:01 Django version 1.11, using settings 'config' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. [21/Feb/2018 19:51:54] code 400, message Bad HTTP/0.9 request type ('\x00\x00\x00') [21/Feb/2018 19:51:54] " c" 400 - [21/Feb/2018 23:55:30] code 400, message Bad request syntax ('\x00\x00\x00TZ\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x04\x010I\x00\x00\x00\x00\x80\x0b¨À\x00\x0c)t F\x07\x00tsXrcsXYs9\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00bbXcsXctst\x00\x00\x00\x00\x00\x00') [21/Feb/2018 23:55:30] "TZ0I ¨À)t FtsXrcsXYs9bbXcsXctst" 400 - [22/Feb/2018 04:42:19] code 400, message Bad HTTP/0.9 request type ('\x00\x00\x00') [22/Feb/2018 04:42:19] " c" 400 - [22/Feb/2018 06:58:13] "GET http://www.google.com/ HTTP/1.0" 404 1662 [22/Feb/2018 06:58:41] "GET http://www.google.com/ HTTP/1.0" 404 1662 [22/Feb/2018 06:59:25] "GET /status HTTP/1.1" 404 3724 [22/Feb/2018 06:59:25] "GET /status HTTP/1.1" 404 3724 [22/Feb/2018 15:43:40] code 400, message Bad HTTP/0.9 request type ('\x00\x00\x00') [22/Feb/2018 15:43:40] " c" 400 - [22/Feb/2018 17:20:24] code 400, message Bad HTTP/0.9 request type ('\x00\x00\x00') [22/Feb/2018 17:20:24] " c" 400 - [22/Feb/2018 18:49:40] code 400, message Bad HTTP/0.9 request type ('\x00\x00\x00') [22/Feb/2018 18:49:40] " c" 400 - [22/Feb/2018 19:39:14] "GET / HTTP/1.1" 500 142024 [22/Feb/2018 19:39:25] "GET / HTTP/1.1" 500 142024 [22/Feb/2018 19:39:26] "GET /favicon.ico HTTP/1.1" 404 3742 [22/Feb/2018 … -
How to use URL names in views?
I have been following this Django tutorial, and I am trying to remove hardcoded URLs, but I can't make the reverse function work. That's my detail view: def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") # How it was before: # return render(request, 'polls/detail.html', {'question': question}) return HttpResponse(reverse('polls:detail', kwargs={'question': question})) path('<int:question_id>/', views.detail, name='detail') And this is the template for the detail view: <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> {% endfor %} <input type="submit" value="Vote" /> <a href="{% url 'polls:index' %}">Index</a> </form> Can somebody help me with that or give any tips? Thanks in advance. -
custom RegisterSerializer doesn't work with django-rest-auth
I'm using django-rest-auth and I want to add registration with my own User model. So I add allauth and create my own RegisterSerializer as it was mentioned in docs. serializers.py class RegisterSerializer(serializers.Serializer): email = serializers.EmailField(required=True) password = serializers.CharField(write_only=True) def validate_email(self, email): email = get_adapter().clean_email(email) if email and email_address_exists(email): raise serializers.ValidationError( _("A user is already registered with this e-mail address.")) return email def validate_password(self, password): return get_adapter().clean_password(password) def get_cleaned_data(self): return { 'password': self.validated_data.get('password', ''), 'email': self.validated_data.get('email', '') } def save(self, request): user = get_user_model() cleaned_data = self.get_cleaned_data() user.create_user(**cleaned_data) return user settings.py REST_AUTH_SERIALIZERS = { 'REGISTER_SERIALIZER': 'users.serializers.RegisterSerializer', } AUTH_USER_MODEL = 'users.User' Unfortunately still uses the default serializer -
Having trouble with django inlineformset_factory
Doing a little project, that has parties and info how people fly to them. Been banging my head on the forms for three days now. Cannot wrap my head around the inlineformset_factory. models.py class Party(models.Model): name = models.CharField(max_length=32) slug = models.SlugField() class Journey(models.Model): party = models.ForeignKey(Party,related_name='journeys') person = models.CharField(max_length=32) class Flight(models.Model): journey = models.ForeignKey(Journey, related_name='flights') departure_datetime = models.DateTimeField() etc... Party must exist before Journeys can be made, Parties are created elsewhere. urls.py, in urlpatterns[] path('<slug:slug>/add/', AddFormSet.as_view()), views.py class AddFormSet(generic.CreateView): template_name = 'party/formset.html' model = Party fields = ('name',) def get_success_url(self): return reverse('party:party-detail', **self.kwargs) def get_context_data(self, **kwargs): context = super(AddFormSet, self).get_context_data(**kwargs) if self.request.POST: context['formset'] = JourneyFormset(self.request.POST) else: context['formset'] = JourneyFormset() return context def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid(): formset.instance = self.object formset.save() return super(AddFormSet, self).form_valid(form) forms.py class BaseJourneyFormset(BaseInlineFormSet): def add_fields(self, form, index): super(BaseJourneyFormset, self).add_fields(form, index) # save the formset in the 'nested' property form.nested = FlightFormset( instance=form.instance, data=form.data if form.is_bound else None, files=form.files if form.is_bound else None, prefix='flight-%s-%s' % ( form.prefix, FlightFormset.get_default_prefix()) ) def is_valid(self): result = super(BaseJourneyFormset, self).is_valid() if self.is_bound: for form in self.forms: if hasattr(form, 'nested'): result = result and form.nested.is_valid() return result def save(self, commit=True): result = super(BaseJourneyFormset, … -
How exactly configure Django to send emails with bug reports?
everyone! I am really novice with Django, and I am having troubles in configuring property my app to send me emails with the bug reports. I already set on the settings file the required variables as I saw on the Django documentation, like this: DEBUG = False ... ADMINS = [('myname', 'myemail@server')] # For server errors MANAGERS = [('myname', 'myemail@server')] # For missing pages errors I provoked a error for testing, but nothing happened, no email. What should I do? -
For loop in Django template not processing
I create a dictionary, and pass it to my Django template: my_dict = {'boo': {'id':'42'}, 'hi': {'id':'42'}} t = get_template('delta.html') html = t.render(delta_dict) print(html) return HttpResponse(html) My Django template looks like this: <html> <body> Out of Dictionary <div> {% for key in my_dict %} <span>{{ key }}</span> {% endfor %} </div> After dictionary </body> </html> My output in the browser looks like this: Out of Dictionary After dictionary The HTML looks like this: <html> <body> Out of Dictionary <div> </div> After dictionary </body> </html> -
Combine 2 Django Querysets
I want to merge two queryset in Django using operand "|" but it don't work. I know that to do it you must have querysets from the same model. This is exactly what I'm trying to do. The loop is because I want to get random objects and merge it into one. Anyone have idea why Django throw "TypeError: unsupported operand type(s) for |: 'Sentence' and 'Sentence'" error? According to below source this is how to make it happen: https://simpleisbetterthancomplex.com/tips/2016/06/20/django-tip-5-how-to-merge-querysets.html from random import randint from sentences.models import Sentence sentence_number = 3 first_pk = Sentence.objects.first().pk last_pk = Sentence.objects.last().pk for i in range(sentence_number): next_pk = randint(first_pk, last_pk) sentence_qs = Sentence.objects.get(pk=next_pk) type(sentence_qs) if i > 1: sentence_qs = sentence_qs | Sentence.objects.get(pk=next_pk) -
How do I customize the display of radio buttons in a Django template?
In my forms.py, I have this, where supbplansTuple is a tuple of tuples: class RegisterForm(UserCreationForm): subChoices= forms.ChoiceField(label=_("Choose plan"), widget=forms.RadioSelect, choices=subPlansTuple) subplansTuple looks something like this: (("plan_1234","$5 a month"),("plan_2345","$10 a month")) register.html has this: <form id="register-form" name="regForm" method="post"> {% csrf_token %} {% for field in registration_form %} <p>{{ field }}</p> {% endfor %} </form> Problem is, Django displays the radio buttons widget like this: <p></p> <ul id="id_subChoices"> <li> <label for="id_subChoices_0"><input id="id_subChoices_0" name="subChoices" type="radio" value="plan_1234" required=""> $5 a month</label> </li> <li> <label for="id_subChoices_1"><input id="id_subChoices_1" name="subChoices" type="radio" value="plan_2345" required=""> $10 a month</label> </li> </ul> <p></p> I do not want the radio buttons to display this way. How do I customize the HTML, maybe to look something like Boostrap's inline radio buttons. -
Django formset not saving my files
So I have these two models Lecture and FileUpload. I want that the user to be able to add a lecture to a specific course and also upload multiple files for that lecture. Thing is that after I submit the form the information gets saved except for the uploaded files, so I am guessing something is wrong with my formset. Please have a look: FileFormset = inlineformset_factory(Lecture, FileUpload, exclude=[]) def classroom(request): if request.method == 'POST': form1 = LectureForm(request.POST) if form1.is_valid(): lecture = form1.save() formset = FileFormset(request.POST, request.FILES, instance=lecture, prefix='files') if formset.is_valid(): formset.save() else: print(formset.errors) formset.save() return redirect('courses:index') else: form1 = LectureForm() formset = FileFormset() context = {'teacher_data': TeacherData.objects.all(), 'teachers': Teacher.objects.all(), 'courses': Course.objects.all(), 'form1': form1, 'formset': formset, } return render(request, 'courses/classroom.html', context) <form method="post" action=""> {% csrf_token %} {{ form1.as_p }} {{ formset.management_form }} {% for form in formset %} {{ form }} <br> {% endfor %} <br> <button type="submit">Add Lecture</button> </form> class LectureForm(forms.ModelForm): class Meta: model = Lecture fields = ('course', 'lecture_title', 'lecture_category', 'content') class FileForm(forms.ModelForm): class Meta: model = FileUpload fields = ('files',) class Lecture(models.Model): LECTURE_CHOICES = ( ('Courses', 'Courses'), ('Seminars', 'Seminars'), ) course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures',) lecture_category = models.CharField(max_length=10, choices=LECTURE_CHOICES, default='Courses',) lecture_title = models.CharField(max_length=100, blank=True, null=True) … -
Django. How to get fields from child model in views.py?
How to get fields from child model in views.py? For example, I've parent model BasicOrder and child model (who extends BasicOrder) TouristVisa. I'm using Django 2.0.2 and Python 3.6.1. My models.py is: class BasicOrder(models.Model): user = models.ForeignKey(User, verbose_name=_('User'), on_delete=models.CASCADE) status = models.PositiveIntegerField(_('Status'), choices=ORDER_STATUS, default=0) def __str__(self): return 'Order #{}'.format(self.id) class TouristVisa(BasicOrder, models.Model): citizenship = models.ForeignKey( Citizenship, verbose_name=_('Citizenship'), on_delete=models.PROTECT ) invitation_entry = models.PositiveSmallIntegerField( _('Invitation entry'), choices=INVITATION_ENTRY ) class Meta: ordering = ['id'] Would be great to have access to field invitation_entry from child model (TouristVisa). I try this way in views.py: order = BasicOrder.objects.get(user=request.user.id) print(order.invitation_entry) But it's show error: AttributeError: 'BasicOrder' object has no attribute 'invitation_entry' -
Issue with SSL, nginx, gunicorn, and Django in production
I'm having an issue getting nginx to pass over control of routing to my django server. By default it checks '/' path and if the user isn't logged in redirects to '/login' and then upon login passes it back to '/'. The login page works fine until you submit then it throws an 'Internal server error'. The server is ubuntu 16.4. Also the python is 3.5 and inside a virtualenv. Let me know if I need to provide the gunicorn service config. My nginx is as follows: server { server_name example.com; rewrite ^(.*) https://www.example.com permanent; } server { listen 80; server_name www.example.com; rewrite ^(.*) https://www.example.com permanent; } server { listen 443 ssl; server_name www.example.com; ssl on; ssl_certificate /etc/nginx/12345678.crt; ssl_certificate_key /etc/nginx/ssl.key; location = /favicon.ico { access_log off; log_not_found off; } location /static/ {root /home/ubuntu/app; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/app/app.sock; } } -
How to load the Django application module?
How to load the Django application module? This error is shown when I squeeze the django server compressed by pyinstaller. hook-sistema.apps.py from PyInstaller.utils.hooks import collect_submodules hiddenimports = collect_submodules('sistema') ERROR: (PythonLib): dist\AGTRAN.exe runserver Unhandled exception in thread started by <function check_errors..wrapper at 0x05F03738> Traceback (most recent call last): File "site-packages\django\utils\autoreload.py", line 225, in wrapper File "site-packages\django\core\management\commands\runserver.py", line 113, in inner_run File "site-packages\django\utils\autoreload.py", line 248, in raise_last_exception File "site-packages\django\core\management_init_.py", line 327, in execute File "site-packages\django\utils\autoreload.py", line 225, in wrapper File "site-packages\django_init_.py", line 24, in setup File "site-packages\django\apps\registry.py", line 89, in populate File "site-packages\django\apps\config.py", line 116, in create File "importlib_init_.py", line 126, in import_module File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 941, in _find_and_load_unlocked File "", line 219, in _call_with_frames_removed File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'sistema' -
Django model with 'order_with_respect_to': how to get object order?
I have two models with an order_with_respect_to relationship: class Book(models.Model): pass class Chapter(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) class Meta: order_with_respect_to = 'book' I know I can get the order of chapters like this: my_book.get_chapter_order() But given a chapter, I need to know its position. I know there's a generated _order field, but it's suposed to be private, so I'd prefer not to use it. My first approach would be something like this: my_chapter = Chapter.objects.get(pk=WHATEVER) chapters = my_book.get_chapter_order() for position, chapter_id in enumerate(chapters): if chapter_id == my_chapter.id: break print(position) But it feels very dirty: I must get the whole order list each time I want to know a chapter's order. I think this should be just a chapter's property. Is there any cleaner way to do this? -
How to restrict user acces to see/modify objects created by other users with Django
I'm making a hobby project with Django to store my ideas seperated by idea groups as the following: class Idea(models.Model): name = models.CharField(unique=True, max_length=50) description = models.TextField() in_process = models.BooleanField() is_done = models.BooleanField() group = models.ForeignKey(Group, on_delete=models.CASCADE, blank=False) class Group(models.Model): name = models.CharField(unique=True, max_length=25) description = models.CharField(max_length=50, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False) Is there any way to restrict the currently logged in user from being able to see or modify ideas and idea groups created by other users using generic class based views? class GroupDelete(LoginRequiredMixin, generic.DeleteView): model = Group pk_url_kwarg = "id" success_url = reverse_lazy('ideas:list') ...and a url for example: urlpatterns = [ path('<int:id>/delete', views.GroupDelete.as_view(), name='delete'), ] I'm using Django 2.0. -
Django Custom model authentication and ACL (Access Control List) with Angular
I have a custom user model with onetoone relationship with django user model, I have migrated data from Odoo to django database. My Odoo password hash is different from django user password. I would like suggestion about how to make custom user model that will be helpful in all scenario for my Odoo data as well as Django data. Which will authenticate user easily in both way. Secondly i have overlooked in django documentation for Custom user authentication. So i have added custom authentication for both django and Odoo. How would i send response to Angular that my user can be authenticate every time on different views for django. How would i will implement ACL on different user roles in this point of view. Any more better example if you could share and better suggestion. Kindly put some good and simple examples would be appreciated. If you need code i will edit my question and put it as well. -
Trouble accessing object
I've been working on an issue all day and am at my wits end. I have two models with a manytomany relationship (bookmark, and boomark group). I am trying to access the bookmarks accosiated with the bookgroup in my view. When print the context to take a peak I get None returned. I've pasted the code below in a gist...any help would be so greatly appreciated. https://gist.github.com/colonelrascals/4bf4e4f98c47d64706b504646346bbd5 -
virtualenv - ModuleNotFoundError: No module named 'django'?
New to linux, I have install django in virtualenv, but i am not able to import django. Is there any variable path i need to set ? (virs) akash@akash-Inspiron-3542:/usr/virs/bin$ django-admin --version 1.11.10 (virs) akash@akash-Inspiron-3542:/usr/virs/bin$ python Python 3.6.4 (default, Jan 28 2018, 17:52:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import django Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'django' -
django ModelForms and normal form in POST request
Hi i just have a small doubt can we create a HTML template which will have the Django form and normal HTML form together. I created a HTML template which has both normal HTML input tag and Django forms. I am getting the following error when i do a form.save(commit=False) could not be created because the data didn't validate. My view.py if request.method == 'POST': form_value = request.POST.copy() print form_value form = InfoForm(data=request.POST) post_val = form.save(commit=False) my HTML <div class="form-row"> <div class="form-group col-md-4"> {{form.name}} </div> <div class="form-group col-md-4"> {{form.number}} </div> <div class="form-group col-md-4"> {{form.location}} </div> </div> <div class="form-group"> <label for="Feedback">Feedback</label> <div id="Feedback" class="optionBox1"> <div class="input-group my-add-div"> <input type="text" class="form-control" name="feedback" required> <input type="text" class="form-control" name="feedback" required> <input type="text" class="form-control" name="feedback" required> </div> </div> </div> my form.py class InfoForm(forms.ModelForm): name = forms.CharField(label='Project Name',max_length=100,widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Click to enter text',})) number = forms.DecimalField(label='Project #',widget=forms.NumberInput(attrs={'class':'form-control','placeholder':'Enter the ID',})) location = forms.CharField(label='Location',max_length=100,widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Enter the Location',})) class Meta: model = Info field = ('name','number','location',) My Model.py name = models.CharField(max_length=200,blank=True , null=True) number = models.IntegerField(blank=True , null=True) location = models.CharField(max_length=200,blank=True , null=True) feedback = ArrayField(ArrayField(models.CharField(max_length=200,blank=True,null=True))) Thanks in advance -
Django bakery ImportError: Could not import 'p'. The path must be fully qualified
I'm trying to export my site as flat files with django bakery. I made a dummy site with a sample polls app and I get this error when I run python manage.py build File "python3.6/site-packages/bakery/management/commands/build.py", line 112, in handle self.build_views() File "python3.6/site-packages/bakery/management/commands/build.py", line 240, in build_views view = get_callable(view_str) File "python3.6/site-packages/django/urls/utils.py", line 25, in get_callable raise ImportError("Could not import '%s'. The path must be fully qualified." % lookup_view) ImportError: Could not import 'p'. The path must be fully qualified. I followed all their instructions correctly: polls/views.py: from bakery.views import BuildableTemplateView class HomePageView(BuildableTemplateView): template_name = "home.html" build_path = 'index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', 'bakery' ] BUILD_DIR = '/Users/me/Downloads/build/' BAKERY_VIEWS = ( 'polls.views.HomePageView' ) mysite/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls')), ] polls/urls.py: from django.urls import path from . import views from polls.views import HomePageView urlpatterns = [ path('', HomePageView.as_view(), name='home'), ] Maybe it is something related to the urls? But I can't see what. The site works fine in the browser... -
How can I define a metric for uniqueness of strings on Django model?
Suppose I have a model that represents scientific articles. Doing some research, I may find the same article more than once, with approximately equal titles: Some Article Title Some Article Title Notice that the second title string is slightly different: it has an extra space before "Title". If the problem was because there could be more or less spacing, it would be easy since I could just trim it before saving. But say there could be more small differences that consist of characters other than spaces: Comparison of machine learning techniques to predict all-cause mortality using fitness data: the Henry ford exercIse testing (FIT) project. Comparison of machine learning techniques to predict all-cause mortality using fitness data: the Henry ford exercIse testing (FIT). This is some random article I used here as an example Those titles clearly refer to the same unique work, but the second one for some reason is missing some letters. What is the best way of defining uniqueness in this situation? In my mind, I was thinking of some function that calculates the levenshtein distance and decides if the strings are the same title based on some threshold. But is it possible to do on a … -
How display request error in custom django admin error page
Currently when a 500 erros ocurrs I show the user my custom 500.html error page. The app is used by both administrators and clients, which users are respectively in groups "operator" and "client". The information shown depends on that group. I would like to apply that concept to the error page. I would like to show the same Traceback error shown when DEBUG = True (not neccesary the same style) when logged user is from group "operator". Information I would like to show to the operator I guess there will be an attribute in the request that I can pass throught the template and print the errors, but I can't find out which attribute is that. This is the functiona I use to render the 500.html page: def error_500(request): data = {} if request.user.groups.filter(name='operator').exists(): # fill the data dict with the traceback/errors return render(request,'app/errors/500.html', data) Thanks in advance.