Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to achieve multiple output representations in Django Rest Framework Serializer
I am trying to use the Django Rest Framework(DRF)'s serializer with Djnago models with some PostgreSQL fields. I understand that by overriding to_representation() method of the serializer, the outgoing (serialized) data format can be changed. Is there any way to have multiple outgoing representations in DRF serializers? For example, what I am trying to achieve is something like this. from rest_framework import serializers class MySerializer(serializers.Serializer): first_name = serializers.CharField(max_length=20) last_name = serializers.CharField(max_length=20) def to_representation_1(self, instance): return { 'first_name': instance.first_name, 'last_name': instance.last_name } def to_representation_2(self, instance): return { 'firstName': instance.first_name, 'lastName': instance.last_name } def to_representation_2(self, instance): return { 'name': f'{instance.first_name} {instance.last_name}', } Is there such support in DRF? If no, what is the recommended way to achieve this keeping the possibility of nested serializers in mind? -
For validation, when to use Modelform clean or Model clean in django?
I found there are many posts related to validation. But I wasn't sure when to use one of them over the other. Can you clarify the difference between the two and when to use them? -
Django REST API: Deduplicating authorization checks in test code
In a chat app I'm making, I have this (similar) copied and pasted at the top of each API test I've written to check against unauthorized access. def test_message(self): # Unauthorized - 401 client = APIClient() url = reverse("chat-messages-list", host="api", kwargs={"pk": self.chatroom.id},) response = client.post(url, {"text": "this is a test message"}) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # Blocked - 403 client.force_authenticate(user=self.user1) response = client.post(url, {"text": "this is a test message"}) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) Is there a more composable way to structure this so I don't need to copy and paste it at the top of every API test? -
django webhook 301 Moved Permanently error
I am implementing a webhook receiver in the website I am developing to receive POST requests. I am having an issue receiving the POST requests. To test if it is working, I tested sending POST data using curl. It is working fine on local development server but I am receiving 301 Moved Permanently error while testing on the server. If I am testing on local development server like below curl --data "event="CASHGRAM_REDEEMED"&cashgramid="cashgramid"&referenceId="referenceId"&eventTime="now"&utr="utr_1"&signature="GHxFF2JHuFVRg0zSJ4L82ju0QtQx3DAEAy9hF4eLzEs="" http://127.0.0.1:8000/cashfree_cashgram_webhook/ It is working fine. But when I do this to test when the code is on the server curl --data "event="CASHGRAM_REDEEMED"&cashgramid="cashgramid"&referenceId="referenceId"&eventTime="now"&utr="utr_1"&signature="BHvFF2JDuFVTh0zSJ4L82ju0QtQx3DAEAy9hF4eLzEs="" https://mywebsite.com/cashfree_cashgram_webhook/ then I am getting below error. <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>301 Moved Permanently</title> </head><body> <h1>Moved Permanently</h1> <p>The document has moved <a href="https://www.mywebsite.com/cashfree_cashgram_webhook/">here</a>.</p> </body></html> Just for privacy I replaced real webiste address with mywesite.com Below is the view method in the backend to receive POST requests. In this method I am verifying signature and saving the received information. @csrf_exempt def cashfree_cashgram_webhook(request): if request.method == "POST": data = "" for key in sorted(request.POST.keys()): print(request.POST[key]) if key != 'signature': data = data+key+request.POST[key] secretKey = settings.CLIENT_SECRET secretKey = bytes(secretKey, 'utf-8') data = bytes(data, 'utf-8') dig = hmac.new(key=secretKey, msg=data, digestmod=hashlib.sha256) generated_signature = base64.b64encode(dig.digest()) generated_signature = generated_signature.decode('utf-8') # … -
Django cant find CSS for the admin page
this just started today I tried to reset css [27/Oct/2020 22:56:44] "GET /static/admin/css/base.css HTTP/1.1" 404 179 [27/Oct/2020 22:56:44] "GET /static/admin/css/responsive.css HTTP/1.1" 404 179 [27/Oct/2020 22:56:44] "GET /static/admin/css/nav_sidebar.css HTTP/1.1" 404 179 [27/Oct/2020 22:56:44] "GET /static/admin/js/nav_sidebar.js HTTP/1.1" 404 179 [27/Oct/2020 22:56:44] "GET /static/admin/css/dashboard.css HTTP/1.1" 404 179 -
Django makemigrations and migrate
I am having trouble with the py manage.py makemigrations [project_name] and py manage.py migrate command. Every time I try these two commands in the right order, I get the following error: Traceback (most recent call last): File "C:\Users\Gilbert\PycharmProjects\GGprojects\django\manage.py", line 20, in <module> main() File "C:\Users\Gilbert\PycharmProjects\GGprojects\django\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Gilbert\PycharmProjects\GGprojects\django\ll_env\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\Gilbert\PycharmProjects\GGprojects\django\ll_env\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Gilbert\PycharmProjects\GGprojects\django\ll_env\lib\site-packages\django\core\management\base.py", line 301, in run_from_argv connections.close_all() File "C:\Users\Gilbert\PycharmProjects\GGprojects\django\ll_env\lib\site-packages\django\db\utils.py", line 225, in close_all connection.close() File "C:\Users\Gilbert\PycharmProjects\GGprojects\django\ll_env\lib\site-packages\django\db\backends\sqlite3\base.py", line 190, in close if not self.is_in_memory_db(): File "C:\Users\Gilbert\PycharmProjects\GGprojects\django\ll_env\lib\site-packages\django\db\backends\sqlite3\base.py", line 287, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Users\Gilbert\PycharmProjects\GGprojects\django\ll_env\lib\site-packages\django\db\backends\sqlite3\creation.py", line 13, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable Looking at the error, I would tell maybe my Python PATH isn't correct. The current path for it is C:\Users\Gilbert\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.9. Is that the reason there is an error? And will it affect my Django project? Also, how can I solve this problem? -
How to implement json_object_agg() in a Django queryset?
How can I implement the json_object_agg() function from PostgreSQL in a Django queryset within a view? As an example, I'd like to translate a query similar to the one below into a Django queryset (taken from https://postgresql.verite.pro/blog/2018/06/19/crosstab-pivot.html) SELECT city, json_object_agg(year,total ORDER BY year) FROM ( SELECT city, year, SUM(raindays) AS total FROM rainfall GROUP BY city,year ) s GROUP BY city ORDER BY city; with expected output like city | json_object_agg -----------+---------------------------------------------------------------------------------------- Ajaccio | { "2012" : 69, "2013" : 91, "2014" : 78, "2015" : 48, "2016" : 81, "2017" : 51 } Bordeaux | { "2012" : 116, "2013" : 138, "2014" : 137, "2015" : 101, "2016" : 117, "2017" : 110 } Brest | { "2012" : 178, "2013" : 161, "2014" : 180, "2015" : 160, "2016" : 165, "2017" : 144 } Dijon | { "2012" : 114, "2013" : 124, "2014" : 116, "2015" : 93, "2016" : 116, "2017" : 103 } Lille | { "2012" : 153, "2013" : 120, "2014" : 136, "2015" : 128, "2016" : 138, "2017" : 113 } Lyon | { "2012" : 112, "2013" : 116, "2014" : 111, "2015" : 80, "2016" : 110, … -
Copying model instances from one model to another
I'm using django and struggling with model to model inheritance. I have two models model A and B. I want to press a button in the html, which will copy a unique onbect instance from model A and create that same instance in model B, I then delete want to delete the single object instance in model A. Model A is Customer quotes and Model B is Customermarketplacequote, please see views.py below. The below code is not actioning the request? is there a smarter way to do this, or a way to modify the code, below. Appreciate any help or guidance. Views.py def cust_create_marketplace_quote(request, id): if request.method == "POST": quote = Customerquote.objects.get(pk=pk) context = { 'quote': quote, 'values': quote, } quote = Customermarketplacequote(request.POST) if quote.is_valid(): quote.save() return redirect('manage-quotes') else: return render(request,'sub/customer_marketplace_quotes.html') Best, Serick -
Djangon 2.2 filtering a single data set across pages
In my django app I have a main page which shows the numbers of books for each genre in a table and it also has a search bar that allows filtering of the books by Genre, title or author which then posts the data to a search page and allows viewing of the book entries in a table. On the search results page I want to then be able to additionally filter the same set of data further using an extended set of search bars - including the original filters, plus filters such as publish date and rating. In the extended search I would not want to lose the original search - so for example if I search for horror genre on the main page and then wish to filter that further to only include highly rated books on the sesrch page I dont want to lose the horror filter if I don't add the filter again. Is this possible? Essentially I'm wondering if you can apply different filters to a single view? Thank you in advance -
How to programatically post to Django Rest Framework endpoint?
I've got an endpoint built with Django Rest Framework. I now want to separate the ingress and the parsing. So I created an endpoint which basically writes the received string of data to a textfield in. I now create a management command which continuously loops over that table and parses the contents. So I get the I raw string from the ingress table, and I now want to post this to the DRF endpoint programmatically. I've done this many times in my unit tests. But I'm unsure how I can do this from the management command. I can use the same code as I do for test requests, but it seems weird to use testing code in production. People might suggest to manually use the serializer, but there's also things happening in the viewset which I need. Does anybody have a good idea how I would be able to do this? -
Vscode with beautify does not indent django html templates
I am looking to format my django templates in the same manner as HTML. Beautify ends up treating my templates like text, and not indenting their contents. For example, after formatting my code looks like this: <head> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> Instead of <head> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> I currently have Beautify & Django extensions installed, running on VSCode and WSL. settings.json VSCode: "files.associations": { "**/*.html": "html", "**/templates/*/*.html": "django-html", "**/templates/*": "django-txt", "**/requirements{/**,*}.{txt,in}": "pip-requirements" }, "emmet.includeLanguages": { "django-html": "html" }, "beautify.language": { "html": [ "htm", "html", "django-html" ] }, "[django-html]": { "editor.defaultFormatter": "HookyQR.beautify" } Why isn't beautify correctly formatting / indenting my templates? How can I resolve this behavior? -
How to handle management command exception in django app?
I'm working on a django app which is based on consuming an external ZeroMQ message queue - it listens to the queue all the time, processing the messages and saving the outcome in the database. The data will be in the future made accessible to the users by API. Currently I'm running it by a custom management command listen, which runs an infinite loop and it works fine. However, whenever some kind of error appears (and they will sometimes appear, it's an external data source) the command dies. What's the best approach to handle such errors? Things I'm considering: Bash script which will restart the command on failure Big Try... except Exception in the main command function (but this seems extremely wrong) Some custom exception handler - the problem is that the recommended handlers only handle errors in views/requests, and my command is not a view/request, it just runs. Any advice would be useful, maybe it's a misuse of the management command? -
Celery 4.4.0 - Disable prefetch while using SQS as broker
I've looked in multiple SO questions about this but still didn't find a solution, and I'm working on it for several days now, so any help would be appreciated! I'm using celery 4.4.0, SQS as a broker, and Django 2.2, most of my tasks are pretty long (1 to 4 hours). This is the command to start the workers: celery worker -A config.celeryconfig:app -Ofair --prefetch-multiplier=1 --max-tasks-per-child=2 And this configuration within my Django config file: CELERYD_PREFETCH_MULTIPLIER = 1 CELERY_ACKS_LATE = True task_acks_late = True # I wasn't sure what's the name of the ack late configuration. BROKER_TRANSPORT_OPTIONS = { 'polling_interval': 3, 'region': 'us-east-1', 'visibility_timeout': 3600 # 1 hour, } Scenario - let's say we have 2 workers - 1,2 and each with one sub-process and two tasks a(longer than 1 hours),b,c and I've dispatched them around the same time: worker 1 picked up task a worker 1 picked up task c (but not executing) worker 2 picked up task b worker 2 finished with task b worker 2 picked up task c worker 2 finished up task c worker 2 picked up task a (because of the visibility_timeout) worker 1 finished with task a worker 1 start with task c worker … -
How to run django tests in a pre-commit hook
I'm stuck on how to simply run my django tests in a pre-commit hook. I will eventually put them in the push stage, but I'm just trying to get them to run first. It's trying to loop over my tests, but the tests object is a NoneType object. Works fine outside of this hook. I'm sure this is obvious to someone. Thanks. This is my test hook. repo: local hooks: - id: tests name: run tests always_run: true entry: python manage.py test language: system types: [python] -
User Authentication With Django Restframework and google
so i'm new to django and django rest api and i'm struggling with drf authentication. I'm trying to build an api with DRF that enables my users sign up with google. I've spent the last few days doing research but i've found more information on how to implement this in django as an app(which i have successfully done) but i need helping with implementing it in DRF. So far i have tried to use django oauth tool kit and socialoauth but i keep failing because most of the tutorials are not beginner friendly and make a lot of assumptions. I then spend hours trying to find out what they meant. This api will be used by an ios app and a webapp I would really appreciate any help. -
How to map the two heroku connect columns _hc_err and _hc_lastop in django ORM?
I've been trying to map the two columns which automatically gets created by heroku connect i.e. "_hc_err" and "_hc_lastop". These contain the value of the status of syncing to salesforce. Now, when I try to map them in django ORM, considering it to be a text field, it throws an error- (models.E008) Field '{variable_in_model_class}' has column name '_hc_err' that is used by another field. HINT: Specify a 'db_column' for the field. If it means that it is a foreign key rather than a text field, then which table should I relate it to? And what should I specify for Lookup i.e. "sf_field_name", "to" and "to_field" which we use for hc_models? I want these fields to check if the record has been successfully synced to salesforce or not. I know that we can use TriggerLogs but they are there for 30 days max in the archive. I want to check the status later as well. -
Access django rest framework CreateApiView response object with jQuery
I want to create an instance of User with ajax call. My view is a heir of CreateApiView and looks like this: class ManagerSignUp(CreateAPIView): serializer_class = ManagerSignUpSerializer permission_classes = [permissions.AllowAny] def perform_create(self, serializer): property_id = check_identifier(uuid.uuid4()) Hotel.objects.create( name=serializer.validated_data.get('works_for'), property_id=property_id ) serializer.save( title=TitleChoice.manager, property_id=property_id ) The jQuery function looks like following: $('#submitform').click(function () { var form = $(this) $.ajax({ url: form.attr('action'), data: form.serialize(), type: 'post', dataType: 'json', success: function (data) { console.log(data) } }) }) It creates User but as you could've guessed it doesn't log anything to the console, but renders standard DRF page. How can I access the data from serializer and prevent rendering the common DRF HTML? -
Image file not getting stored and Fetched in Django via Template Update View
views.py: from django.shortcuts import render, redirect from django.http import HttpResponse, JsonResponse from .models import Project, Task from .forms import ProjectForm, TaskForm from django.views.generic import (TemplateView,ListView,DetailView,CreateView,UpdateView,DeleteView) # Create your views here. def index(request): projects = Project.objects.all() print("projects: ", projects) form = ProjectForm() if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): form.save() else: print(form.errors) return redirect('/') context = {'projects': projects, 'form': form} return render(request, 'projects/list_project.html', context) class ProjectDetailView(DetailView): model = Project def updateProject(request, pk): project_inst = Project.objects.get(id=pk) form = ProjectForm(instance=project_inst) if request.method == 'POST': form = ProjectForm(request.POST, instance=project_inst) if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request, 'projects/update_project.html', context) models.py from django.db import models from django.utils import timezone from django.urls import reverse from django.conf import settings # Create your models here. def upload_project_image(instance, filename): return "todoapp/files/{filename}".format(filename=filename) class Project(models.Model): title = models.CharField(max_length=200, unique=True) description = models.TextField(null=True, blank=True) image = models.ImageField(upload_to=upload_project_image, null=True, blank=True) duration = models.DurationField(null=True, blank=True) created_date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse("project_detail",kwargs={'pk':self.pk}) def __str__(self): return self.title class Task(models.Model): STATUS= ( ('New', 'New'), ('Assigned', 'Assigned'), ('Selected For Development', 'Selected For Development'), ('In Progress', 'In Progress'), ('Blocked', 'Blocked'), ('Completed', 'Completed'), ) title = models.CharField(max_length=200) description = models.TextField() project = models.ForeignKey(Project, related_name='tasks', on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) current_status = models.CharField(max_length=50, choices=STATUS, default='New') def … -
Is there any Multithreading issue with Kubernetes
I have severe Django API in my application one of the API implement multithreading and return response but when I deploy it using kubernetes That particular API gives performance issue almost all the time it stuck in pending mode for long and does not return a response . without kubernetes it is working fine . Is this issue with the thread ? -
Cant login using hashed password in django
I am trying to implement a custom user model. Whenever I try to log in for a user (created using the registration form), it returns no user. but if I create a user using the admin panel then the login function works perfectly. I think the problem is with password hashing. Tried some solve from here and there but seems like I can't find what I am looking for. The problem I am having : email: yeamin21@outlook.com pass: 1234 works (created using admin panel) but, email: yeamin21@outlook.com pass: hashed(1234) does not (created using the registration form) models.py from django.contrib.auth.base_user import AbstractBaseUser from django.db import models class User(AbstractBaseUser): username = models.CharField(max_length=30,unique=True) email = models.EmailField(verbose_name='Email',unique=True) name = models.CharField(max_length=100) is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) is_restaurant = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' def __str__(self): return self.name class Restaurant(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) location = models.CharField(max_length=200) def __str__(self): return self.user.email forms.py from django.contrib.auth.forms import UserCreationForm from django.db import transaction from Customer.models import User, Restaurant class RestaurantSignUpForm(UserCreationForm): class Meta(UserCreationForm): model = User fields = ['email','name','username'] @transaction.atomic def save(self, commit=True): user = super().save(commit=False) user.is_restaurant=True user.is_active=True user.save() restaurant = Restaurant.objects.create(user=user) restaurant.save() return user backend.py from django.contrib.auth.backends import BaseBackend, ModelBackend from Customer.models import User … -
How to Build a Studying App for mobile phones and PC
I would like to develop an App for studying that will work on mobile phones and on Windows. The idea is that the app should allow me to create different courses and upload study materials for each course where I can access them and read anytime I want to. And I should be able to track my progress for each course. I need some suggestions on how I can implement it, or is there any app that I can use which does what I have mentioned? -
how to create subdomain automatically for each user in django & heroku
I want to create subdomains automatically for each user, like: user1.example.com, user2.example.com, user3.example.com .... or I want to show example.com/user1 to user1.example.com in url using django and heroku. how can I do it? Please try to explain in brief as I am beginner. I am using django with heroku and my domain is on godaady. -
I am trying to add signup page data to django admin table that I created but code is not working
Here is my signup page code:- <body> <form action="/signup" method="POST"> {% csrf_token %} <div id="wrapper"> <div class="main-content"> <div class="header"> <img src="https://www.instagram.com/static/images/web/mobile_nav_type_logo.png/735145cfe0a4.png" alt="noimage"/> <h4>Sign up to see photos and videos from your friends.</h4> </div> <div class="l-part"> <input type="email" placeholder="Email/Mobile Number" class="input-1" name="email" /> <div class="overlap-text"> <input type="text" placeholder="Name" class="input-2" name="name"/> </div> <div class="l-part"> <input type="text" placeholder="Username" class="input-1" name="username"/> <div class="overlap-text"> <input type="password" placeholder="Password" class="input-2" name="password"/> </div> <a href="" ><input type="button" value="SignUp" class="btn" /></a> </div> </div> </div> </div> </form> </body> This is how I rooted url to views from django.urls import path from . import views urlpatterns = [ path('',views.index,name="index"), path('main', views.main, name="main"), path('signup', views.signup, name="signup"), path('signup_page', views.signup_page, name="signup_page"), ] and here is my views section: from django.shortcuts import render from .models import sign def index(request): return render(request, "polls/index.html") def main(request): return render(request, "polls/main.html") def signup_page(request): return render(request,"polls/signup.html") def signup(request): if request.method=="POST": email=request.POST["email"] name= request.POST["name"] username = request.POST["username"] password = request.POST["password"] sign_up=sign(email=email,name=name,username=username,password=password) sign_up.save() return render(request, "polls/signup.html") else: return render(request, "polls/signup.html") Here is my models section from django.db import models class sign(models.Model): email=models.EmailField(max_length=200) name=models.CharField(max_length=100) username=models.CharField(max_length=100) password=models.CharField(max_length=10) def __str__(self): return self.name I tried to do it with this code Please tell me where I am doing wrong as there is no error But the … -
How to create a user in django with custom attributes using create_user?
I'm trying to run a test of the middleware of a django app. Looks like this: class TestAuthenticationMiddleware(TestCase): @classmethod def setUpTestData(cls): cls.user = User.objects.create_user('test_user', 'test@example.com', 'test_password') def setUp(self): self.middleware = AuthenticationMiddleware(lambda req: HttpResponse()) self.client.force_login(self.user) self.request = HttpRequest() self.request.session = self.client.session But I'm getting this attribute error: queryset = user.get_subscriptions_all() AttributeError: 'User' object has no attribute 'get_subscriptions_all' because the User class is defined like this: User(AbstractBaseUser, LimitHelpers): [...] def get_subscriptions_all(self): return self.subscriptions.all().union(self.account.subscriptions.all()) Any idea about how to use the create_user to include the get_subscriptions_all attr? -
Defining enviromental variables Django + Heroku
Can you define env variables in settings.py this way?: DEBUG = 'DEVELOPMENT' in os.environ Have a variable set in Heroku : DEVELOPMENT = False Yet it still works in debug mode.