Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Annotate - Concat from last created ManyToMany Object Fields
class User(models.Model): name=CharField() class Address(models.Model): user= Foreignkey(user, related_name="Addresses") buildingname=CharField() subbuildingname=CharField() town=CharField() ... I have a models like top and want to extract data as list below. { [ ['USERNAME1', 'A XYZBUILDING 14 Drain St. '], ['USERNAME2', 'C XXXBUILDING 13 Drain St. '], ['USERNAME3', 'B ZZZBUILDING 12 Drain St. '], ... ] } Also as a workaround, this is a closest thing to the answer but i could not make it done without looping every user or executing raw sql in extra field. I want to achive this with Django Object Relational Mapping. address_subquery = Address.objects.filter(user__id=F('pk')).order_by('created') User.objects.filter(**my_custom_filters).annotate( subbuildingname_str=Subquery(address_subquery.values('subbuildingname')[:1], output_field=CharField()), street_str=Subquery(address_subquery.values('street')[:1], output_field=CharField()), buildingname_str=Subquery(address_subquery.values('buildingname')[:1], output_field=CharField()), buildingnnumber_str=Subquery(address_subquery.values('buildingnnumber')[:1], output_field=CharField()), ).annotate( address_text_str=Concat( 'subbuildingname_str', Value(' '), 'buildingname', Value(' '), 'buildingnumber', Value(' '), 'street_str', output_field=CharField(), default="" ) ).values_list('name', 'address_text_str') -
How To Paginate Django REST API With Angular11?
I am trying to consume a Django REST pagination object using Angular 11. I not a total coding noob, but I am very new to Angular. Currently my Django REST api is configured to paginate every 6 items, and the total items in the object is 10. Django then outputs a "next" URL that would work fantastic with Django's string interpolation feature, but is not so easily figured with Angular. I followed this tutorial closely, not just because it has nearly complete codeblocks, but also because it's legit the only complete code example dealing with Django REST API and Angular pagination: Link to other stackoverflow question dealing with this same issue, but remains unreasolved The Django API outputs this object: Django REST API Paginated output My Angular model is thus: Angular model My pagination service: My pagination service My component: Component I'm trying to paginate My rendered result: enter image description here And the console error message: ERROR TypeError: Cannot read property 'results' of undefined Any help would be much appreciated! -
user: ["This field is required."] in DRF
I am trying to allow user to update the name of Lists they have created. However, when I attempt to POST the data I return the following error: user: ["This field is required."] I have racked my brain trying to solve this, hardcoded the username etc. but I keep turning up empty. I'd be grateful for some more expertise to assist me. Here is my view: class UpdateUserListViewSet(viewsets.ModelViewSet): serializer_class = UserListSerializer queryset = UserList.objects.all() def update(self, instance, validated_data): serializer_class = UserListSerializer if self.request.method == "POST": list_id = request.data.get('id') user = UserList(user=self.request.user.id) list_name = request.data.get('list_name') data = {'id':int(list_id), 'list_name': list_name} serializer = serializer_class(user, data=data) if serializer.is_valid(): serializer.update() return Response({'status' : 'ok'}, status=200) else: return Response({'error' : serializer.errors}, status=400) And here is my serializer: class UserListSerializer(serializers.ModelSerializer): class Meta: model = UserList fields = ['id', 'user', 'list_name'] -
Django multi tenant schemas errors while migrating
I'm working on a small project using Django and now I tried to install multi-tenant-schemas and I followed the documentation step by step but when I try to migrate I get some errors after doing this command: python manage.py migrate_schemas --shared Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/root/centrix/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/root/centrix/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/centrix/lib/python3.8/site-packages/django/core/management/base.py", line 322, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "/root/centrix/lib/python3.8/site-packages/django/core/management/base.py", line 296, in create_parser self.add_arguments(parser) File "/root/centrix/lib/python3.8/site-packages/tenant_schemas/management/commands/migrate_schemas.py", line 20, in add_arguments command.add_arguments(parser) File "/root/centrix/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 26, in add_arguments parser.add_argument( File "/usr/lib/python3.8/argparse.py", line 1398, in add_argument return self._add_action(action) File "/usr/lib/python3.8/argparse.py", line 1761, in _add_action self._optionals._add_action(action) File "/usr/lib/python3.8/argparse.py", line 1602, in _add_action action = super(_ArgumentGroup, self)._add_action(action) File "/usr/lib/python3.8/argparse.py", line 1412, in _add_action self._check_conflict(action) File "/usr/lib/python3.8/argparse.py", line 1551, in _check_conflict conflict_handler(action, confl_optionals) File "/usr/lib/python3.8/argparse.py", line 1560, in _handle_conflict_error raise ArgumentError(action, message % conflict_string) argparse.ArgumentError: argument --skip-checks: conflicting option st ring: --skip-checks Source : https://django-tenant-schemas.readthedocs.io/en/latest/install.html -
Send an email through Django in an if statement
I have an html template that looks like this: <table> {% for instance in queryset %} <tr> <td> {% if instance.quantity <= instance.reorder_level %} <div style="background-color: red;"> <a href="{% url 'item_detail' instance.id %}">{{instance.quantity}}</a></div> {% else %} <a href="{% url 'item_detail' instance.id %}">{{instance.quantity}}</a> {% endif %} </td> {% endfor %} </table> Basically an inventory system app. I want to send an email to a user when the item reorder level is at or below a certain amount. Right now I have it to just highlight red. I know I have to create a view to send an email, but how do I get a function to trigger in the: {% if instance.quantity <= instance.reorder_level %} **send_email right here** {% else %} `**don't send email**` {% endif %} if statement? I am new to django and I have seen a lot of tutorials to send emails by form submit but not in this way. Thank you for any help! -
How to populate select option dropdown with database info in django
I have a django project with a select dropdown. I have typed in the names of players that users can select, but i want to populate the dropdown with the same names but dynamically from the database. How can i go about this? This is my html so far, not sure how to write the views.py for this, or if i should do a for loop or and if. <form method="POST"> {% csrf_token %} <select id="playerselect" name="pitcher" class="player-dropdown"> <option value="{{ pitching.id}}">{{ pitching.player_name }}</option> <option value="2">Yadiel Lugo</option> <option value="3">Cody Reeds</option> <option value="4" >Xavier Colon</option> <option value="5" >Andy Smith</option> <option value="6" >Carson Rex</option> <option value="7" >Jalen Jackson</option> <option value="8" >Matthew Cobbs</option> <option value="9" >Matt Sampson</option> <option value="10" >John Harrison</option> <option value="11" >Robert Santiago</option> <option value="12" >Efrain Zuniga</option> <input type="submit" value="Search"/> </select> -
Is there way to confirm user email when user change his email inside his profile - django
I have an option that allows a user to change email in his profile but without confirming a new email so when he enters a new email I want activate the email to save it in his profile, how to add confirm I am using UserCreationForm is there 3rd party app i can use it ? (my django version is 2.2) models.py : from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() my code | forms.py : # Profile Form class EmailChangeForm(forms.ModelForm): email = forms.EmailField(required=True,label='Email',widget=forms.EmailInput(attrs={'class': 'form-control center container','style': 'width:85%;text-align: center;background-color:#f6f6f6','placeholder':' Enter Your New E-mail '}) ) class Meta: model = User fields = [ 'email', ] def clean_email(self): email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).count(): raise forms.ValidationError('Email is already in use, please check the email or use another email') return email views.py : # Edit Profile View class EmailChange(UpdateView): model = User form_class = EmailChangeForm success_url = reverse_lazy('home') template_name = 'user/commons/EmailChange.html' def get_object(self, queryset=None): return self.request.user urls.py : from django.urls import path from blog_app.views import SignUpView, ProfileView, ActivateAccount,EmailChange urlpatterns = [ path('profile/change-email/me/', EmailChange.as_view(), … -
SSL for Django project on bitnami
I have an Django project deployed on ubuntu AWS instance with Bitnami and configured with Lightsail, Route53. The project is working for HTTP. I've tried to migrate to HTTPs using the bncert-tool and got DNS with HTTPS, although I see: "You are now running Bitnami Django 3.1.6 in the Cloud" instead of my project. HTTP://<static_ip> is showing my project. ps: I didn't enable: sample-vhost.conf and sample-https-vhost.conf, as if I do that I see "You don't have permission". Is there additional steps that should be executed after bncert-tool? -
Django queryset for Case object and When Object, ---
I would to get your help on the following : I have two models Parent model and a Child Model: class Rate(models.Model): RATE_VOLTAGE_CHOICES = ( (BAJA_TENSION, "Low tension"), (MEDIA_TENSION, "Mid tension"), (ALTA_TENSION, "High tension") ) rate_type = models.CharField(max_length=1, choices=RATE_TYPE_CHOICES, default="0") class ParentRate(models.Model): rate = models.ForeignKey(Rate, on_delete=models.SET_NULL, blank=True, null=True ) so front-end wants to "filter" rate_type choice by Low tension, Mid Tension, and High tension as strings, they send strings so I am trying to use When Case object so I can filter then: rates = ParentRate.objects.annotate(rate_voltage=Case( When(rate__rate_type=Rate.BAJA_TENSION, then=Value('Low tension')), When(rate__rate_type=Rate.MEDIA_TENSION, then=Value('Mid tension')), When(rate__rate_type=Rate.ALTA_TENSION, then=Value('High tension')), default=Value('Low tension'), ) ) but I am getting the following error: django.core.exceptions.FieldError: Cannot resolve expression type, unknown output_field -
My code is still throwing out httperror 403 forbidden i tried connecting to nasa api, i even tried using csfr_exempt
from django.shortcuts import render from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt import requests import json import os import urllib.request from django.http import HttpResponse from django.conf import settings from .models import Destination @csrf_exempt @login_required def apod(request): url = 'https://api.nasa.gov/planetary/apod?api_key=4ZafMxbFfczTLG5ScI4Iej3zrfkHeOOEYz21cc8h' os.environ['NO PROXY'] = 'api.nasa.gov/planetary' apod_url = urllib.request.urlopen(url) apod_read = apod_url.read() decode_apod = json.loads(apod_read.decode('utf-8')) return HttpResponse(decode_apod) -
How do I prevent Django from applying a migration
I am on a team working on a project using Django. Besides my local dev server, we also have the Test environment and Live environment. In the process of undoing changes and reverting PR, the test and Live environment databases are out of sync, but the codes are the same. In our workflow, we merge the feature branch into the test branch, then test branch into master(Live branch) The local dev server and the test DB have a table column that I need to remove. This column is not in the Live environment db. I make the appropriate change to the model class, generate and apply the migrations and push to test branch. The migration is applied in the test environment. My Challenge When test is merged to master, Django attempts to apply the migration to remove the column but fails to find the column. Hence, error is thrown. Is there a way to mark this migration so that on Live DB, Django does not apply it? Note: I do not have access to the Live Db, otherwise I would have manually added the column to be remove by the migration. Thanks. -
Can't get ModelForm ChoiceField return as string - Cannot assign "'5'": "Reclamacoes.uf" must be a "Estados" instance
This form gets entries from models Estados, Cidades, Categorias and Status from the database, to be displayed in ChoiceFields. The other fields are CharFields, EmailFields and a PhoneNumberField (from this lib). After pressing the submit button with proper data, I get the following error: "Cannot assign "'5'": "Reclamacoes.uf" must be a "Estados" instance." Tried several different widgets and form elements to try and get this input as string (including forms.Select), but they don't fulfill the purpose I'm looking for. models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField class Estados(models.Model): nome = models.CharField(("nome"), max_length=50) unidade = models.CharField(("unidade"), max_length=2) disponibilidade = models.BooleanField(("disponibilidade"), default=False) class Cidades(models.Model): nome = models.CharField(("nome"), max_length=50) uf = models.ForeignKey("Estados", on_delete=models.CASCADE) disponibilidade = models.BooleanField(("disponibilidade"), default=False) class Categorias(models.Model): tipo = models.CharField(("tipo"), max_length=50) disponibilidade = models.BooleanField(("disponibilidade"), default=False) nome = models.CharField(("nome"), max_length=50) class Status(models.Model): status = models.CharField(("status"), max_length=50) class Reclamacoes(models.Model): uf = models.ForeignKey("Estados", on_delete=models.CASCADE) cidade = models.ForeignKey("Cidades", on_delete=models.CASCADE) categoria = models.ForeignKey("Categorias", on_delete=models.CASCADE) autor = models.CharField(("autor"), max_length=50) email = models.EmailField(("email"), max_length=254) telefone = PhoneNumberField(null=False, blank=False, unique=False) reclamacao = models.CharField(("reclamacao"), max_length=50000) status = models.ForeignKey("Status", on_delete=models.CASCADE) forms.py from django import forms from django.db.models import fields from phonenumber_field.formfields import PhoneNumberField from .models import Estados, Cidades, Categorias, Status, Reclamacoes from django.core.exceptions import ValidationError class FormReclamacao(forms.ModelForm): uf = … -
Trying to add OCR to a PDF, then upload to AWS using Django
I'm developing a web app so I can OCR files while at work but not have Adobe tied up the whole time it's running the OCR. My goal is to allow a user to upload a non-OCR'd PDF, have it be OCR'd via the ocrmypdf tool, then have the resulting OCR'd file sent to an S3 bucket where it's downloadable by the user. I've verified that I can save a regular PDF to S3, but I'm getting hung up on how to actually save the OCR'd version to S3. Here is the view I currently have for doing the OCR'ing: class CreatePost(generics.CreateAPIView): permission_classes = [IsAuthenticated] parser_classes = [MultiPartParser, FormParser] def post(self, request, *args, **kwargs): posts_serializer = FileSerializer(data=request.data) if posts_serializer.is_valid(): uploaded = posts_serializer.save() ocr_pdf = subprocess.call(['ocrmypdf', uploaded.file.path, 'output.pdf']) return Response(ocr_pdf, status=status.HTTP_201_CREATED) else: print('error', posts_serializer.errors) return Response(posts_serializer.errors, status=status.HTTP_400_BAD_REQUEST) return uploaded I'd really appreciate any help with this. Thanks! -
Django Email Confirmation: Opening the email alone will fire user update, they don't even have to click the link
I have email confirmation set up so that when a user registers, they will have is_active set to true but my custom email_confirmed field will be false. For that to be updated to true, they must click on an email sent to them upon registration. This is what the email looks like: The weird thing is that as soon as I open this email, without even hovering or clicking the link, I can see in the Heroku logs that the activate() function in views.py (shown below) is firing! I don't even have to click the link. This is causing issues, is there any way I can block the function from firing just from someone opening an email? Preferably I would like a plaintext option, as not all email providers correctly present html emails. views.py function called upon click of the link in email: #View called from activation email. Activate user if link didn't expire (1 week). Offer to resend link if the first expired def activation(request, key): # key is the pk accepted in the url from clicking the link in the email. User may/may not be logged in... Actually maybe i will require login print('~~~in activation()~~~') user = User.objects.filter(activation_key=key).first() … -
how should I configure mailman on ubuntu 20.04
I'm having an ubuntu 20.04 and I want to send an email to a list email and all the members under the list receive the email. on my server there is a django-based website running using apache2 webserver. How should I install the mailman and config it to perform the task? -
Receive only one row, if multiple rows with same credentials exist in Django - SQLite
I am looking for an elegant way to do a query in Django on a SQLite and only get one result, if there is multiple rows with the same content. My example: I have multiple time slots, which I model like this: class Slots(models.Model): year = models.IntegerField(_("Year"), blank=False) month = models.IntegerField(_("Month"), blank=False) day = models.IntegerField(_("Day"), blank=False) hour = models.IntegerField(_("Hour"), blank=False) block = models.IntegerField(_("Block"), blank=False) date = models.DateTimeField(_("DateTimeField"), blank=False) Lets assume I have two entries with: year = 2021 month = 4 day = 22 hour = 15 block = 0 date = DateTimeField(2012/04/22,15:00:00) When I do a: Slots.objects.filter(year=2021, month=4, day=22, hour=15, block=0) I get two entries, but I only want one, as long as the condition is matched. -
How do I check if user exists in db given an email and a number and then create it or update it?
I wrote this code that does not work since it has some syntax errors among other things but I think the functionality I'm looking for can be seen in it. I basically need to check if given an email or a phone, the user exists and, if it does, return it. Then, if the user inputs both their email and phone, I need to get the user if it exists, update it if one of the fields is different, create it if it doesn't exist and, if there're two users (one with the same phone, another one with the same email) return none. How can I improve this so that it actually works? def create(self, validated_data): filters = {} if email = validated_data.get('email') or telefono = validated_data.get('telefono'): filters["email"] = email filters["telefono"] = telefono try: go = Cliente.objects.get(foo='bar') except Cliente.DoesNotExist: go = None elif email := validated_data.get('email') and telefono := validated_data.get('telefono'): filters["email"] = email filters["telefono"] = telefono try: go = Cliente.objects.get(foo='bar') except Cliente.DoesNotExist: cliente, _ = Cliente.objects.update_or_create(**filters) return user except Cliente.MultipleObjectsReturned: go = None This is the models: class Food(models.Model): nombre = models.CharField(max_length=100, unique=True) cant = models.IntegerField(default=0) def __str__(self): return self.nombre class Order(models.Model): fecha = models.DateField(auto_now_add=True) email = models.EmailField(max_length=200, null=True) telefono … -
Inserting javscript function parameters into django template syntax
I've got a setup where I basically have a button that passes an ID to a javascript function, like so: <script> function posted(key){ console.log("test is", `{{ appointments.appointments.106 }}'`) } </script> the appointments dictionary is in the front end, and something like this works fine. So, I wanted to use the key input here, and do something like this: <script> function posted(key){ console.log("test is", `{{ appointments.appointments.${key} }}'`) } </script> but for the life of me I cannot get this to work. Doing it like this throws a syntax error, so I've tried escaping the brackets, even tried concatenation, etc. and nothing works -- seems like Django refuses to dynamically inject variables like this. Is there any workaround here? Thanks. -
Adding image background using django-imagekit
I'm using django imagekit for generating thumbnails of transparent images(png) to jpeg using ImageSpecField. How can i use a image to make the background of jpeg thumbnails. Here is my code : class Image(Base): def get_image_path(instance, filename): ext = filename.split('.')[-1] filename = "%s.%s" % (uuid.uuid4(), ext) return os.path.join('images', str(instance.subcategory.category.category_slug), str(instance.subcategory.sub_slug), filename) image = models.ImageField(upload_to=get_image_path, null=True) image_thumbnail = ImageSpecField(source='image', processors=[ResizeToFit(480,480)], format='JPEG', options={'quality':60}) image_preview = ImageSpecField(source='image', processors=[ResizeToFit(800,800)], format='JPEG', options={'quality':60}) -
how can I redirect to a dynamic url using HTML?
My code is {% if user.employee.employee_id == 2 %} <head> <title>HTML Redirect</title> <meta http-equiv="refresh" content="1; url = employee/2/" /> </head> {% elif user.employee.employee_id == 4 %} <head> Wait! <title>HTML Redirect</title> <meta http-equiv="refresh" content="1; url = employee/4/" /> </head> As you can see from above, i am using if elif to access pages based on the id of employee and this method is not efficient. I want to change the employee_id to variable. something like this: x = user.employee.empolyee_id <head> Wait! <title>HTML Redirect</title> <meta http-equiv="refresh" content="1; url = employee/x/" /> </head> -
I can't load my method in the browser when i add the id number /id
I'm working on a small project using Django / Rest Framework. I try to access my show method in the browser but it doesn't work like that /contacts/show/15/ This is my class class ContactView(viewsets.GenericViewSet): @action(methods=['GET'], detail=True) def show(self, request, pk): return Response("i would like to get the id from the url") This is my urls from django.urls import path from contact.api.views import ContactView from rest_framework import routers router = routers.DefaultRouter() router.register(r'contacts', ContactView, basename="contact") urlpatterns = router.urls how can i access to the id (15) in my function -
Django Channels | Can you do a SQL Query in a Channels Consumer?
i am making a Tool which can show me the Temperature of an Connected thermostat via GPIO. I want to log the temperature by sending the current temperature via an SQL Query to the Django SQLITE DB using Models. It also logs the current time when the temperature was recorded so i maybe later can do graphs or stuff like that. When i do it nothing happens. I dont get an exception in the Webserver Shell or on the webpage itself. The SQL Query im sending simply dosent work. Note that the temperature fuction works i tried it out by only showing the current temperature on the website. Models.py from django.db import models class TempLog(models.Model): temp = models.CharField(max_length=10) time = models.DateTimeField(auto_now_add=True, auto_now=False, blank=False) consumers.py Im using the fuction temp_db to create the SQL Query. The Temperature Data is being saved in the Variable ctemp. And then the function is called in the loop within the consumer. import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from .tempclient import getTempTCP from tcore.models import TempLog async def temp_db(tcptemp): tempdb = TempLog() TempLog.objects.create(temp=tcptemp) class TempConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) await self.send({ "type" : "websocket.accept" }) i = 0 … -
how to prevent my users from going backward?
I am making an online test application in Django.The flow of the control is: test-> display marks-> Profile. all these three components are working perfectly but the problem is that users after giving the test can press the back button of the browser and go back to the test and change their responses. How can I prevent users from going back to the test? note: I cannot make any custom session token because there are multiple tests so if I make a session token the user will not be able to give any other test. -
Django Multiselectfield works locally but not on server
I've installed multiselectfield on my machine and it works well. I can choose multiple items thanks to multiple checkboxes in admin: Then I had to copy/paste all the files of the project to my VPS using Filezilla. So I have the exact same code and the exact same files locally and remotely. The site works well remotely (the VPS django admin page too). However on the server's django admin page, the multiselectfield widget shows a simple text field instead of an actual list of checkboxes, plus it says Enter a list of values. when I try to validate the form. So, how is it, that with the same code at two different places, the multiselectfield acts differently and how to I fix this ? -
Trying to Run 2 Celery Daemons and Queues with Django and Redis and Apache wsgi
I have two Django 3.0 sites (test and production) running under apache2 2.4.9, mod_wsgi, redis 4.0.9 and celery 4.3.0 as a daemon, and flower 0.9.7 on the same server. The django code base for each site is identical, just different databases. Each site runs in its own virtual environment, but using identical requirements.txt files and python version. Each site has its own wsgi.py file, celery.py file, apache.conf file, /etc/conf.d/celery settings file, /etc/systemd/system/celery.service file, and settings.py file with different settings for the celery daemons. There is only one redis server running, and both daemons talk to that server. If I run each site alone (stop the other site's celery daemon), then the celery tasks all work as expected. If I enable both daemons, then the celery tasks fail with very strange error messages - e.g. in the celery task log file I get "matching query does not exist" for the same code which works when each daemon runs separately, and the same code on my dev machine. I thought the solution would be to make two separate celery queues for each site, which is not working. In the settings.py for each for the 'test' environment I have CELERY_TEST_BROKER_URL = 'redis://:' + …