Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Edited Image is not saving in Admin ( following Toast-tui-image editor )
I am building a Blog App and I am following Toast tui Image editor - Toast tui Image Editor Github. I am editing image on browser with tui Image editor and saving in database. BUT Image is adding but not edited image is adding. I mean selected image is saving without edit effects. forms.py class ImageForm(forms.ModelForm): class Meta: model = Profile fields = ("image",) def save(self): photo = super(ImageForm,self).save() return photo template.html <link type="text/css" href="https://uicdn.toast.com/tui-color-picker/v2.2.6/tui-color-picker.css" rel="stylesheet" /> <link type="text/css" href="/static/e/css/service-basic.css" rel="stylesheet" /> </head> <body> <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> <b>Dreams</b> <input type="file" id="input-image-file" name='photu'> </table> <button type="submit">Save Changes</button> </form> </div> <div class="body-container"> <div class="tui-image-editor-controls"> <div class="header"> <img class="logo" src="img/TOAST UI Component.png" /> <span class="name"> Image Editor</span> <ul class="menu"> <li class="menu-item border input-wrapper"> Load </li> <li class="menu-item border" id="btn-download">Download</li> </ul> </div> <label> <input type="radio" name="input-check-fill" id="input-check-transparent" value="transparent" /> transparent </label> <label> <input type="radio" name="input-check-fill" id="input-check-filter" value="filter" /> filter </label> <script type="text/javascript" src="https://api-storage.cloud.toast.com/v1/AUTH_e18353c4ea5746c097143946d0644e61/toast-ui-cdn/tui-image-editor/v3.11.0/example/fabric-v4.2.0.js" ></script> <script type="text/javascript" src="https://uicdn.toast.com/tui.code-snippet/v1.5.0/tui-code-snippet.min.js" ></script> <script type="text/javascript" src="https://uicdn.toast.com/tui-color-picker/v2.2.6/tui-color-picker.min.js" ></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js" ></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js" ></script> <script type="text/javascript" src="/static/e/dist/tui-image-editor.js"></script> There are so many functionalities so i uploaded few of them. I also tried super().save() method to return image but still not saving the edited … -
Page not found (404) (Django)
I got an error message while clicking [Delete] option/link in post_detail.html: Page not found (404) No comment found matching the query Request Method: GET Request URL: http://127.0.0.1:8000/post/7/comment/delete/ Raised by: blog.views.CommentDeleteView Here is my files: post_detail.html file {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} {% if not post.comments.all %} No Comments Yet... <a href="{% url 'post-comment' post.pk %}">Add Comment</a> <br/><br/><br/><br/><br/><br/> {% else %} <a href="{% url 'post-comment' post.pk %}">Add Comment</a> <br/><br/> {% for comment in post.comments.all %} <strong> {{user}}, </strong> <small> {{comment.date_added}} </small> <br/> {{comment.body}} <br/> {% if request.user == user %} <a href="{% url 'comment-delete' post.pk %}">[Delete]</a> {% endif %} <br/><br/> {% endfor %} {% endif %} {% endblock content %} models.py file from django.db import models from django.urls.base import reverse_lazy from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(default=timezone.now) date_added = models.DateTimeField(default=timezone.now) def __str__(self): return self.title class Meta: ordering = ['-date_added'] views.py file from django.contrib.messages.api import success from django.urls.base import reverse_lazy from users.forms import CommentForm from django import forms from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ( … -
The function can't return callable object from it
I created a function to return a list of categories from data base, however, Django just doesn/t see categories and as a result says it a syntax error in the statement and doen't return it. But on the other funtion which I used it sees the list so my program can see it from data. @register.inclusion_tag('news/list_categories.html') def show_categories(): categories = Category.objects.all() return ("categories": categories) Unexpected expression syntax -
Celery crontab on daily basis
I have run the celery tasks based on crontab for every minutes and 12.30 pm on every day. every minute is working perfectly. But the daily tasks of every day 12.30 pm is not working. Any suggestions ? from celery.schedules import crontab CELERY_BEAT_SCHEDULE = { 'task-second': { 'task': 'app1.tasks.add_schedular', 'schedule': crontab(minute='*/1'), }, 'mail-check': { 'task': 'app1.tasks.mail_schedular', 'schedule': crontab(hour=12,minute=25), } } -
Django default arguments in URL
I have a url path that looks like this: path("asset_app/asset/<str:location>/", views.AssetListView.as_view(), name="asset_app_asset_list"), I want that if location is not set that it sets location = "all" How do I do that? -
Django simplejwt: How to add refresh token to dict?
I am using simplejwt to get an access and refresh tokens. In a view I need to create a dict, where the both will be stored as well as access token claims and another additional data. Everything works but by some reason when the refrsh token is added to dict, it returns its decoded value, but not the token. my views.py @csrf_exempt #@api_view(('GET',)) def check_token(request): token_refresh = RefreshToken.for_user(request.user) print('REFRESH', token_refresh) token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1] data = {'token': token, 'refresh_token': token_refresh} try: valid_data = TokenBackend(algorithm='HS256').decode(token, verify=False) data['uui'] = valid_data['user_id'] data['validUntil'] = valid_data['exp'] data['clientId'] = 'default' print(data) return JsonResponse(data) except ValidationError as v: print("Validation error", v) print('REFRESH', token_refresh) returns the token: 'REFRESH eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI...' but data object returns: {'token': 'eyJ0eXAiOiJKV1QiLCJhbGci...', 'refresh_token': {'token_type': 'refresh', 'exp': 1628664751, 'jti': '38f0e3a4d7bb452681834a6b149aa496', 'user_id': 'None'}, 'uui': 1, 'validUntil': 1628059131, 'clientId': 'default'} my ideal result: {'token': 'eyJ0eXAiOiJKV1QiLCJhbGci...', 'refresh_token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI...', 'uui': 1, 'validUntil': 1628059131, 'clientId': 'default'} -
Can I use the same @property on multiple models in django?
I want to define an @property once and use it on two different models. Is this possible? Example: Suppose I have two models, seller and buyer: class seller(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class buyer(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) And I wish to add a property for the django admin interface to display both models: @property def display_name(self): return f"{first_name} {last_name}" Is there a way to define this property once, but use it for both models? -
Use Django ORM in multiprocess spawn process
i need to use the Django ORM in some spawned process using python multiprocess module. At this moment, this how i spawn the process: import multiprocessing with multiprocessing.get_context('spawn').Pool() as pool: pool.map(insert_to_db, args) Now, here is the issue: the function insert_to_db uses the django ORM to get some objects, check data consistency and save the new collected result to DB. Actually, i can't start the spawned process using fork context due to some unidentified deadlocks. My initial idea is to start a the process, inject the Django dependencies, and before doing the execution of the insert_to_db function execute the django.setup() to load all django things. Anyone is able to give me a solution? -
Run cron job with curl to execute django command management
I have a command management that I should run daily at midnight, I usually execute it from my pc, I want to create a cronjob that can do this automatically here the command that I execute from my local environment: env=application; kubectl exec -ti $(kubectl get pods| grep $env| awk '{print $1}') -c "application" -- ./manage.py daily_job and here the corn job yml file that I wrote: apiVersion: batch/v1beta1 kind: CronJob metadata: name: update-client-tasks labels: environment: application spec: schedule: "0 0 * * *" jobTemplate: spec: template: spec: restartPolicy: OnFailure containers: - name: update-client-tasks image: gcr.io/application-156608/application:v0.5.32 args: - /usr/bin/curl --data "key=$CRON_KEY" http://application/code/ | env=application; kubectl exec -ti $(kubectl get pods| grep $env| awk '{print $1}') -c "application" -- ./manage.py daily_job env: - name: CRON_KEY valueFrom: secretKeyRef: name: application-secrets key: cronKey when running this corn job I got this error: 2021-06-22 09:00:24.184 JSTTraceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/usr/local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], … -
How to configure django standalone app to install automatically all sub apps?
Problem description I have django standalone app named django_codeserver. It can be loaded from my private package registry as a pip-package. My app contains about twenty sub-apps for example django_codeserver.headers, django_codeserver.genders etc. Current behaviour To register all models in my project which uses django_codeserver, I have to register all the sub applications in the parent project INSTALLED_APPS such as: INSTALLED_APPS = [ ... 'django_codeserver.headers', 'django_codeserver.genders' ... ] Preferred behaviour I would want all the sub apps being registred in the parent project when I only: Install the standalone django app as pip-package (pip install django-codeserver) Register only the parent app in parent project installed apps: INSTALLED_APPS = [ 'django_codeserver ] -
How to retrieve employee Id from Azure AD using Django?
I am trying to retrieve the Employee Id using Django as shown above. This platform is derived from Azure Active Directory. What are some of the parameters or ways to CALL the Employee ID? -
My Django form is not displaying on the HTML template
This is the code for the form, model, and template. That refused to show. This project is with urgency to be delivered before next week. I would love if, y'all help me here thanks. this is the forms.py code from voterRegistration.models import voterReg from django import forms from django.forms import ModelForm from .models import voterReg class VoterRegForm(ModelForm): firstname = forms.CharField(initial='First Name', max_length=20) lastname = forms.CharField(initial='Last Name', max_length=30) email = forms.EmailField(help_text='Enter your Email Address') phonenumber = forms.IntegerField() Address = forms.CharField(max_length=70) gender = forms.CheckboxInput() dateofbirth = forms.DateField() state = forms.CharField(max_length=50) local = forms.CharField(max_length=50) occupation = forms.CharField(max_length=20) passport = forms.ImageField() class Meta: model = voterReg fields = ("firstname", "lastname","email", "phonenumber", "Address", "gender", "dateofbirth", "state", "local", "occupation", "passport") def save(self, commit=True): voterReg = super(VoterRegForm, self).save(commit=False) voterReg.firstname = self.cleaned_data["firstname"] voterReg.lastname = self.cleaned_data["lastname"] voterReg.email = self.cleaned_data["email"] voterReg.phonenumber = self.cleaned_data["phone number"] voterReg.Address = self.cleaned_data["Address"] voterReg.gender = self.cleaned_data["gender"] voterReg.dateofbirth = self.cleaned_data["dateofbirth"] voterReg.state = self.cleaned_data["state"] voterReg.local = self.cleaned_data["local"] voterReg.occupation = self.cleaned_data["occupation"] voterReg.passport = self.cleaned_data["passport"] if commit: voterReg.save() return voterReg this is the voterRegistration html template <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width; initial-scale=1; shrink-to-fit=no;"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>e-NEC || Voter Registration page</title> <!--load static--> {% load static %} <!--link to bootstrap and the rest--> <link href="{% static … -
Method for Changing django template to PDF that having either bootstrap or css or both
I have tried via weasyprint , pdfkit but showing errors even though if all errors removed, its showing very unsimilar output as expected .. Can anyone tell me what to do in changing django template that contains either Bootstrap or Css Or both in Django Thanks for any help. -
Django CheckConstraint With IntegrityError
I have a constraint that I'd like to add in my Django Model. I thought the CheckConstraint method would help to catch the error when the input does not meet the constraint. However, when I saved the model with an invalid input, e.g. percentage = 101, an error page was shown with IntegrityError. Does anyone here know how to properly use this method to validate the input? class Meta: constraints = [ models.CheckConstraint( check=Q(percentage__gte=1) & Q(percentage__lte=100), name="Please enter a valid percentage", ) ] -
django select_related().values() not returning all fields from 2 tables
I have 2 tables, one child (Car) and the other parent (Dealership). I'm using the orm query Car.objects.all().select_related('dealership').values() to perform a left join which would give me all the fields from both cars and their related dealerships but that's not happening as I'm only able to get all the fields from the Car model. class Dealership(models.Model): ... class Car(models.Model): dealership = models.ForeignKey(Dealership, on_delete=models.CASCADE, null=True, default=None) ... I read it in a different question that with .values() I'll have to explicitly mention all the required fields but there are just too many fields to enter manually. Is there a cleaner solution to this? -
How to redirect user to the desired page after login using LoginRequiredMixin in django?
I have created a mini project called ToDoList App. I have used class based views for create, update and delete functions. There is MyTasks icon on navbar. What I want? If the user is not logged in and he clicks on MyTasks icon, he should be redirected to the login page and after login to MyTasks page. I have used LOGIN_REDIRECT_URL = 'home' and LOGIN_URL='login' in settings.py file If I write LOGIN_REDIRECT_URL = 'task_list', it is working fine else not. Below is the code from views.py file: class TaskListView(LoginRequiredMixin, ListView): """List of all tasks.""" model = MyTasks context_object_name = 'tasks' template_name = 'task_list.html' This is from urls.py file: path('tasks/', views.TaskListView.as_view(), name="task_list"), I have used the attribute redirect_field_name='next' and tried to override dispatch method in the above class, still it is not working. The output I am getting is, after login, it is getting redirected to homepage instead of my tasks page. Any help is much appreciated. Below is the screenshot from the terminal: [1]: https://i.stack.imgur.com/KtsIG.png -
Object of type Token is not JSON serializable
views.py this is my views.py. when I wanna login I get an error. class AuthAPIView(APIView): def post(self, request, format=None): data = request.data username = data.get('username', None) password = data.get('password', None) user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) token = Token.objects.get(user=user) return Response(token) else: return Response(status=status.HTTP_404_NOT_FOUND) else: return Response(status=status.HTTP_404_NOT_FOUND) I have created a token for each user when registering. and now when I wanna authenticate I get an error. I wanna get my Token instead. -
How to get column names and data types from an SQL query without creating view
I am facing a challenge in Python/Django application. Can anyone help me to find the column names and their data type from a custom sql query. Example Query: SELECT Customers.CustomerName, Customers.Address, Orders.OrderID, Orders.OrderAmount FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID ORDER BY Customers.CustomerName; I need the result as follows:- {"CustomerName":"Varchar","Address":"Text","OrderID":"Int","OrderAmount":"Decimal"} -
Make a form that pulls choices from table in DB and then allows user to change to different foreign keys
So I have a user model with the following columns: username = models.CharField(db_column='Username',max_length=32,unique=True) email = models.CharField(db_column='Email',max_length=255) password = models.CharField(db_column='Password',max_length=128) prosthodontist = models.ForeignKey('Prosthodontist',on_delete=models.SET_NULL,null=True) I'm trying to make a dropdown that allows the user to change their Prosthodontist value through django forms. It can't be a static list cause it has to always have every available Prosthodontist as they get added. Just for show this is what I have so far along the lines of the form: class ChangeProsthodontistForm(forms.ModelForm): class Meta: model = User fields = ('prosthodontist',) prosthodontist = forms.ChoiceField( label = "Prosthodontist", widget = forms.Select( attrs={ 'id':'prosthodontist', }, ), choices=() ) Please help me with this cause I'm really confused I feel like I could be able to iterate through the entries with a for loop but I feel like there has to be a better way through Django. -
How to obtain the field from the parent serializer while serializing a nested json?
Assume this scenario class SerializerA(serializers.ModelSerializer): batch = SerializerB(many=True) class Meta: model = ModelA fields = ['fieldA', 'fieldB'] class SerializerB(serializers.ModelSerializer): class Meta: model = ModelB fields = ['fieldC', 'fieldD'] def validate(self, data): #I want to use fieldA value in this place How to access the field of the JSON one level above the current level while serializing the current level? -
Django Form is Not Visible - Using Model Forms
I'm trying to create a form on my site but the form itself is not visible. I just have a button to 'create post' but the form itself doesn't appear. I've been reading the Django documentation and so far haven't found an answer. I also tried making sure GET requests are explicitly mentioned in my views.py because I saw a post on this site, saying that can sometimes cause this. I'm also using form.as_p in my html file. Not sure what I'm doing wrong. views.py def make_post(request): if request.method == "GET": form_for_post = {'form': PostForm()} return render(request, "network/make_post.html", form_for_post) else: form = PostForm(request.POST) if form.is_valid(): text = form.cleaned_data['text'] new_post = Post.objects.create( text=text, username=request.user, ) print("printing POST:", request.POST) return render(request, "network/make_post.html", { "new_post": new_post, }) def edit_post(request, pk): post = Post.objects.get(id=pk) form = PostForm(instance=post) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): form.save() return render(request, "network/profile.html", { "form_for_post": form, "post": post, }) else: if request.method == "GET": form = PostForm() form_for_post = {'form': form} return render(request, "network/make_post.html", { "post": post, "form_for_post": form, }) relevant urls.py path('edit_post/<str:pk>/', views.edit_post, name="edit_post"), path("make_post", views.make_post, name="make_post"), html <div class="container"> <div class="add"> <h3> Write Your Post! </h3> <form method="POST" id="post-form" enctype="multipart/form-data"> {% csrf_token %} {{ … -
Using django-autocomplete-light and django-addanother for the same field in a ModelForm
I'm trying to implement django-autocomplete-light and django-addanother for the same field in a ModelForm. I've tried the following: import floppyforms.__future__ as forms from .models import Worker from dal import autocomplete from organizations.models import Hub from django.urls import reverse_lazy from django_addanother.widgets import AddAnotherWidgetWrapper from django.forms import MultiWidget class WorkerCreateForm(forms.ModelForm): class Meta: model = Worker fields = ['display_name', 'hub', 'capacity', 'vehicle', ] widgets = { 'hub': autocomplete.ModelSelect2(url='hubs-autocomplete', attrs{'data-html': True}), 'hub': AddAnotherWidgetWrapper( forms.Select, reverse_lazy('create_hub')) } This will only render the AddAnotherWidgetWrapper obviously. I've tried to use MultiWidget in multiple ways and every time I got a different error (I will not post all my trials and errors since most of them don't make a lot of sense, but if you think I should share them I would be happy to do so). I'm finding it hard to understand how to use MultiWidget since there are no clear examples, and I'm not sure if it's the right solution for my use case. In django-autocomplete-light's documentation, they recommend using django-addanother for adding a model with multiple fields, but there's no explanation on how to implement it. I'd like to know if there's an easy way to use both packages together or if I should write … -
zsh: command not found: django-admin?
I installed django but when i run command django-admin startproject send_email it gives an error showing zsh: command not found: django-admin what can i do please help me. i search same question in google but the answers are not working pathparakh@Paths-MacBook-Air send_email % django-admin startproject send_email zsh: command not found: django-admin pathparakh@Paths-MacBook-Air send_email % python3 Python 3.9.6 (v3.9.6:db3ff76da1, Jun 28 2021, 11:49:53) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> django.VERSION (3, 2, 5, 'final', 0) >>> -
query one to many and array of id
First i have this problem: I want to send an array of id to the backend and then search for some things related to that id. but I don't know how to send the array, I am using this form. How should I pass the array to that url? var ids = [1,3,34,76,114] ... await self._list (`1.0/cda/inventariov/`, (response) => {}) Second: I have this url in the backend router.register (r'tecnico', viewsets.TecnicoViewSet) this is the view set class TecnicoViewSet ( mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): queryset = Technician.objects.all () serializer_class = Tecnicoserializer def list (self, request): data = request.data # [1,23,43,65] return Response(data) when I receive the array from step 1, I want to search all the information related to the id in different tables. As I said before, I have received the id of the technicians to consult, a model is work_orders so I want to obtain all the work orders made by each technician. apart from that I also need more queries to other models in the same viewset, but I think that is enough. this is the tecnico model class Tecnico(BaseModel): foto = models.ImageField(blank=True, null=True, verbose_name='Foto tecnico', upload_to='cda/pictures') empleado = models.IntegerField(null=True) categoria_tecnicos = models.ForeignKey('cda_configuracion.listaitems', related_name='Categoria_tecnico', on_delete=models.PROTECT) activo … -
Normal text field workable but once i add in form control it stop working
Currently I have this form where the inputs are normal textfield (Basic look) and it works. But once i add in form control, it stop working. In my HTML (One part of the text field) Workable <div class="col-md-5"> <div class="form-group"> <label for="{{form.hostname.id_for_label}}">Hostname</label> {{form.hostname}} </div> </div> But if i change it to Not workable <div class="col-md-5"> <div class="form-group"> <label for="{{form.hostname.id_for_label}}">Hostname</label> <input class="form-control" type="text" id="form.hostname.id_for_label" name="form.hostname" placeholder="" required> </div> </div> Am i doing something wrong? Appreciate if anyone could help