Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
issue with django context processor
Context processor does not work when href inside templates redirect to details context_processor.py from .models import Category def polls_category(request): for e in Category.objects.all(): name=e.title return {"polls_category":name} Context_processor in settings.py 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'products.context_processors.polls_category' ], }, Template {% for obj in gili_list %} <p><small><a href='{{obj.get_absolute_url}}'>{{polls_category}}</a></small></p> {% endfor %} views.py class CategoryListView(ListView): model = Category template_name = "products/product_list.html" def get_context_data(self, *args, **kwargs): context = super(CategoryListView, self).get_context_data(*args, **kwargs) context['gili_list'] = Category.objects.all() return context -
Additional spaces when having for loop
I'm getting an additional white spaces in the first post. {% for ctr in id%} <div class="border"> <div> ... </div> </div> {% endfor %} Actual result: When I add the for loop, I get this this Expected Result: When there is no for loop, I get this -
How create custom validator which check multiple fields in django admin panel?
I am working on a project which needs to implement an advising system, I create an adviser session model as following code snippet in Django: class AdviserSession(models.Model): ... date = models.DateField() session_start_time = models.TimeField() session_end_time = models.TimeField() ... first I want to check that sessions do not conflict with each other so I need to check it with session_start_time and session_end_time, but I don't know how to do that. second if I want to insert multiple session in a date how can I do that in Django admin panel? -
Run multiple django project with nginx and gunicorn
I am using Ubuntu 18 servers and using nginx with gunicorn I follow Digitalocean tutorial for server setup. I successfully did for one project but now I need to run multiple projects under by server. Here is my gunicorn setup sudo nano /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=rfr Group=www-data WorkingDirectory=/home/rfr/helpdesk/helpdesk ExecStart=/home/rfr/helpdesk/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ helpdesk.wsgi:application [Install] WantedBy=multi-user.target And also here is my nginx setup sudo nano /etc/nginx/sites-available/helpdesk server { listen 80; server_name 192.168.11.252; location = /favicon.ico { access_log off; log_not_found off; } location /assets/ { root /home/rfr/helpdesk/helpdesk; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Now how can I add another project under this IP? I want to configure my nginx setup for access project like this 192.168.11.252/firstProject 192.168.11.252/secoundproject I try a few googles but not help me more. -
How to send string parameter to url with path?
I want to send a string as parameter to one of my URL in urls.py in Django. The url is path('competitions//about', views.comp_about, name='comp_about'), Im sending my string through my HTML file as <a href="% url 'comp_about' {{c.comp_name}}%">Register Now!</a> where c is my object with data member comp_name this is final url after clicking http://127.0.0.1:8000/competitions/%%20url%20'comp_about'%20Comp1% It says Page not found! Ive searched SO and google for problem why I am facing. views.py @login_required(login_url='login') def comp_about(request,comp_name): comps= Competition.objects.get(comp_name=comp_name) context={ "comps": comps } return render(request,"competition/about.html",context) html File <h4>List of Comps</h4> <br> <div class="section"> {% if comps %} <ul> {% for c in comps%} <li> {{c.comp_name}} <br> <a href="% url 'comp_about' {{c.comp_name}}%">Register Now!</a> </li> <br><Br> {% endfor %} {% endif%} </ul> </div> urls.py path('competitions/<comp_name>/about', views.comp_about, name='comp_about'), models.py class Competition(models.Model): comp_name = models.CharField(max_length=75) comp_description = models.TextField(max_length=10000) comp_team_size = models.IntegerField(null=True,blank=False) comp_payment_fee = models.IntegerField(null=True,blank=True) comp_rules = models.TextField(max_length=10000,blank=False) comp_date = models.DateField(null=True,blank=False) comp_registration_deadline = models.DateField(null=True,blank=False) class Meta: ordering = ['-id'] def __str__(self): return self.comp_name -
Django EmbeddedModelField saying "This field may not be blank" when doing PUT request despite field having "blank=True"
I'm creating a Django application with django-rest-framework and using djongo to connect to MongoDB. I have nested models as such: class Group(models.Model): users = models.ArrayModelField( model_container=User ) class User(models.Model): number = models.IntegerField( default=None, null=True ) song = models.EmbeddedModelField( model_container=Song, null=True, blank=True ) class Meta: abstract = True class Song(models.Model): mp3_file = models.URLField( default=None, blank=True, null=True ) comments = models.CharField( max_length=250, default='', blank=True ) class Meta: abstract = True When a Group is created, the Users and the Songs are created without any problems. For example, when created, the Group may look like: { "name": "Sample", "users: [ { "number": null, "song": { "mp3_file": null, "comments": "" } } ] } This all works fine. However, if I try to do a PUT request and don't change the value of "number", "mp3_file", or "comments", I will get the following error message: "user": [ { "number": [ "This field may not be null." ], "song": { "mp3_file": [ "This field may not be null." ], "comments": [ "This field may not be blank." ] } } ] Any thoughts on how to fix this error? I am just using a generic RetrieveUpdateDestroyAPIView as the view for this endpoint. edit: I have also … -
get value in table manytomany django
hi i try to get same value in a table many to many in django but i don't know how can i do it this is my modles: class Raza(models.Model): Nombre = models.CharField(max_length=50) Origen = models.CharField(max_length=45) Altura = models.CharField(max_length=10) Peso = models.CharField(max_length=10) Esperanza_vida = models.CharField(max_length=10) Actividad_fisica = models.CharField(max_length=45) Recomendaciones = models.CharField(max_length=500) Clasificacion_FCI = models.ForeignKey(Clasificacion_FCI,null=True,blank=True,on_delete=models.CASCADE) Tipo_pelo = models.ManyToManyField(Tipo_pelo,blank=True) Caracteristicas_fisicas = models.ManyToManyField(Caracteristicas_fisicas,blank=True) Caracter = models.ManyToManyField(Caracter,blank=True) Ideal = models.ManyToManyField(Ideal,blank=True) Tamanio = models.ForeignKey(Tamanio,null=True,blank=True,on_delete=models.CASCADE) User = models.ManyToManyField(User,blank=True) and the User model are the default model that Django give me i don't have any idea how i can do it i want do something like that table user id_usuario = 1 name = "Juan" table raza id_raza = 1 name = "pitbull" table user_raza id_user_raza = 1 id_user = 1 id_raza = 1 -
Why does my query and template result in a blank page?
I'm running the below query based on generic relations in django: Master_Query = Studies.objects.select_related().filter(Q(conditions__ConditionsName__icontains = TypeFormData)).order_by('nct_id')[:10] When executing the query I see nothing on my template page. From my debug log it seems like the query doesn't select any fields from my Conditions model despite executing the inner join. Relevant models: class Studies(models.Model): content_type = models.ForeignKey(ContentType, on_delete = models.CASCADE) nct_id = models.CharField(primary_key = True, max_length = 100, unique=True, db_column = 'nct_id') content_object = GenericForeignKey('content_type', 'nct_id') brief_title = models.TextField(blank=True, null=True) official_title = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'studies' class Eligibilities(models.Model): id = models.IntegerField() nct_id = models.CharField(primary_key = True, max_length = 100, unique=True, db_column = 'nct_id') nct = GenericRelation(Studies, related_query_name = 'eligibilities', content_type_field = 'content_type', object_id_field = 'nct_id') gender = models.CharField(max_length = 10000, blank=True, null=True) criteria = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'eligibilities' class Conditions(models.Model): id = models.IntegerField() nct_id = models.CharField(primary_key=True, max_length = 100, unique=True, db_column = 'nct_id') nct = GenericRelation(Studies, related_query_name = 'conditions', content_type_field = 'content_type', object_id_field = 'nct_id') ConditionsName = models.CharField(max_length = 10000, blank=True, null=True, db_column = 'name') downcase_name = models.CharField(max_length = 10000, blank=True, null=True) class Meta: managed = False db_table = 'conditions' I expect to see the following fields from the … -
UnicodeDecodeError at / 'utf-8' codec can't decode byte 0xfe in position 0: invalid start byte when rendering new template
I'm trying to render a template that extends from my base.html. however I'm getting this error.enter image description here I tried to change my template directory location (from the app folder to the project root). I also made my Templates directory point to the right place in my settings file. The problem occurred after i made this change. I tried to put the templates folder back in the same location but it didn't work afterwards. Im quite new to Django. would greatly appreciate if you can show me what i'm doing wrong. Traceback (most recent call last): File "C:\Users\arfat\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\arfat\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\arfat\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\arfat\pycharmprojects\FormProject\myformapp\blog\views.py", line 10, in home return render(request, 'home.html', {'categories': categories}) File "C:\Users\arfat\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\arfat\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\arfat\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\arfat\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 171, in render return self._render(context) File "C:\Users\arfat\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\arfat\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 937, in render bit = node.render_annotated(context) File "C:\Users\arfat\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) … -
Using text-overflow: ellipsis with flexbox
I'm building a shopping cart page and want to list products' image, title, price, and a form element to remove it from the cart. I've tried using white-space: nowrap;, overflow: hidden;, and text-overflow: ellipsis; together on elements that I want to truncate, but I can't figure out how to display them correctly, especially with img-container and name-price-container using flexbox. Here's my Django template: <ul> {% for product in products %} <li class="row product"> <div class="img-container"> <a href="{% url 'gallery:product_page' %}?id={{ product.id }}"> <img src="{{ product.image.url }}" alt="{{ product.name }}"> </a> </div> <div class="name-price-container"> <span> <a href="{% url 'gallery:product_page' %}?id={{ product.id }}">{{ product.name }} Loooooooooong Text</a> </span> <span>${{ product.price_per_unit }}</span> </div> <div class="btn-container"> <form method="POST" action="{% url 'gallery:remove_cart' %}"> {% csrf_token %} <input type="hidden" name="id" value="{{ product.id }}"> <input type="submit" class="btn btn-light" value="Remove"> </form> </div> </li> {% endfor %} </ul> ...and the relevant CSS: .product .img-container { background-color: #343a40; border: 1px solid #343a40; box-sizing: unset; height: 128px; width: 128px; flex: 0 0 auto; } .product .img-container img { display: block; max-height: 128px; max-width: 128px; width: auto; height: auto; } .name-price-container { margin: 0 1rem; display: flex; flex: 1 0 auto; flex-direction: column; justify-content: center; min-width: 0; } .name-price-container a { white-space: … -
when client close the web socket,the server disconnect() can't work
I wrote a class.(constumer) When the browser actively disconnects,Server-side function(disconnect )don‘t execute. The user actively closes the webpage, the connection is actually disconnected, but does not trigger disconnect. -
Python/Django PDF Creation Not Working For Me
I'm just getting started on creating a pdf from a binary string. Here is my code: ... resp = HttpResponse(content_type='application/pdf') resp['Content-Disposition'] = 'inline; filename="mypdf.pdf"' resp.write(b'Hello world.') return resp ... The problem is that I keep getting an error that says "Failed to load PDF document." What am I doing wrong? Thanks. -
Initialize Django Form with Parameters from Previous Page
New to Django and everything was going smoothly until this... I am trying to pass latitude / longitude to a django form when user clicks on map. Here is the js for my map page: mapview.on("click", function(event) { // Get the coordinates of the click on the view // around the decimals to 3 decimals var lat = Math.round(event.mapPoint.latitude * 100000) / 100000; var lon = Math.round(event.mapPoint.longitude * 100000) / 100000; openForm(lat, lon); function openForm(lat, lon){ window.location.href = 'http://127.0.0.1:8000/form'; alert("latitude: "+lat+" and longitude: "+lon); } And my forms.py class MyForm(forms.ModelForm): created_date = forms.DateTimeField() userid = forms.CharField() description = forms.CharField() latitude = forms.CharField() longitude = forms.CharField() def __init__(self, *args, **kwargs): #instance = kwargs.get('instance', None) kwargs.update(initial={ # 'field': 'value' 'latitude': 'this text will initially populate...', 'created_date': }) super(MineralForm, self).__init__(*args, **kwargs) and views.py def mineral(request): if request.method == "POST": form = MineralForm(request.POST) # populates form with what user tried to submit... if form.is_valid(): post = form.save(commit=False) post.author = request.user post.created_date = timezone.now() post.save() return render(request, 'blog/matMap.html') form = MyForm() return render(request, 'form.html', {'form': form}) Any help with this would be greatly appreciated! Thank you!!! -
Django 1.11 Json Models
I want to create a Django Models Database with an object with entries as such for a checklist inside a report. { 'int id':{ 'description': string, 'value': bool, # yes/no ... represented by true/false 'remarks': string }, . . . } such that when I import: data = filename.json list ={} with open('data', 'r') as read_file: raw_data = json.load(read_file) i = 0 if i < len(raw_data): # Make sure we don't go out of bounds # Cycle thru data for id in raw_data: s = str(i) list[i] = {} list[i]['Description'] = raw_data[s]["Description"] list[i]['Value'] = raw_data[s]["Value"] list[i]['Remarks'] = raw_data[s]["Remarks"] i = i+1 ... ... ... class Report (models.Model): ... ... Other items like reporter's name, etc ... checklist = list{} I want to populate this model as such. And I can edit them under the Reports model in the admin page. However i cannot fins what method to use to properly do this. I have tried choice but it’s not what i want. -
Test permission denied not catched
I try to check with unittests if it is possible to access a certain url without the proper permissions. When I wrote the test everything worked correctly. I don't know if the error started to occure after an Django update because I didn't checked the test after the update and just started to write new tests which failed. So I checked my old test which are now failing too. class MemberTestMethods(TestCase): def setUp(self): # Create user user = User.objects.create_user('temp', 'temp@temp.tld', 'temppass') user.first_name = 'temp_first' user.last_name = 'temp_last' user.save() # login with user self.client.login(username='temp', password='temppass') # Create member member = Member.objects.create(salutation=Member.MR, first_name='Temp', last_name='Temp') member.save() def test_member_list_permission(self): "User should only access member list if view permission is set" user = User.objects.get(username='temp') response = self.client.get(reverse('members:list')) self.assertEqual(response.status_code, 403) user.user_permissions.add(Permission.objects.get(codename='view_member')) response = self.client.get(reverse('members:list')) self.assertEqual(response.status_code, 200) After running python manage.py test I get the following error Creating test database for alias 'default'... System check identified no issues (0 silenced). WARNING:django.request:Forbidden (Permission denied): /de/reporting/ Traceback (most recent call last): File "/home/***/.virtualenvs/pyVerein/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/***/.virtualenvs/pyVerein/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/***/.virtualenvs/pyVerein/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/***/.virtualenvs/pyVerein/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, … -
Converting a JSON string to a dictionary in Django
Firstly, I am not able to get the json.stringfy in Django. It shows in request.POST but using request.POST['jstring'], it returns nothing. #building json in for statement data.push({ fname: firstName, lname: lastName, }); #attach to formData formData.append('data', JSON.stringify(data)); #views.py print(request.POST) <!-- displays the 'data' field print(request.POST['data'] <!-- empty data = request.POST.get('data') data_json = json.dumps('data') I don't get why the POST['data'] shows empty when POST displays all the fields including 'data' and how I can convert the string data to JSON? -
add value in table manytomany django
hi i try to add same value in a table many to many in django but i don't know how can i do it this is my modles: class Raza(models.Model): Nombre = models.CharField(max_length=50) Origen = models.CharField(max_length=45) Altura = models.CharField(max_length=10) Peso = models.CharField(max_length=10) Esperanza_vida = models.CharField(max_length=10) Actividad_fisica = models.CharField(max_length=45) Recomendaciones = models.CharField(max_length=500) Clasificacion_FCI = models.ForeignKey(Clasificacion_FCI,null=True,blank=True,on_delete=models.CASCADE) Tipo_pelo = models.ManyToManyField(Tipo_pelo,blank=True) Caracteristicas_fisicas = models.ManyToManyField(Caracteristicas_fisicas,blank=True) Caracter = models.ManyToManyField(Caracter,blank=True) Ideal = models.ManyToManyField(Ideal,blank=True) Tamanio = models.ForeignKey(Tamanio,null=True,blank=True,on_delete=models.CASCADE) User = models.ManyToManyField(User,blank=True) and the User model are the default model that Django give me i tried someone like that class AgregarFav(views.APIView): def post(self, request, *args, **kwargs): idUsario= request.POST.get('isUsuario') idPerro = request.POST.get('idPerro') raza = Raza.User.add(idPerro,idUsario) raza.save() return HttpResponse(idUsario) but i have the error 'ManyToManyDescriptor' object has no attribute 'add' i want do something like that table user id_usuario = 1 name = "Juan" table raza id_raza = 1 name = "pitbull" table user_raza id_user_raza = 1 id_user = 1 id_raza = 1 -
is a way to make crispy forms work not editing my forms in bootstrap format
I am using crispy forms tag but its not affecting my form. i will display a picture for more understanding Signup.html {% include "profiles/account/base.html" %} {% load crispy_forms_tags %} {% load i18n %} {% block head_title %}{% trans 'Signup' %}{% endblock %} {% block content %} <h1>{% trans 'Sign Up' %}</h1> <p>{% blocktrans %}Already have an account? Then please <a href=" {{ login_url }}">Sign in</a>{% endblocktrans %}</p> <form class="signup" id="signup_form" method="POST" action="{% url 'account_signup' %}"> {% csrf_token %} {{ form|crispy }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button type="submit" class="btn btn-default">{% trans "Sign Up" %}&raquo;</button> </form> {% endblock %} ecommerce.urls.py from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url from django.contrib import admin from django.urls import include,path urlpatterns = [ path('', include('profiles.urls')), path('contact/', include('contact.urls')), path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, `enter code here` document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) format of how how folders are arranged in my text editor output in my browser but not what i want -
Django segmentation fault when querying model within runserver
What could cause Django to see fault when querying a mode within run server, but that same model can be queried exactly the same way within the interactive shell and not see fault? -
ERROR 404 Django project has a wrong current path
I was creating a basic website following this tutorial: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/skeleton_website When I tried to redirect the home page to my django app called unihub this error prompted: Using the URLconf defined in TFGsWeb.urls, Django tried these URL patterns, in this order: admin/ unihub/ ^static\/(?P<path>.*)$ The current path, catalog/, didn't match any of these. My files look like this: /TFGsWeb/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'unihub.apps.UnihubConfig', ] ROOT_URLCONF = 'TFGsWeb.urls' STATIC_URL = '/static/' /TFGsWeb/urls.py from django.contrib import admin from django.urls import path # Use include() to add paths from the unihub application from django.urls import include # Add URL maps to redirect the base URL to our application from django.views.generic import RedirectView urlpatterns = [ path('admin/', admin.site.urls), path('unihub/', include('unihub.urls')), path('', RedirectView.as_view(url='/unihub/', permanent=True)), ] # Use static() to add url mapping to serve static files during development (only) from django.conf import settings from django.conf.urls.static import static urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) /TFGsWeb/unihub/urls.py from django.urls import path from . import views urlpatterns = [ ] I don't understand why this catalog/ appears when I see no reference to any app or path named catalog/ in the files I did modify. I'd also like to upload this project to my github … -
Django: Remove / of slug
The issue I am dealing with is "Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens." The following is my form field validation: def clean_slug(self): slug = self.cleaned_data['slug'] if slug.endswith('/'): self.cleaned_data['slug'] = slug[:-1] slug_check = self.organizer.events.filter(slug=slug).exclude(pk=self.event.pk).exists() if slug_check: raise forms.ValidationError(_("Slug already exists"), code='duplicated_slug') return slug Somehow Django is not considering my self.cleaned_data['slug'] = slug[:-1]when is_valid() is being called. Do you know why? -
How I can get id selector connected with item id
I have list of buttons on my app list with items, which I can like. I am using here id selector. I would like to use id selector with id of item - to make id selector unique. How I can get id of item and connect them to id selector for this result? 1. #voteup-2 2. #voteup-section-2 I was trying use data-id Here is my jquery part: <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click', '#voteup', function(event){ event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: "{% url 'qa:answer_voteup' %}", data: {'id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: 'json', success: function(response){ $('#voteup-section').html(response['form']) console.log($('#voteup-section').html(response['form'])) }, error: function(rs, e){ console.log(rs.responseText); }, }); }); }); </script> Button in html part, here I have id selector with voteup-section-{{ answer.id }} <div id="voteup-section-{{ answer.id }}" data-id="{{ answer.id }}"> <form action="{% url 'qa:answer_voteup' %}" method="post"> {% csrf_token %} <button type="submit" id="voteup-{{ answer.id }}" name="answer_id" value="{{ answer.id }}" {% if is_voted_up %} class="btn btn-danger btn-sm">Voted up! {% else %} class="btn btn-primary btn-sm">Vote up!{% endif %} <span class="badge badge-light">{{ answer.total_vote_up }}</span></button> </form> </div> -
Cant go to adming login
I want to acces my /admin page, but I cant do anything becouse of this error:Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^admin/ ^ ^$ [name='index'] ^ ^contact/ [name='contact'] ^blog/ The current path, admin, 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. -
Refresh instance reversed relation in Django
I'm trying to refresh a reversed "RelatedManager" relation. I tried with refresh_from_db and prefetch_related(None). Example: class Autor: name = models.Charfield(...) class Book: autor = models.ForeignKey(Autor) title= models.Charfield(...) I need to make some operations with an autor my_autor = Autor.objects.get(id=1).prefetch_related('book_set') print(my_autor.book_set.all()) # Returns empty queryset # Manually create Book instances related with the autor # Note that I do not want to call .add() or neighter book_set.create() Book.objects.create(autor=my_autor, title="Test") # Now if I call .all() again, returns the previous cached queryset print(my_autor.book_set.all()) # Same empty queryset At this point,I want to refresh only the book_set to make some calcs, but performing the minimun SQL queries, just fetch the Book set from Autor. I'm forced to do it this way because of the app workflow. # I tried with refresh_from_db, but 'book_set' is not a field in Autor. my_autor.refresh_from_db() print(my_autor.book_set.all()) # Same empty queryset # my_autor.refresh_from_db('book_set') raise Exception # I also tried .prefetch_related(None) my_autor.book_set.prefetch_related(None) print(my_autor.book_set.all()) # Same empty queryset # Finally, I tried to perform a filter, but I doesnt clear the cached query books = my_autor.book_set.all().filter() print(books) # [<Book Test>] print(my_autor.book_set.all()) # Same empty queryset How could I refresh this relation without creating additional queries? Or just clear the cached queryset … -
django-tellme rendering problem in django admin
I installed this app but when I run it, I get a error in django admin, it does not rendering HTMl text as it should have done, I'm not familiar with how to make these customizations, I have also posted a issue, if it help in understanding my problem, I hope I get a solution for this. Thanks