Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ForeignKey default value in new table
I need to set a default value to a ForeignKey after the model has been migrated. Is this possible? For instance, a "meal" Class has a ForeignKey named "drinks". Some drinks are added, Pepsi, Coke,.. to the drink table. In the meal Class is it possible to name Coke as the default? From the docs I see only that the index can be used. That implies that I would have to ensure that I added the correctly named default into the correct index. Then I would be stuck with it hard coded in. How is it done so that changes to the default can be done after the fact? An example would be great if anyone has one handy. Best regards. -
How do I create a model that stores multiple images in relation to another model
How do I create a Django model PaperImage that stores multiple images that relates to another Django model Papers? And I have to afterwards access all the images related to one Papers object. How should my views.py should be in order save both these relative to eachother? #models.py class Papers(models.Model): yearChoices = [] grades = ( #some grades ) termChoices = ( #some terms ) for r in range(1985,(datetime.datetime.now().year)): yearChoices.append((r,r)) subject_list = ( #some subjects ) province_list = ( #some provinces ) year = models.DateField(choices=yearChoices,default=datetime.datetime.now().year) term = models.CharField(choices=termChoices,default=1,max_length=15) subjects = models.CharField(max_length=1,choices=subject_list,help_text="Choose what subject the post belongs to.",default='u') grade = models.IntegerField(choices=grades,default=10) school = models.CharField(max_length=254,help_text="Which school's paper is this?") province = models.CharField(max_length=254,choices=province_list,default=1) education_zone = models.CharField(max_length=254,blank=True) class PaperImage(models.Model): paper = models.OneToOneField(Papers, related_name='paper',blank=True,null=True, on_delete=models.CASCADE) images = CloudinaryField("images") -
How to handle JS script with Django template language?
I'm trying to use django template language to manipulate JS scripts, but when I try appears the following error I checked the error in case there is a misstyped code, but I couldn't detect it. How is the best way to handle multiple JS script with multiple HTML files in Django template language? Infraestructura.html {% extends "Portafolio/layout.html" %} {% block scripts %} <script src = "{% static 'Portafolio/scriptinfra.js' %}" type="text/javascript"></script> {% endblock %} {% block content %} <form class="form mt-5" id="infra"> <h1>Factibilidad Técnica y Operativa</h1> <h2>Análisis de Infraestructura</h2> <main class="container"> <section class="row"> <div class="col-lg-4 mb-2"> <input name='infs' class="form-control" type="text" placeholder="Infraestructura"> </div> <div class="col-lg-4 mb-2"> <input name='time' class="form-control" type="text" placeholder="Tiempo"> </div> <div class="col-lg-4 mb-2"> <input name='cost' class="form-control" type="text" placeholder="Costo Mensual"> </div> </section> </main> <nav class="btn-group"> <button id='add' class='btn btn-success' type='button'> <i class="fa fa-plus-square"></i> Añadir </button> <button id='rem' class='btn btn-danger' type='button'> <i class="fa fa-minus-square"></i> Eliminar </button> </nav> </form> <form class="form mt-3"> <div class="d-grid gap-2 mt-3"> <a class="btn btn-lg btn-primary" href="tecnicoequipo.html">Siguiente</a> </div> <div class="d-grid gap-2 mt-3"> <a class="btn btn-lg btn-primary" href="financierobeneficio.html">Atrás</a> </div> </form> {% endblock %} layout.html {% load static %} <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" … -
Why django template loader is case-sensitive in production but not in development
I'm using manage.py runserver on a MacOs Catalina OS as development. I have some templates that fit my built-in class based views. For example: CuadroDeControl_detail.html LoteDeMedio_list.html TipoDeMedio_detail_tablaCuadros.html CuadroDeControl_detail_resumen.html LoteDeMedio_list_tabla.html TipoDeMedio_list.html CuadroDeControl_detail_tablaMetodos.html MetodoDeControl_detail.html TipoDeMedio_list_tabla.html LoteDeMedio_confirm_delete.html MetodoDeControl_detail_resumen.html dropdown_CuadroDeControl.html LoteDeMedio_create.html TipoDeMedio_confirm_delete.html dropwdown_CuadroDeControl.html LoteDeMedio_detail.html TipoDeMedio_detail.html LoteDeMedio_detail_resumen.html TipoDeMedio_detail_resumen.html Here is an example of a working view: 58 class TipoDeMedioDetailView(AreaCalidadMixin, DashboardMixin, DetailView): 59 model = TipoDeMedio Note that my views do not explicitly set template_name. On my production environment, all my views load just fine.Django's template loader knows that the corresponding template to the view is TipoDeMedio_detail.html However, on my production environment, which is set up with apache2 and mod_wsgi on a Ubuntu 20.04.2 LTS x86_64 Linode VM, the template loader fails to load the template of the same view, because it searches for it in all lowercase. Here is an example: Request Method: GET Request URL: http://45.79.4.38/calidad/TipoDeMedio/lista Django Version: 3.1.6 Exception Type: TemplateDoesNotExist Exception Value: calidad/tipodemedio_list.html Exception Location: /home/jonatan/django-rodam/venv/lib/python3.8/site-packages/django/template/loader.py, line 47, in select_template Python Executable: /home/jonatan/django-rodam/venv/bin/python Python Version: 3.8.5 Python Path: ['/home/jonatan/django-rodam/mysite', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/jonatan/django-rodam/venv/lib/python3.8/site-packages'] Server time: Mon, 21 Jun 2021 18:24:19 -0500 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/jonatan/django-rodam/mysite/templates/calidad/tipodemedio_list.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/jonatan/django-rodam/mysite/login/templates/calidad/tipodemedio_list.html … -
How to get a variable in another js file in django?
I am trying to use moovit embebed services. I want to put an origin and destination address automatically. So, I have this function in a js file that receives the origin address and open a new window. I don't know how to get this data from js in html. function print_moovitmap(origin) { origin_ad = origin; //Origin_ad is global window.open('/new', '_blank'); } I am working with django. I have also origin_ad in a form field with an id but I couldn't access to this form field in html. It gives me null. origin_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={'class':'data_aux data','id':'origin_address'})) In html (null): console.log(document.getElementById('origin_address')); And in new.html: <div class="mv-wtp" id="mapa_moovit" data-to='' data-lang="es"> <script> var m = document.getElementById('mapa_moovit'); m.setAttribute("data-to", "Central Park"); m.setAttribute("data-from", "Times Sq"); </script> {% load static %} <script src="{% static 'moovit_script.js'%}"></script> </div> I need to set atribute data-from to origin_ad but I don't know how. Thank you -
How to do aritmethic operations with django queries and .count?
I want to get a value by using the amount of objects I have in my database and making operations over that and then displaying the result in the template (So I'm passing this value in the context). The answers I found was about making operations with model fields, and that doesn't help me. This is what I tried to do in the view. (status is a charfield with options, but it could be anything) def get_context_data(self, **kwargs): context = super(Index, self).get_context_data(**kwargs) amount_one = mymodel.objects.filter(status='status1').count amount_two = mymodel.objects.filter(status='status2').count total_amount = amount_one + amount_two result_amount = (amount_one * 100) // total_amount context['result'] = result_amount return context This doesn't work, but you could get the idea of what I'm trying to do. -
Geo redirect same domain after slash with AWS
Lets say i have a website called abc.com, I'm planning on scale the website based on geo location, I have two ways in mind. The first way: paris.abc.com, london.abc.com The second way: abc.com/paris, abc.com/london The first way seems simpler with AWS, The idea being hosting different subdomains to different instances with different databases, Each subdomain is basically a completely different website. But I prefer the second way, What i have in mind is, Setting up geo redirect to different instances but to the same domain, "abc.com", Then have instance A redirect abc.com to abc.com/paris inside my django project, Have instance B do the same thing to abc.com/london. Now if i do it this way, What would happen if someone from london, Instead of typing the url abc.com, They typed abc.com/paris? Would they be able to access the paris page via instance A? (This is what i want, I want them to have acess) Or the page will be empty since the django project inside instances B(london) have no page called paris. Assuming both ways are achievable, If someone logged in paris.abc.com or abc.com/paris, How do u keep them logged in If they go to page london.abc.com or abc.com/london, A shared … -
Nothing renders on Django Template
building a news aggregator. I am collecting reddit and twitter posts using their APIs, and then I create a model object for each post, which is stored in my database. I'm then passing in these post objects as context into my template, looping through the context in the template with the hope to display the posts 'html' attribute (A model field I created) onto the page, which in turn embeds the post onto the screen. However, I can't figure out why my template page is still blank. No errors are thrown, and the model objects are being created because I can see them in the admin panel. I'll provide my models.py, views.py, and template to be taken a glance at. I appreciate and am grateful for any help/advice. models.py class Post(models.Model): post_type = models.CharField( max_length=20, null=True, blank=True) root_url = models.CharField(max_length=200, default="") html = models.TextField(default="") created_at = models.DateTimeField(auto_now_add=True) views.py def main(request): all_posts = Post.objects.all context = {'posts': all_posts} return render(request, "test.html", context) template {% block content %} {% autoescape off %} <div class="container"> <div class="row"> <div class="col-6"> <h3 class='text-center'>Twitter News</h3> {% for post in posts %} {% if post.post_type == 'twitter' %} <div class="mdl-card__media" id="timeline"></div> {{ post.html }} {% endif %} … -
DoesNotExist at /accounts/login/ (delate example.com from admin page)
I'm trying to configure Django App. I logged in to Django admin page and delated "example.com" from "Site". After that, I can not access the admin page or login page. Error message is here Exception Value: Site matching query does not exist. Exception Location: /home/app_admin/venv_ruling/lib64/python3.7/site-packages/django/db/models/query.py, line 437, in get Since I can not access admin page, I can not recover "example.com" as site. How can I recover it?? I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
Add label or modifying widget on django-filter form
I'm looking for a way of specifying what the select fields in the filter form are for, this is how it looks like right now: And is hard to understand what the select inputs are for, the ideal would be to change the default option ("Unkown" and "--------") but it should be custom for each one. Already tried that but couldn't find a way to do it, it is possible? If someone knows a way of doing this it would be great. Adding a label should be the easier way, but don't know how to do it. filters.py class PatientFilter(django_filters.FilterSet): class Meta: model = Patient fields = { 'dni': ['exact'], 'first_name': ['icontains'], 'last_name': ['icontains'], 'risk': ['exact'], 'status': ['exact'], 'ubication': ['exact'], 'supervisor': ['exact'], } HTML {% if filter %} <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='inline' field_class="mr-3 mt-3" %} <div class="mt-3"> {% bootstrap_button 'Filter' button_class="btn-secondary" %} <a href="{% url 'patients' %}" class="ml-3 btn btn-secondary">Clear</a> </div> </form> {% endif %} The select inputs are foreign keys, here is its definition in models.py status = models.CharField(max_length=15, choices=STATUS_CHOICES) ubication = models.ForeignKey(Ubication, on_delete=models.CASCADE) supervisor = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) I'm using tables2 with django-filters. -
How to display content assigned to foreignkey DJango
I want to display content assigned to foreignkey. After clicking on user name display in new page all of his content. Something like in "/users/" display every users but after clicking on name go to "/users/1". class Users(models.Model): def __str__(self): return self.name image = models.CharField(blank=True, max_length=600) name = models.CharField(blank=True, max_length=80) description = models.TextField(blank=True) class Meta: verbose_name = "User" verbose_name_plural = "Users" class Content(models.Model): def __str__(self): return self.name name = models.CharField(blank=True, max_length=80) image = models.CharField(blank=True, max_length=600) description = models.TextField(blank=True) User = models.ForeignKey(Ekipa, on_delete=models.CASCADE, null=True, related_name='User') class Meta: verbose_name = "Content" verbose_name_plural = "Content" -
Dynamic Fields On A Serializer For A ForeignKey
I set up a serializer that is able to dynamically serialize the desired fields as specified in the Django Rest Framework docs. class DynamicFieldsModelSerializer(serializers.ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) >>> class UserSerializer(DynamicFieldsModelSerializer): >>> class Meta: >>> model = User >>> fields = ['id', 'username', 'email'] >>> >>> print(UserSerializer(user)) {'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'} >>> >>> print(UserSerializer(user, fields=('id', 'email'))) {'id': 2, 'email': 'jon@example.com'} How would I then add in a model that is related by ForeignKey to this and dynamically serialize the desired fields from that model? We could make the models class User(models.Model): id = IntegerField() username = CharField() email = EmailField() class Vehicle(models.Model): color = CharField() type = CharField year = DateField() driver = ForeignKey(User) and then based on the view either include color, type, year, or any combination of … -
Django admin model query url string on NOT EQUALS
I have a simple Django ForeignKey relationship between two models in postgreSQL. The logic here is the Sample object can optionally have a foreign key into a type of sample control. from django.contrib.postgres.fields import CICharField from django.db import models class Sample(models.Model): controls_applied = models.ForeignKey(SampleControl, null=True, blank=True, on_delete=models.SET_NULL) class SampleControl(models.Model): id = CICharField(max_length=200, primary_key=True) On the admin changelist for Sample, I am trying to create filter that queries all or none of Samples that have a specific control (in this case, we'll use a SampleControl with id='runcontrol'). I'm trying to craft the specific URI string to append to my changelist url as I have other filters I'm trying to run in conjunction. To get all samples with controls_applied= 'runcontrol', I can simply append the following string to my URL (notice the reference to the id of the foreign key): ?controls_applied__id=runcontrol But if I want to get all samples that are not run control, it's more complicated. Wasn't sure what to do, so I decided to use 'startswith', which has a convenient 'notstartswith' companion that will do the inverse. When I use this, I see that the following works: ?controls_applied__id__startswith=runcontrol However, the inverse ?controls_applied__id__notstartswith=runcontrol gives me an error: Unsupported lookup 'notstartswith' for … -
Financiamiento() got an unexpected keyword argument 'MontoProyecto'
I'm trying to make a post request, I have created the models as well, but for some reason, it is giving me the following error I understand that this mean there is some mistyped, but when I check the html and views.py, I don't see any mistake, everything should be in order financiamiento.html {% extends "Portafolio/layout.html" %} {%block content %} <br> <div class="text-center"> <form action="{% url 'financiamiento'%}" method="POST" style="max-width:800px;margin:auto;"> {% csrf_token %} <h1 class="mt-5">Perspectiva Financiera</h1> <h1 class="h3 mb-10 mt-2">Financiamiento</h1> <label class="sr-only"></label> <input name= "MontoProyecto" type="text" id="MontoProyecto" placeholder="Monto Aporte Proyecto"class="form-control"> <label class="sr-only"></label> <input name= "MontoPropio" type="text" id="MontoPropio" placeholder="Monto Aporte Propio"class="form-control"> <label class="sr-only"></label> <input name="MontoBanca" type="text" id="MontoBanca" placeholder="Monto Aporte Banca"class="form-control"> <label class="sr-only"></label> <input name="MontoPublico" type="text" id="MontoPublico" placeholder="Monto Aporte Publico"class="form-control"> <div class="d-grid gap-2 mt-3"> <input type="submit" class="btn btn-lg btn-primary"> </div> </form> </div> {% endblock %} views.py from django.http.response import HttpResponse from django.shortcuts import redirect, render from django.http import HttpResponse from .models import Proyecto, Financiamiento # Create your views here. def index(request): return render (request, "Portafolio/index.html",{ "financiamiento":Financiamiento.objects.all() }) def registroproyecto(request): if request.method == 'POST': NombreProyecto = request.POST.get('NombreProyecto') ResponsableProyecto = request.POST.get('ResponsableProyecto') EvaluadorProyecto = request.POST.get('EvaluadorProyecto') DescripcionProyecto = request.POST.get('DescripcionProyecto') Proyecto.objects.create(NombreProyecto=NombreProyecto, ResponsableProyecto=ResponsableProyecto, EvaluadorProyecto=EvaluadorProyecto, DescripcionProyecto=DescripcionProyecto) return redirect("/Portafolio") return render (request, "Portafolio/RegistroProyecto.html") def financiamiento(request): if request.method == 'POST': MontoProyecto = … -
django nginx upstream prematurely closed connection while uploading large data
I am getting this error: upstream prematurely closed connection while reading response header from upstream when I try to upload large data from an excel file to the server. I tried with only 10000 inputs with 4 rows each. It doesn't do this when I try it on my localhost, so this might be the remote server's config. This is what I currently have in my nginx.conf file: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; client_max_body_size 20M; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } I added the client_max_body_size 20M; line and restarted nginx but it was the same. -
Django with Heroku doesn't server static files except admin files
I'm trying to deploy my project to heroku. Everything is working, but without static files. I get such exception form browser: artyom-blog-v2.herokuapp.com/:1 Refused to apply style from 'https://artyom-blog-v2.herokuapp.com/static/bootstrap/dist/css/bootstrap.min.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. artyom-blog-v2.herokuapp.com/:9 GET https://artyom-blog-v2.herokuapp.com/static/jquery/dist/jquery.min.js net::ERR_ABORTED 404 (Not Found) artyom-blog-v2.herokuapp.com/:10 GET https://artyom-blog-v2.herokuapp.com/static/bootstrap/dist/js/bootstrap.min.js net::ERR_ABORTED 404 (Not Found) Code: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = '/static/' STATIC_DIR = BASE_DIR / 'posts' / 'static' STATICFILES_DIRS = [STATIC_DIR] # NEED STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' How to solve it? -
Simple python object has no attribute and cannot set queryset as variable
I'm new to python and django and am receiving the following attribute error: AttributeError at /account/1/ 'Account' object has no attribute 'subscribers_set' I don't know why this happens because one account can have many subscribers. In the shell I can run a query for an account that will return all the subscriber objects, e.g. account.subscriber_set.all() returns <QuerySet [<Subscriber: bob@bob.com>, <Subscriber: sally@salhurst.com>, <Subscriber: jessy123@something.com>]> - but for some reason I can't set the queryset to a variable: trying to set variable with subscribers = account.subscribers_set.all() returns error AttributeError: 'Account' object has no attribute 'subscribers_set' In my views.py I have this account function: def account(request, id): account = Account.objects.get(id=id) subscribers = account.subscribers_set.all() # error here? context = {'account': account, 'subscribers': subscribers} return render(request, 'accounts/account.html', context) And my view: {% extends 'accounts/main.html' %} {% block content %} <h1>Account Page for {{account}}</h1> <p>Email Address: {{account.email}}</p> {% for sub in subscribers %} <p>{{subscriber}}</p> {% endfor %} {% endblock %} And url.py: urlpatterns = [ path('account/<str:id>/', views.account, name="account"), ] The class model is basically just the user model: class Account(AbstractUser): pass And there's a one:many relationship between Accounts and Subscribers: class Subscriber(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, null=True, blank=True) email = models.CharField(max_length=100, null=True) date_joined = … -
Django intermediary model
I dont understand Django Intermediary models at all. Let's say that i want to add one more additional field to User model, and store relationship between two users in another model(intermediary) like this: class Contact(models.Model): user_from = models.ForeignKey(User...) user_to = models.ForeignKey(User...) ... And the field i want to add is: following = models.ManyToManyField('self', through=Contact, related_name='followers', symetrical=False) What really happen when i call user_object.followers.all() and what is the difference between user_object.following.all() are they both the same? -
Django error with template print variables
Why is Django returning <django.contrib.messages.storage.fallback.FallbackStorage object at 0x000002503DA6F188> when I tried to print a variable in the template -
HTML/Django - Carousel with one picture active and the before and after translucent
I was not sure how to word my question, and I really don't have any example code to show because I have tried 100 different searches and can't seem to get it to work... I am using Django to create a website and the designer specified that I need to have a section like below: The image It looks like it would be a carousel with the active picture in the middle, and one inactive picture on each side and translucent. The arrows are on either side and not below. I am hoping I was clear enough and this is a somewhat simple solution. Thank you for you help in advanced! -
python telegram bot to get next question I need to type anything
I'm working with Django and Python Telegram Bot, the problem that I have is that when the conversation starts and I get to my 3rd question and answer, I need to type anything again in order to get the next question As you can see in the picture if I dont type 'OK' I do not get the next question. This is my code GET_CLIENTE, GET_TELEFONO, SET_MENU, SET_TELEFONO, SET_CLIENTE, SET_NOMBRE, SET_EMAIL, GET_EMAIL, RESPUESTAS = range( 9) def cliente(update: Update, _: CallbackContext): nombre = Cliente.objects.filter(id=1)[0] nombre = str(nombre) update.message.reply_markdown_v2( nombre, reply_markup=ForceReply(selective=True), ) def set_nombre(bot, update): message = 'Dame el nombre completo de la persona' pass def start(update: Update, _: CallbackContext) -> None: """Send a message when the command /start is issued.""" keyboard = [['Clientes', 'Reporte']] message = 'Selecciona la Opción deseada' reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True, resize_keyboard=True) update.message.reply_text(message, reply_markup=reply_markup) return SET_MENU def set_menu(update: Update, _: CallbackContext) -> None: """ Set option selected from menu. """ keyboard = [['Alta', 'Actualizar']] message = 'Qué vamos a hacer' reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True, resize_keyboard=True) update.message.reply_text(message, reply_markup=reply_markup) return SET_CLIENTE def set_cliente(update: Update, _: CallbackContext) -> None: message = 'Dame el nombre completo de la persona' update.message.reply_text(message) return GET_CLIENTE def get_nombre(update: Update, context: CallbackContext) -> None: nombre = … -
get dict value from prefect_related data without creating nested lists
I'm getting values from multiple models using the snippet below: a = App1.objects.all().prefetch_related("app2", "app3").filter(id=self.id) and getting results like this app_1 = [x.app2.values() for x in a] this result creates [<QuerySet [{'field1': value1, 'field2': value2,......}]>] It seems unnecessary (perhaps I am overcomplicating the process) to create a list of list of dict just to get values app1 Is there a way to get the inner dict without having to reference something like print(app_1[0][0].get("field1")) -
Escaping quotes in django template within javascript
I'm having trouble figuring out how to handle the quotes in the following: var attributes = { Description: "<a href="{% url 'project_map' project.id %}">{% url 'project_map' project.id %}</a>" } The link text will render as expected but the href resolves to a blank. I've tried escaping the quotes and other attempts to shift things around with no joy. This is django tempting language mixed with javascript. -
Setting up Django AnonymousUser logins with djangorestframework-simplejwt web tokens
I'm using djangorestframework-simplejwt to handle authentication on a project I'm working on using refresh and access tokens. I'd like to implement a way for users to use my note-taking app without making accounts. I was thinking of using Django's AnonymousUser object for this. The problem is I can't find anything online that describes how to do this with JSON web tokens. I tried logging in by sending in null and empty strings for the username and password, but my backend gave me a response of 400 BAD REQUEST. What should I add to my backend to allow users to click on a link and receive refresh/access tokens as AnonymousUser? authentication/serializers.py from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework import serializers from .models import ErsatzNoteUser class ErsatzNoteUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) password = serializers.CharField(min_length=8, write_only=True) class Meta: model = ErsatzNoteUser extra_kwargs = { 'password': { 'write_only': True } } fields = [ 'email', 'password' ] def create(self, validated_data): password = validated_data['password'] instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class ErsatzNoteTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super(ErsatzNoteTokenObtainPairSerializer, cls).get_token(user) token['user'] = user.email return token authentication/views.py from rest_framework import status, permissions from rest_framework.exceptions import AuthenticationFailed from rest_framework.response import Response from rest_framework.views … -
Posting comments with django-comments-xtd returns SQL syntax error
I'm trying to implement django-comments-xtd on my blog for the first time. Almost everything seems to be well, except that I'm getting this error when posting (authenticated user) or confirming (anonymous user) comments: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ORDER BY django_comments_xtd_xtdcomment.thread_id ASC, `django_comments_x...' at line 1") Any advice on how to resolve it? I'm using MySQL 8.0, but I've also tested with 5.6 and still get the same error.