Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I extend a Django Form class?
I want to create multiple, similar forms based on this one: class DatabaseForm(forms.Form): label = "Database label" # This does not work, but I also can't define it in __init__ method, as I can't access self below in "name" field name = forms.BooleanField(label=label, required=False) username = forms.CharField(label="Username", required=False) password = forms.CharField(label="Password", required=False) where I only change the label, like this: class MySQLForm(DatabaseForm): label = "MySQL" # Somehow override label of super class How can I achieve this? -
Django dynamic HTML table - row insertion issue
I'm trying to create a HTML table that the users can fill with DB data (in this case, jump parameters) that they request with a form. This data will then be used to create a chart with Highcharts. I got to the point where I successfully load the requested Jump to the table, but somehow the row is automatically erased after I insert it. Can you please tell me what I'm doing wrong? Also if you can think of a better approach to what I'm trying to do, I'm more than open to suggestions. Thanks! main/views.py @login_required def index(request): current_user = Person.objects.get(person_user=request.user) if request.method == 'GET': current_user = Person.objects.get(person_user=request.user) data = {'current_user_id': current_user.id} form = PersonJumpSelectForm(initial=data) context = { 'form': form, } return render(request, 'main/index.html', context) charts/views.py def insert_data(request): jump_requested = Jump.objects.get(pk=request.GET['date']) context = { 'jump_requested': jump_requested, } if request.is_ajax(): data = {'rendered_table': render_to_string('charts/table.html', context=context)} return JsonResponse(data) index.html <div class="row no-gutters"> <div class="col-2 chart-container form-col"> <h2>Opciones</h2> <form id="get-data-form" data-jumps-url="{% url 'charts:ajax_load_jump' %}" novalidate> {{form}} <button id="data-form-btn" insert-data-url="{% url 'charts:insert_data' %}" class="data-form_btn full-width hov green-border transparent" type="submit">Graficar</button> </form> </div> <div class="col-7 chart-container"> <div id="container2"></div> </div> <div class="col-3 table-col"> <table id="jump-table" class="data-table"> <tr> <th>Tipo de salto</th> <th>Altura</th> <th>Tiempo de salto</th> <th>Velocidad</th> <th>Potencia</th> … -
Vue in Django app - How to setup Vue instance from static js files
I'm struggling with initializing the vue instance from separate js file (I don't ant to keep the code inside each template html). template: <html> <head> <title>Cinema project</title> <meta name="viewport" content="width=device-width, initail-scale=1.0"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://code.jquery.com/jquery-3.4.0.min.js"></script> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> {% load static %} </head> <body> <div class="container"> <ul class="list-group mt-2"> {% for x in huj%} <li class="list-group-item">{{x}}</li> {% endfor %} </ul> [[rate]] </div> <script src="{% static 'js/vue.js' %}" type="text/javascript"></script> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </body> </html> js_file: new Vue({ delimiters: ['[[', ']]'], el:".container", data: { rate: "test", }, }) The staticfiles_dir works - I tested it with some random js code. In the above vue instance simply can't hook with my template. Is there any way to fix it ? -
Any advice for python hosting server? [closed]
I have just finished a python Django project and I need a good hosting server any advices with good price and performance -
django get queryset which is latest of other column value
I have a model with some columns, between them there are 2 columns: equipment_id (a CharField) and date_saved (a DateTimeField). I have multiple rows with the same equipment_id and but different date_saved (each time the user saves the record I save the now date time). I want to retrieve a list of records that have a specific equipment_id and is the latest saved, i.e.: | Equipment_id | Date_saved | | --- ----- | --------------------- -------- | | 1061a | 26-DEC-2020 10:10:23| | 1061a | 26-DEC-2020 10:11:52| | 1061a | 26-DEC-2020 10:22:03| | 1061a | 26-DEC-2020 10:31:15| | 1062a | 21-DEC-2020 10:11:52| | 1062a | 25-DEC-2020 10:22:03| | 1073a | 20-DEC-2020 10:31:15| Output: | 1061a | 26-DEC-2020 10:31:15| | 1062a | 25-DEC-2020 10:22:03| | 1073a | 20-DEC-2020 10:31:15| I have tried various approach without success: try: progall=Program.objects.filter(equipment_id__startswith=str(b_id_to_search)).latest('saved_date') The command doesn't work, the program goes to the except line -
Docker Compose and Django app using AWS Lighstail containers fail to deploy
I'm trying to get a Django application running on the latest version of Lightsail which supports deploying docker containers as of Nov 2020 (AWS Lightsail Container Announcement). I've created a very small Django application to test this out. However, my container deployment continues to get stuck and fail. Here are the only logs I'm able to see: This is my Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ And this is my docker-compose.yml: version: "3.9" services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . image: argylehacker/app-stats:latest command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db I'm wondering a few things: Right now I'm only uploading the web container to Lightsail. Should I also be uploading the db container? Should I create a postgres database in Lightsail and connect to it first? Do I need to tell Django to run the db migrations before the application starts? Is there a way to enable more logs from the containers? Or does the lack of logs mean that the containers aren't even able to start. Thanks for the help! -
how do I make sure a particular user is the one logged in?
so I have some code which creates a user but how do I make sure every url that the user goes to will be in his/her own "user session" such that request.user will be the user i created? def liked(request): try: sp = Spotify(auth_manager=oauth) liked = sp.current_user_saved_tracks(limit=30)['items'] spotify_user = sp.current_user() user__ , created = User.objects.get_or_create(username=spotify_user['uri'], first_name=spotify_user["display_name"]) userprofile = UserProfile.objects.get_or_create(user=user__)[0] i have other views i want only accessible to the user created or gotten from the get_or_create, i reckon I'd have to use the @login_required decorator but then again I do not know what constitutes this "login" with respect to the userI created. How do I do ensure that user is the logged in user? -
Django adding foreign key
I am working on a student assignment submission project, I have made the submission model, which has assignment as foreign key to question, student as a foreign key to the profile. I am working on some way where teacher can select the list of students who have submitted the assignment and assign marks to them, I tried the following way, but its form is not getting validated stating that "select a valid choice" Submission model class Submission(models.Model): assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE, verbose_name='assignment') student = models.ForeignKey(StudentProfile, on_delete=models.CASCADE, verbose_name='student') answer = models.URLField() time_submitted = models.DateTimeField(auto_now_add=True) marks_obtained = models.IntegerField(null=True) MarkUpdateForm class MarksUpdateForm(forms.ModelForm): class Meta: model = Submission fields = ['student', 'marks_obtained'] def __init__(self, *args, **kwargs): self.assignment_id = kwargs.pop('assignment_id', None) super(MarksUpdateForm, self).__init__(*args, **kwargs) self.fields['student'].queryset = Submission.objects.filter(assignment__id=self.assignment_id).values_list( 'student__user__username', flat=True) My view form = MarksUpdateForm(request.POST) if form.is_valid(): row = Submission.objects.get(id=assignmentId, student__user__username=form.cleaned_data['student']) row.marks_obtained = form.cleaned_data['marks_obtained'] row.save() messages.success(request, message="Marks Updated Successfully") else: print(form.errors) I tried updating my marksupdateform by overriding label_from_instance and creating custom form instead of model form, but didnt solve the error of "select a valid choice" Thank you. -
Recreate deleted django_migrations table
I am building a Django web application and I dropped the table django_migrations using psql command line and I want to recreate it. -
How to save an Inline Formset inside another?
I have the following situation: I have to create a project, and inside this project I can have multiple internships and for each internship I can have multiple interns. I was able to create and save the Internship, but I can't find a way to create the interns. Is there a way to do so? Here's my code: view.py def cadastrar_bolsa(request, projeto_id): if request.method == 'GET': projeto_editar = Projeto.objects.filter(id=projeto_id).first() if projeto_editar is None: return redirect(reverse('projeto')) form = EditForm(instance=projeto_editar) form_bolsa_factory = inlineformset_factory(Projeto, Bolsa, form=BolsaForm, extra=1) form_bolsa = form_bolsa_factory(instance=projeto_editar) form_bolsista_factory = inlineformset_factory(Bolsa, Bolsista, form=BolsistaForm, extra=1) form_bolsista = form_bolsista_factory(instance=????) context = { 'form': form, 'form_bolsa': form_bolsa, 'form_bolsista': form_bolsista, 'id': projeto_id, } return render(request, 'cadastrar_bolsa.html', context) elif request.method == 'POST': projeto_editar = Projeto.objects.filter(id=projeto_id).first() if projeto_editar is None: return redirect(reverse('projeto')) form = EditForm(request.POST, instance=projeto_editar) form_bolsa_factory = inlineformset_factory(Projeto, Bolsa, form=BolsaForm, extra=1) form_bolsa = form_bolsa_factory(request.POST, instance=projeto_editar) form_bolsista_factory = inlineformset_factory(Bolsa, Bolsista, form=BolsistaForm, extra=1) form_bolsista = form_bolsista_factory(instance=????) if form.is_valid() and form_bolsa.is_valid(): projeto_editado = form.save() form_bolsa.instance = projeto_editado form_bolsa.save() ????? return redirect('bolsas', projeto_id) else: context = { 'form': form, 'form_bolsa': form_bolsa, 'form_bolsista': form_bolsista, 'id': projeto_id, } return render(request, 'cadastrar_bolsa.html', context) I've put question marks on the part I couldn't find a way to solve. -
How to register a lookup in django?
I'm trying to use __lower to search with django, but when I run the view of it, it throws this error: Unsupported lookup 'lower' for CharField or join on the field not permitted. So, I searched for possible solutions, and found that I need to register that lookup, but I can't figure out where should I do it. The code is: from django.db.models import CharField from django.db.models.functions import Lower CharField.register_lookup(Lower) I tried running it into myapp.apps, or even manage.py shell, but got no success. Into django docs, I was not able to find any clear mention of it. How can I do it? Thanks -
How do I get the Django login api to work after extending the user object?
I've followed the documentation here to extend my user class, but now my login tests fail. I'm assuming this is due to the extended class not being linked correctly back to the django view that deals with auth. r = self.client.post('/login/', {'username': 'test@test.com', 'password': 'test'}) returns b'\n<!doctype html>\n<html lang="en">\n<head>\n <title>Not Found</title>\n</head>\n<body>\n <h1>Not Found</h1><p>The requested resource was not found on this server.</p>\n</body>\n</html>\n' I've set the AUTH_USER_MODEL in my setttings AUTH_USER_MODEL = 'api.ApiUser' I can create users in my admin, and login as normal. models.py class Company(models.Model): """ Represents a company that has access to the same missions/mission plans/etc. """ id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) name = models.TextField() logo = models.ImageField(blank=True) def __str__(self): return self.name class UserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, ) user.is_admin = True user.save(using=self._db) return user class ApiUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) company = models.ForeignKey(Company, null=True, … -
Как правильно настроить gunicorn для django проекта?
Я установил gunicorn, создал файл gunicorn_config.py с содержимым: command = '/root/code/mysite/env/bin/gunicorn' pythonpath = '/usr/bin/python3' bind = '0.0.0.0:8000' workers = 3 user = 'root' limit_request_fields = 32000 limit_request_field_size = 0 raw_env = 'DJANGO_SETTINGS_MODULE=main.settings' А так же файл bin/start_gunicorn.sh с содержимым: #!/bin/bash source /root/code/mysite/env/bin/activate source /root/code/mysite/env/bin/postactivate exec gunicorn -c "/root/code/mysite/gunicorn_config.py" main.wsgi При первом запуске этого скрипта все нормально запустилось, но в settings.py был некорректно указан путь STATIC_URL = '/static/', из-за чего не отображались все изображения на сайте. После этого я исправил ошибку в пути, но теперь не могу запустить gunicorn: bin/start_gunicorn.sh:source:3: no such file or directory: /root/code/mysite/env/bin/postactivate [2020-12-27 00:59:29 +0300] [17006] [INFO] Starting gunicorn 20.0.4 [2020-12-27 00:59:29 +0300] [17006] [ERROR] Connection in use: ('0.0.0.0', 8000) [2020-12-27 00:59:29 +0300] [17006] [ERROR] Retrying in 1 second. [2020-12-27 00:59:30 +0300] [17006] [ERROR] Connection in use: ('0.0.0.0', 8000) [2020-12-27 00:59:30 +0300] [17006] [ERROR] Retrying in 1 second. [2020-12-27 00:59:31 +0300] [17006] [ERROR] Connection in use: ('0.0.0.0', 8000) [2020-12-27 00:59:31 +0300] [17006] [ERROR] Retrying in 1 second. [2020-12-27 00:59:32 +0300] [17006] [ERROR] Connection in use: ('0.0.0.0', 8000) [2020-12-27 00:59:32 +0300] [17006] [ERROR] Retrying in 1 second. [2020-12-27 00:59:33 +0300] [17006] [ERROR] Connection in use: ('0.0.0.0', 8000) [2020-12-27 00:59:33 +0300] [17006] [ERROR] Retrying in 1 second. [2020-12-27 00:59:34 … -
PDF document does not contain utf-8 encoding
I am making an application on Django. You need to add html page to PDF document. The document is being created, but the Cyrillic alphabet is smeared with squares. #views.py def fetch_pdf_resources(uri, rel): if uri.find(settings.MEDIA_URL) != -1: path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, '')) elif uri.find(settings.STATIC_URL) != -1: path = os.path.join(settings.STATIC_ROOT, uri.replace(settings.STATIC_URL, '')) else: path = None return path def export_pdf(request, pk): obj = get_object_or_404(Application, pk=pk) template_path = 'applications/applications_detail.html' context = {'applications': obj, 'to_pdf': True} response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="ApplicationDetail.pdf"' template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF(BytesIO(html.encode('UTF-8')), response, encoding='utf-8', link_callback=fetch_pdf_resources) return response #urls.py path('export_pdf/', views.export_pdf, name = 'export_pdf') -
Why am I getting this Django NoReverseMatch error?
I'm getting Django's dreaded "NoReverseMatch" error and I can't see the problem. I believe I'm doing everything correctly. When I try to go to the music application's home page at 127.0.0.1:8000/music/ I get the following error: NoReverseMatch at /music/ Reverse for 'album-delete' with arguments '(",)' not found. 1 pattern(s) tried: ['music/album/(?P<pk>[0-9]+/delete/$'] Here are my urls: # app/urls.py urlpatterns = [ path('music/', include('music.urls')), ] # music/urls.py from django.urls import path from . import views app_name = 'music' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('album/add/', views.AlbumCreate.as_view(), name='album-add'), path('album/<int:pk>/', views.AlbumUpdate.as_view(), name='album-update'), # Problem is with this url pattern: path('album/<int:pk>/delete/', views.AlbumDelete.as_view(), name='album-delete'), ] Here is the template calling the delete url: # music/index.html <form action="{% url 'music:album-delete' album.id %}" method="post"> {% csrf_token %} <input type="hidden" name="album_id" value="{{ album.id }}"> <button type="submit"></button> </form> Here is the class-based view to delete an album: # music/views.py class AlbumDelete(generic.DeleteView): model = Album success_url = 'music:index' The error is triggered by the form's action attribute because if I just set the action to blank, the error goes away. <form action="" method="post"> <!-- No error --> -
How do i get the username of a logged user writing a text and display it beside the text permanently in Django
Please see the image, i want to add name of the person entering the text at the end of the text. [1]: https://i.stack.imgur.com/qd5fn.png Here is my code for template. {% extends 'learning_logs/base.html' %} {% block content %} <p>Topic: {{ topic }}</p> <p>Entries:</p> <p> <a href="{% url 'learning_logs:new_entry' topic.id %}">add new entry</a> </p> <ul> {% for entry in entries %} <li> <b><p>{{ entry.date_added|date:'M d, Y H:i' }}</p></b> <p>{{ entry.text|linebreaks }}</p> <a href="{% url 'learning_logs:edit_entry' entry.id %}">edit entry</a> </p> </li> {% empty %} <li> There are no entries for this topic yet. </li> {% endfor %} </ul> {% endblock content %} Here is my views function for topic. def topic(request, topic_id): """Show a single topic and all its enteries""" topic= Topic.objects.get(id=topic_id) entries= topic.entry_set.order_by('-date_added') context= {'topic': topic, 'entries':entries} user_if= request.user return render(request, 'learning_logs/topic.html', context) Here is my Topic and Entry models. from django.db import models from django.contrib.auth.models import User # Create your models here. class Topic(models.Model): """A topic user is learning about""" text=models.CharField(max_length=200) date_added=models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): """Return a string representation of the model.""" return self.text[:50] +"..." class Entry(models.Model): """Something specific learned about the topic""" topic=models.ForeignKey('Topic',on_delete=models.CASCADE) text=models.TextField() date_added=models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural='entries' def __str__(self): """Return a string … -
Putting a Django app under a path on a webserver
I am developing a Django app, and testing it on http://localhost:8000 on the development server. My urls file has urls in the sorts of ; path('somepath1/', myviewclass.function1, name='view_name1'), path('somepath2/', myviewclass.function2, name='view_name2'), etc I have some static links to views in some of the templates using the {% url 'view_name1' %} tags. When I navigate the app, as I click links the paths work correctly : If I goto http://localhost:8000/somepath1/, and then click on a link to another view I get the url : http://localhost:8000/somepath2/ When I put the app on the webserver under the url : http://myserver.com/myapp, as I click the links and submit forms the paths start accumulating : If I goto http://localhost:8000/somepath1/, and the click on a link to another view I get the url : http://localhost:8000/somepath1/somepath2/, and that is not matched in the urls so I get a 404. How do I prevent this ? Thanks Regards -
Rest Framework Simple JWT: AttributeError at /api/token/
I'm using simple_jwt for authenticating Django_rest_api but getting this response on an attempt to login: AttributeError at /api/token/ 'str' object has no attribute 'decode' Packages: Django==3.1.4 djangorestframework-simplejwt==4.4.0 -
Django Child template not loading the form
I have a base Django template: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'CS/base.css' %}"> </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="/">Cheat Sheet</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'CS-home' %}">Home</a> <!-- <a class="nav-item nav-link" href="">About</a> --> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> <a class="nav-item nav-link" href="#">Login</a> <a class="nav-item nav-link" href="#">Register</a> </div> </div> </div> </nav> </header> {% block body %} {% endblock body %} <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </body> </html> And a Child Template home.html: {% extends "CS/base.html" %} {% block body %} {% endblock body %} {% block content %} <div class="container"> <form action="/URL/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> </div> {% endblock content %} And my views.py function to load the home.html file: def home(request): context={} context['form']=urlForm return render(request,'CS/home.html',context) When I try to render the form in the child template … -
Django production server on digital ocean cant access images from spaces
When using a local server everything works perfectly. I can upload an image from my local server to Digital Ocean spaces I can open a url (from spaces) with my local server and convert it to bytes. url = 'https://wwww.myspaces.com/my-spaces-static/images/xxxxxxxxxxxxxxxx.png' ssl._create_default_https_context = ssl._create_unverified_context resp = urllib.request.urlopen(url) image = np.asarray(bytearray(resp.read()), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) The code above fails however when i switch from my local server to my digital ocean production server. I have recently created a domain and https access with letsEncrypt on my Digital Ocean droplet. I am uncertain to what i'm missing. Is this a problem with SSL? I am not sure how to correctly debug this to get more detail on why the code on my production server is failing. -
Problems Rendering a function in Django
@smokesignal.on('rfid') def _RFID_cb(request,payload): print(payload) context={"payload":payload,'tableheader':['EPC-96','AntennaID','PeakRSSI','LastSeenTimestampUTC','TagSeenCount']} return render(request,"index.html",context) def tag_seen_callback(llrpMsg): """Function to run each time the reader reports seeing tags.""" tags = llrpMsg.msgdict['RO_ACCESS_REPORT']['TagReportData'] #print(tags) if tags: smokesignal.emit('rfid', { 'tags': tags, }) The print shows : [{'EPC-96': b'8a4b6028555555558a4b6028', 'AntennaID': (1,), 'PeakRSSI': (-43,), 'LastSeenTimestampUTC': (1608938708959031,), 'TagSeenCount': (1,)}] When I try to render the _RFID function I get this error: builtins.TypeError: _RFID_cb() missing 1 required positional argument: 'payload' -
How to change the default settings of warpdrive in a django Docker file?
I'm using Docker to build a Django Application using Apache and mod_wsgi(python package). I followed this tutorial by Graham Dumpleton (https://www.youtube.com/watchv=H6Q3l11fjU0&list=PLW4uuEXFgYkPDCwo7kT73P6SYVbvvIDl4&index=6&t=2s). I'm using warpdrive package because it automates few tasks like installing requiments.txt, using mod_wsgi as a default WSGI server, and a few more. The default settings of warpdrive are 5 threads and 1 process which I think is too low for my Django API as you can do only 5 concurrent requests (threads*process=concurrent requests). How to change the default threads, processes, and other configurations of warpdrive? I tried using the below command in the Dockerfile but it didn't change the threads. CMD [ "warpdrive", "start" ,"--threads","10"] Dockerfile FROM python:3 RUN apt-get update && \ apt-get install -y --no-install-recommends apache2 apache2-dev locales && \ apt-get clean && \ rm -r /var/lib/apt/lists/* ## Installing MS ODBC SQL SERVER 2017 for pyodbc library RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - RUN curl https://packages.microsoft.com/config/ubuntu/20.04/prod.list > /etc/apt/sources.list.d/mssql-release.list RUN apt-get update && ACCEPT_EULA=Y apt-get install -y msodbcsql17 RUN apt-get update && ACCEPT_EULA=Y apt-get install -y mssql-tools RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc RUN /bin/bash -c "source ~/.bashrc" RUN apt-get install unixodbc-dev RUN adduser --disabled-password --gecos "Warp Drive" --uid 1001 … -
Logged in user information incorrectly dispalyed
I have created a page to update User profile. If I try to update a value of user with existing user, error is thrown as expected, however the variable user.username in profile.html shows the value I am trying to update. My query is why {{ user.username }} is picking up the incorrect value even though the save() method is not called. profile.html <div class="content p-3"> <div><img class="rounded-circle" src="{{ user.profile.image.url }}" width="100" height="100"></div> <div>{{ user.username }}</div> <div>{{ user.email }}</div> </div> <div class="w-25"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset> <legend>Profile Info</legend> {{ user_form | crispy }} {{ profile_form | crispy }} </fieldset> <input class="mt-3" type="submit" value="Update"> </form> </div> forms.py class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] views.py @login_required def profile(request): if (request.method == "POST"): user_form = UserUpdateForm(request.POST, instance=request.user) profile_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if (user_form.is_valid() and profile_form.is_valid()): user_form.save() profile_form.save() messages.success(request, f"Your profile is updated successfully") return redirect("profile") else: messages.error(request, f"Failed to update profile") else: user_form = UserUpdateForm(instance=request.user) profile_form = ProfileUpdateForm(instance=request.user.profile) return render(request, 'User/profile.html', {'user_form': user_form, 'profile_form': profile_form} -
Why does ubuntu end up with different versions of python and pip and django gets installed globally instead of in the virtualenv?
I'm trying to learn django and i installed ubuntu bash on windows to use it there, ubuntu comes with python preisntalled but not pip so i installed pip and updated it but when i use pip3 -V it shows the past version, there is two pip installs and i can't figure out how to upgrade the one that python uses, also i installed django when i was already inside the virtualenv but it was installed globally, so i guess is because the same problem, does anyone know how can i have just one python and one pip installed? so none of this happens? i reinstalled ubuntu cuz got really annoyed. -
django get record which is latest and other column value
I have a model with some columns, between them there are 2 columns: equipment_id (a CharField) and date_saved (a DateTimeField). I have multiple rows with the same equipment_id and but different date_saved (each time the user saves the record I save the now date time). I want to retrieve the record that has a specific equipment_id and is the latest saved, i.e.: | Equipment_id | Date_saved | | --- ----- | --------------------- -------- | | 1061a | 26-DEC-2020 10:10:23| | 1061a | 26-DEC-2020 10:11:52| | 1061a | 26-DEC-2020 10:22:03| | 1061a | 26-DEC-2020 10:31:15| | 1062a | 21-DEC-2020 10:11:52| | 1062a | 25-DEC-2020 10:22:03| | 1073a | 20-DEC-2020 10:31:15| I want to retrieve for example the latest equipment_id=1061. I have tried various approach without success: prg = Program.objects.filter(equipment_id=id) program = Program.objects.latest('date_saved') when I use program I get the latest record saved with no relation to the previous filter