Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Update Class form (delete form imput title)
I have : class CompanyUpdateView(LoginRequiredMixin, UpdateView): model = UserCompany template_name = 'panel/admin/company.html' fields = [ "name", "phone_number", "address", "city", "region", "legal_document", ] success_url ="/panel" and HTML: <div class="col-6"> {{ form.name|as_crispy_field }} </div> and return : enter image description here How i change the input title "name" -
Django multidb with router not inserting during test
I have a multiple databases application and a DB router, but somehow insert is not working during test. here is my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # HOST, PORT, NAME, USER, PASSWORD 'TEST': { 'NAME': 'test__db', 'CHARSET': 'utf8', 'COLLATION': 'utf8_general_ci', } }, 'default_replica': { 'ENGINE': 'django.db.backends.mysql', # HOST, PORT, NAME, USER, PASSWORD 'TEST': { 'NAME': 'test__db_replica', 'CHARSET': 'utf8', 'COLLATION': 'utf8_general_ci', } }, 'reporting': { 'ENGINE': 'django.db.backends.mysql', # HOST, PORT, NAME, USER, PASSWORD 'TEST': { 'NAME': 'test__reporting', 'CHARSET': 'utf8', 'COLLATION': 'utf8_general_ci', } }, 'reporting_replica': { 'ENGINE': 'django.db.backends.mysql', # HOST, PORT, NAME, USER, PASSWORD 'TEST': { 'NAME': 'test__reporting_replica', 'CHARSET': 'utf8', 'COLLATION': 'utf8_general_ci', } }, } my router.py: class Router: def db_for_read(self, model, **hints): if model._meta.label_lower in settings.DB_REPORTING_MODELS: return 'reporting_replica' if model._meta.label_lower in settings.DB_FORCE_READ_MODELS: return 'default_replica' return 'default' def db_for_write(self, model, **hints): if model._meta.label_lower in settings.DB_REPORTING_MODELS: return 'reporting' return 'default' def allow_relation(self, obj1, obj2, **hints): return None def allow_migrate(self, db, app_label, model_name=None, **hints): if model_name is None: return None model_id = f'{app_label}.{model_name}' if db == 'reporting' and model_id in settings.DB_REPORTING_MODELS: return True elif db == 'default': return True return None my test function: def insert(): a = ModelName.objects.create(value='test') return a and my test: def test_insert(self): assert not ModelName.objects.exists() a = … -
AWS Cognito in react js with django rest framework?
I want to integrate third party authentication with AWS Cognito in my webapp. I have a React JS app with a django backend. I found this tutorial but I dont really get how this will work with an existing frontend application rather than how to implement it. if a user logs into the frontend and is authenticated via cognito (other question: is a backend in Amplify necessary?), can the token be passed to the django API - does cognito then need to be called again in django? this step is not yet completely clear to me. Any help is appreciated. Are there no examples for react + DRF? -
Loading aws s3 lamda generated files in Django
Whats working I have a Django website application form that takes an image from a user and uses django-storages to save the uploaded images to a AWS S3 bucket: <bucket>/private/images/file_name.jpg On upload, I have an AWS SNS triggered that executes a Lambda function to filter the users image and store it in the same S3 bucket <bucket>/private/filtered_images/file_name.jpg; the SNS is only triggered on the images folder in order to avoid recursive Lambda evaluations. Whats the problem I want a good way to reference the Lambda generated filtered images in my Django application. Currently, my django image model is: class Image(models.Model): title = models.CharField(max_length=200) image_owner = models.ForeignKey(image_owner, on_delete=models.CASCADE, null=True) # image owner has multiple images source_image = models.ImageField(storage=PrivateMediaStorage(), upload_to="images/", null=True, blank=True) def get_absolute_url(self): return reverse('image-detail', args=[str(self.id)]) def get_update_url(self): return reverse('image-update', args=[str(self.id)]) def get_delete_url(self): return reverse('image-delete', args=[str(self.id)]) where class PrivateMediaStorage(S3Boto3Storage): location = settings.AWS_PRIVATE_MEDIA_LOCATION default_acl = 'private' file_overwrite = False custom_domain = False It would be ideal if I could somehow add a filtered_image field to the Image model upon the creation of Image, even though the processing for the filtered_image would only start when source_image is uploaded (due to the nature of the s3 -> lambda trigger I have set). Is this … -
Only able to add two child objects in Django using a ModelForm and inline_formsets
I'm making a recipe application in Django. Each user has their own OneToOne RecipeBook object, which in turn can hold as many recipes as needed, as each Recipe has a ForeignKey relationship to the RecipeBook object. There are also Ingredient and Direction objects that each have a FK relationship to the Recipe object. I am trying to make a form that allows the user to create a Recipe, and then dynamically add/remove Ingredient/Direction objects as needed. I'm using Class Based Views, ModelForms, and inlineformsets_factory to accomplish this, as well as using the django-dynamic-formset jQuery plugin, and I've been following this guide. My issue is that I am only able to create two child Ingredient/Direction objects for each recipe. I want to make it so users can create as many Ingredient/Direction objects as they like. Previously I was only able to add one instance of each child object, but through some changes I don't recall, I am now able to add two. I previously thought that I would need to iterate over each object in my view to allow multiple objects, but since I can now create two I'm not sure if that is the case. So my question is, what … -
In django, what is the optimal way to access data in a OnetoMany relationship to output to template?
I'm working in django and my objective is to output to a template a table consisting of all my customers and a corresponding amount equal to the total amount they have spent. I have the classes/models Customers and Transactions with a OneToMany relationship. Every time a customer makes a purchase, the transaction is recorded as is the amount they spent (tx_amount). I have the following set a code that works but I believe is not optimal since its running in O(x * y) time, i.e., running a full loop over Transactions for every customer. Q1: What is the optimal way for accomplishing this task? When I originally tried to get my template to work, instead of using local_customer, I was using setattr(customer[x],"value",tx_amount) which worked in the django shell but did not work in the template. My workaround was to create a local class which I would use to population my context variable. Q2: When combining data models to output in a template, is it necessary to use some sort of local class like my local_customer implementation below or is there a better way? Pseudo-code below: models.py: class Customers(models.Model): name = models.CharField(max_length=70) def __str__(self): return self.name class Transactions(models.Model): customers = models.ForeignKey(Customers, … -
How do i specify a variable in side of django template file
So I am trying to declare a variable inside of my django templates file {% with object = "2" %} {% for detail in details %} {% if detail.post.id == {{object}} %} {{detail.name}} {% endif %} {% endfor %} {% endwith %} I know that with is used to this job, but when i run this code it shows me this error: 'with' expected at least one variable assignment Please help me. Thank You -
I can't seem to get a Docker-Nginx-Django app to refresh the static files
I currently have a Django website that runs on a server using Nginx an Docker. Every time I update my main css file and deploy it, nothing changes, despite hard refreshing the site. When new static files are added, they end up working, but modified files don't seem to change. This led me to believing that nginx or Docker was caching the file. I've tried the following: Clearing the cache in the nginx container, setting the lines expires -1 and sendfile off, rebuilding the containers, with no luck. The last time I had this problem, I believe I had to delete the volume for it to refresh, which I don't think is a good solution. Can someone explain what I am doing wrong? Settings: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] nginx configuration: upstream my_server { server web:80; } server { listen 80; server_name mywebsite.com; location / { proxy_pass http://my_server; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $Host; proxy_redirect off; return 301 https://$host$request_uri; } location /.well-known/acme-challenge/ { root /var/www/certbot; } location /static/ { alias /code/staticfiles/; expires -1; } } server { listen 443 ssl; server_name mywebsite.com; ssl_certificate /etc/letsencrypt/live/mywebsite.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mywebsite.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; … -
Django download csv from model database
I don't know why this is so difficult but I want to download a csv file that has already been saved to my database for users to look at on their own PCs. Here are my models and views: models.py class datasheet(models.Model): file_name = models.FileField(upload_to = 'upload', max_length = 100) def __str__(self): return 'File id: {}'.format(self.id) views.py def download(request): csvfile = datasheet.objects.get(id = 1) return (csvfile as a downloaded attachment) Any ideas? -
Django Admin action different names then function names
Is possible to have action display in Django Admin with a different name than its function name? for example: def an_action(): pass class AdminPanel(admin.ModelAdmin): actions = [ an_action] In the Django admin panel an_action would display as "An action". Could I made this display something arbitrary like "Best Action Ever" instead of "An Action"? -
Django Rest Framework: changing output format of annotated field in queryset
Hello StackOverflow community, I am currently struggling with specifying an output format in my views.py. I have a column "date" which is using following format: 2021-01-14. In my response, I would like to change the date format so that it only shows the year 2021. I already tried it with Cast but it seems like this is not the right approach. For this view, I do not use a Serializer, hence adding it there would not be an option. views.py class FilterParams(generics.ListAPIView): model = Variants queryset = Variants.objects.all() def get(self, request, *args, **kwargs): queryset = self.get_queryset() ModelsByYears = queryset.values('model').distinct().annotate(min_year=Min('date')).annotate(max_year=Max('date')).order_by('model') return Response(data= {'ModelsByYears':ModelsByYears}) What I tried: class FilterParams(generics.ListAPIView): model = Variants queryset = Variants.objects.all() def get(self, request, *args, **kwargs): queryset = self.get_queryset() ModelsByYears = queryset.values('model').distinct().annotate(min_year=Min(Cast('date', DateTimeField(format="%Y")))).annotate(max_year=Max('date')).order_by('model') return Response(data= {'ModelsByYears':ModelsByYears}) Error message TypeError: __init__() got an unexpected keyword argument 'format' -
Calling a django function from html button
I am new to django. What i am trying to do is to run a django function from my "main.py" file when a html button is pressed. what I've done is created a button in html: <input type="button" value="Formatting excel" onclick="excel_formatting"> And then in my "main.py " I have: def excel_formatting(): print("hello world") return() The website loads fine, but when i press the button nothing is printed in the terminal. i must be doing something wrong. -
Django refuses to parse javascript variable when creating qr code
I have been trying different ways to try to make django read the javascript variable but nothing has been working. Either it prints the variable as a string or gives me an error. I am trying to create a qr-code, I need to enter the qr-code information which is stored in a js variable. <script type="text/javascript"> const id = document.getElementById('id-input-product'); function loadPreviewProduct() { value = '"' + id.value + '"'; document.getElementById('qr-code').innerHTML = `{% qr_from_text ${value} size="t" image_format="png" error_correction="L" %}`; } </script> <div id="qr-code"> </div> -
Bootstrap toast - Data delay not respectés - Toast dont hide
After hit the submit button of a form (Ajax POST) I want to refresh the toast with the message generated in Django view. I succeed to show the message but the data-delay is not respected, the toast does not disappear after 5 sec. <div id="messages" aria-live="polite" aria-atomic="true" style="position: relative"> <div style="position: absolute; top: 12px; right: 12px;" > {% for message in messages %} <div class="toast d-flex toast-success" role="alert" aria-live="assertive" aria-atomic="true" data-delay="3000"> <div class="toast-header toast-success shadow-none" > <i class="fas fa-check"></i> </div> <div class="toast-body"> {{message}} </div> </div> {% endfor %} </div> </div> And in success part of Ajax I add $('#messages).load(location.href + " #messages>*", "") -
Django get plain value of Foreign Key
I have the following model: def MyModel(models.Model): other = models.ForeignKey(OtherModel, db_column='other', on_delete=models.DO_NOTHING, db_constraint=False, blank=True, null=True) The problem is that maybe a value in other field (which is a string value) of the model MyModel could not be in OtherModel so when I do, for example: inst = MyModel.objects.first() # Gets any (with an "invalid" key in other) inst.other It threw: others.models.OtherModel.DoesNotExist: OtherModel matching query does not exist. I'd like that, in case that it doesn't exists, get the plain value of the other field. How could I achieve that? Any kind of help would be really appreciated -
'ManyToManyField' object has no attribute '_m2m_reverse_name_cache' error in ManyToMany field with 'self'
This is related to this question, I thought it makes sense if I open a separate question for this specific issue. I'd like to link to each other more instances of the same model: class MsTune(models.Model): concordances = models.ManyToManyField('MsTune', through='Concordance', blank=True) [...] class Concordance(models.Model): tune = models.ManyToManyField(MsTune) title = models.CharField(max_length=64) def __str__(self): return self.title What I want is to link together many similar tunes, and get the list of the other-similar tunes for each tune. E.g: tune_1: concordances.all: tune_1a, tune_1b tune_1a: concordances.all: tune_1, tune_1b tune_1b: concordances.all: tune_1, tune_1a Now, when I access concordances.all from my template I get a 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache' error. Accessing concordance_set, on the other hand, gives me only the id/name of the concordance instance (the through model), and I'm not able to get information about the single tunes with, for example, {% for concordance in tune.concordance_set.all %} {{ concordance.tune }}{% endfor %}. That is 'None', or empty. What am I overlooking? -
git working/production branch for django project
What is the right workflow for a "working" and "production" branch in github (concerning a django project)? To be specific: I have obviously settings.py and wsgi.py file in production that are different from the ones in working which I use locally. So I considered adding these files to .gitignore, but thats obviously not going to work when two+ people work on it. And pushing "working" to "production" every now and then will overwrite these files there. And just cheking out "production" on the server will either give a warning message or overwrite settings... Surely others have a solution, but its not obvious to me... Can anyone help? (I am very new to git, I have to google every command... more or less...) -
django rest framework not outputting custom responses
whenever I post a valid request to create view I get { "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" } instead of the custom responses I setup class ServerView(generics.CreateAPIView): queryset = Server.objects.all() serializer_class = ServerSerializer class CreateView(APIView): serializers_class = CreateSerializers def post(self, request, format=None): serializer = self.serializers_class(data=request.data) if serializer.is_valid(): name = serializer.data.get(name) queryset = Server.objects.filter(name=name) if not queryset.exists(): server = Server(name=name) server.save() return Response(ServerSerializer(server).data, status=status.HTTP_201_CREATED) return Response({'Bad Request': 'Join or try another name'}, status=status.HTTP_226_IM_USED) return Response({'Bad Request': 'Name is not valid'}, status=status.HTTP_400_BAD_REQUEST)``` -
Testing a CreateView with TestCase in Django
I'm new to unit testing in Django and I'm trying to test my CreateView which creates a new blog post when is submited, my first assertEquals which checks if the response code is 302 which practically means that the form was submited correctly because it was redirected is ok but the second check it gives me this error: " Traceback (most recent call last): File "/Users/aryanlilian/Desktop/EcoMon/blog/tests/test_views.py", line 53, in test_post_create_view_POST self.assertEquals(post.title, 'test post') AssertionError: 'Test post' != 'test post' Test post ? ^ test post ? ^ " my TestCase from django.test import TestCase, Client from django.urls import reverse from blog.models import Post, Comment from users.models import User class TestViews(TestCase): def setUp(self): self.client = Client() self.blog_url = reverse('blog') self.tag_url = reverse('tag', args=['test']) self.post_url = reverse('post', args=['test-post']) self.add_post_url = reverse('add-post') self.user = User.objects.create( username='testuser', email='test@test.com', first_name='test', last_name='test', password='test' ) self.post = Post.objects.create( author=self.user, title='Test post', content='test content post', ) self.post.tags.add('test') def test_blog_list_view_GET(self): response = self.client.get(self.blog_url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'blog/blog.html') def test_tagged_post_list_view_GET(self): response = self.client.get(self.tag_url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'blog/blog.html') def test_post_detail_view(self): response = self.client.get(self.post_url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'blog/post.html') def test_post_create_view_POST(self): response = self.client.post(self.add_post_url, { 'title': 'test post', 'content' : 'test content', 'category' : 'BUSSINESS', 'tags' : 'test' }) post = Post.objects.last() self.assertEquals(response.status_code, … -
Django Rest - Authorization Data Filtering
When i login, i only want see data that is connected to my own account. With every model there is an id. But i can't figure out how to do that. I have these models. This is for a new project i am working on. It is for a SAAS software. class ServicesModel(models.Model): id = models.UUIDField( primary_key=True, auto_created=True, unique=True, default=uuid4, editable=False) saloon_id = models.CharField(max_length=25) service_name = models.CharField(max_length=30) service_price = models.IntegerField() service_price_readable = models.CharField() service_explanation = models.CharField(max_length=150) service_length = models.IntegerField() service_length_readable = models.CharField() created_at = models.DateField(auto_now_add=True, auto_created=True) updated_at = models.DateTimeField(auto_now=True) class SaloonsModel(models.model): id = models.UUIDField( primary_key=True, auto_created=True, unique=True, default=uuid4, editable=False) subscription = models.IntegerField(null=False) subscription_active = models.BooleanField(null=False) transactions = ArrayField(models.OneToOneField()) payment_method = models.CharField(max_length=25) last_payment = models.DateField(null=True) saloon_name = models.CharField(max_length=50) saloon_password = models.CharField(max_length=100) saloon_phonenumber = models.CharField(max_length=15) saloon_email = models.CharField(max_length=75) saloon_bio = models.TextField(max_length=350) saloon_employees = models.OneToOneField(EmployeesModel) available_times = ArrayField(models.DateTimeField(null=True)) services = models.OneToOneField(ServicesModel) created_at = models.DateField(auto_now_add=True, auto_created=True) updated_at = models.DateTimeField(auto_now=True) class LoginSessionsModel(models.Model): id = models.UUIDField( primary_key=True, auto_created=True, unique=True, default=uuid4, editable=False) ip_adress = models.CharField(max_length=15, null=False) saloon_id = models.OneToOneField(SaloonsModel) created_at = models.DateTimeField(auto_now_add=True, null=False) -
Requesting a specific view in Django multitenant API
Created a multitenant API in Django 2.2.17 using django-tenant-schemas==1.10.0 and currently testing it using Postman. I'm able to create a new organization (which is the Tenant) and GET them all Thing is, in the GET and POST requests to the endpoint http://127.0.0.1:8000/employee/ I'm getting AttributeError at /employee/ 'str' object has no attribute 'get' Here's my employee/views.py from django.shortcuts import render from employee.models import Employee from organization.models import Organization from django.http import JsonResponse,request, HttpResponse from django.views import View from tenant_schemas.utils import schema_context import json # Create your views here. class EmployeeView(View): def get(self, request, *args, **kwargs): try: organizations = Organization.objects.get(domain_url=request.META['HTTP_HOST']) schema_name = organizations["schema_name"] #schema_name = organizations.schema_name except Organization.DoesNotExist: return "no organization" with schema_context(schema_name): employees = Employee.objects.all() data = {"results": list(employees.values("id","name"))} return JsonResponse(data) def post(self, request, *args, **kwargs): try: organizations = Organization.objects.get(domain_url=request.META['HTTP_HOST']) schema_name = organizations.schema_name except Organization.DoesNotExist: return "no organization" with schema_context(schema_name): name = json.loads(request.body)['name'] employee = Employee(name=name) employee.save() return "Employee added successfully" -
Matplotlib Live Animation in Django
I am trying to display a live graph constructed with matplotlib's animation feature in Django, however I am stuck and do not know how to approach this. I have successfully generated the animation using matplotlibs FuncAnimation. Therefore, I have an matplotlib object called "animation" that updates with live data. Now my question is, how to I dynamically show this animation object in my web page using Django. I am really struggling with this. If someone has advice, it would be greatly appreciated. -
CSS Not loading in Django-Oscar production but in development
:8000 CSS loading in development but NOT in production -
Password fields attribute not rendering correctly registration page Django
I'm creating a registration page in Django and everything works fine, and gets rendered correctly except the password fields. Why can that due to? I've tried building a form without the inbuild Django methods but it doesn't work either. It is very weird as I think all the code is working fine and everything is build correctly. Here is the html: <body class="bg-gradient-primary"> <div class="container"> <div class="card o-hidden border-0 shadow-lg my-5"> <div class="card-body p-0"> <!-- Nested Row within Card Body --> <div class="row"> <div class="col-lg-5 d-none d-lg-block bg-register-image"></div> <div class="col-lg-7"> <div class="p-5"> <div class="text-center"> <h1 class="h4 text-gray-900 mb-4">Create an Account!</h1> </div> <form class="user" method="POST"> {% csrf_token %} <div class="form-group row"> <div class="col-sm-6 mb-3 mb-sm-0"> {{ form.first_name }} </div> <div class="col-sm-6"> {{ form.last_name }} </div> </div> <div class="form-group"> {{ form.email }} </div> <div class="form-group row"> <div class="col-sm-6 mb-3 mb-sm-0"> {{ form.password1 }} </div> <div class="col-sm-6"> {{ form.password2 }} </div> </div> <button type="submit" class="btn btn-primary btn-user btn-block"> Register Account </button> <hr> <a href="index.html" class="btn btn-google btn-user btn-block"> <i class="fab fa-google fa-fw"></i> Register with Google </a> <a href="index.html" class="btn btn-facebook btn-user btn-block"> <i class="fab fa-facebook-f fa-fw"></i> Register with Facebook </a> </form> <hr> <div class="text-center"> <a class="small" href="forgot-password.html">Forgot Password?</a> </div> <div class="text-center"> <a class="small" … -
How to get each column as one list from a Django QuerySet over DRF
Using Django-REST-framework, I have the following view: class MyRESTfulAPIView(APIView): permission_classes = [IsAuthenticated, MyCustomPermision] def get(self, request): data = MyModel.objects.values('field1').annotate(field2=..., field3=...) return Response(data) Which returns a JSON with the shape: [ {'field1': Result1.field1, 'field2': Result1.field2, 'field3': Result1.field3}, {'field1': Result2.field1, 'field2': Result2.field2, 'field3': Result2.field3}, ... ] Is there a way to get each column as a list of values, like this: { 'field1': [Result1.field1, Result2.field1, ...], 'field2': [Result1.field2, Result2.field2, ...], 'field3': [Result1.field3, Result2.field3, ...], } The exact shape of the JSON is not important, just getting each "column" (model field) as one list of all values, instead of each row as a dictionary. (Because the data then gets passed to a library that expects the data to be in separate lists) Obviously I could just unpack the QuerySet and restructure it with Python, but I am looking for some way to tell either Django or DRF to build the JSON like that in the first place instead having it build it one way and then iterate over it again to restructure it.