Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework Read-Only Field Issue
I am learning DRF and I encountered one issue. I have slug field in model which I want to be slugified fom title. The issue is I can`t complete this auto population whatever ways I tried. I have created custom save method in model like this: class Post(models.Model): class PostObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(status="published") options = (("draft", "Draft"), ("published", "Published")) category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1) title = models.CharField(max_length=250) excerpt = models.TextField(null=True) content = models.TextField() slug = models.SlugField(max_length=250, unique_for_date="published") published = models.DateTimeField(default=timezone.now) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name="blog_posts" ) status = models.CharField(max_length=10, choices=options, default="published") objects = models.Manager() postobjects = PostObjects() class Meta: ordering = ("-published",) def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title Then I tried making the field read only with couple of ways in Serializer.py: class PostSerializer(serializers.ModelSerializer): slug = serializers.ReadOnlyField() class Meta: model = Post fields = ("id", "title", "author", "excerpt", "content", "status", "slug") #read_only_field = ["slug"] #extra_kwargs = {'slug': {'read_only': True}} All three ways (ReadOnlyField, read_only_fields, extra_kwargs) give me error that slug is required. I also tried to create custom "perform_create" in views so I can supply this slugify to .save method but no result again, as is.valid gives false Any help is … -
How to use mathjax in django-ckeditor?
I'm currently developing with Django, and I use django-ckeditor to use ckeditor. I want to use mathjax in ckeditor, but the settings are not reflected in ckeditor. What should I do? My settings.py CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'toolbar_Custom': [ ['Bold'], ] } } It works in the example above, but not in the example below. CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'toolbar_Custom': [ ['mathjax'], ] } } It seems mathjax support on default though. https://django-ckeditor.readthedocs.io/en/latest/ -
Django - saving over ImageFile appends upload path to filename
I'm trying to resize an ImageField image and overwrite the existing file. I'm using Django 3.1.2 and Pillow 8.0.0. When I save the updated image, its upload_to path seems to get prepended to the existing file path. I don't know why it's doing that, and I want it to stop. The field is defined as: hero_image = models.ImageField(blank=True, null=True, upload_to="images/articles/hero") Here's a reproducible example of what's happening: from my_app.models import Article from PIL import Image, ImageOps from six import BytesIO # load an Article article=Article.objects.get(id=6019) # get its image article.hero_image > <ImageFieldFile: images/articles/hero/park_lake_5.jpg> # open the image image_file = Image.open(article.hero_image) # resize the image image_file_fit = ImageOps.fit(image_file, (100,100), method=Image.LANCZOS) # create a stream image_content = BytesIO() # save updated image to stream image_file_fit.save(image_content, format="JPEG", quality=80) # create a new image file from the stream new_image_content = ImageFile(image_content) # save the new image content into the existing image field article.hero_image.save(article.hero_image.name, new_image_content) # inspect the updated image article.hero_image <ImageFieldFile: images/articles/hero/images/articles/hero/park_lake_5.jpg What's going on? What am I doing wrong? -
How to segregate a django queryset according to given fields
# models.py class CartProduct(models.Model): cart = models.ForeignKey(to=Cart, on_delete=models.PROTECT, verbose_name=_("Cart")) product = models.ForeignKey( to=Product, on_delete=models.PROTECT, verbose_name=_("Product in Cart") ) outlet = models.ForeignKey( to=Outlet, on_delete=models.PROTECT, verbose_name=_("Outlet") ) delivery_time_from = models.TimeField(verbose_name=_("Delivery Time From")) delivery_time_to = models.TimeField(verbose_name=_("Delivery Time To")) delivery_date = models.DateField(verbose_name=_("Delivery Date")) ordering_option = models.CharField( verbose_name=_("Ordering Option"), choices=ORDER_ORDERING_OPTION_CHOICE, max_length=20, default=IMMEDIATE, ) # utils.py def groupby_queryset_with_fields(queryset: QuerySet, fields: List): from itertools import groupby for field in fields: queryset = queryset.order_by(field) def getter(obj): related_names = field.split("__") for related_name in related_names: try: obj = getattr(obj, related_name) except AttributeError: obj = None return obj fields_qs = [ list(group) for _, group in groupby( queryset, lambda x: getattr(x, field) if "__" not in field else getter(x), ) ] return fields_qs # implementation cart = Cart.objects.get(id=some_id) products = CartProduct.objects.filter(cart=cart).select_related("outlet") # working as expected data = groupby_queryset_with_fields(queryset=products, fields=["outlet"]) # this is working fine and giving correct result output -> [[<ProductInCart: ProductInCart object (1)>], [<ProductInCart: ProductInCart object (2)>, <ProductInCart: ProductInCart object (3)>, <ProductInCart: ProductInCart object (4)>]] # not working data = groupby_queryset_with_fields(queryset=products, fields=["outlet", "delivery_time_from", "ordering_option"]) # this segregated the queryset according to ordering option output -> [[<ProductInCart: ProductInCart object (0)>, <ProductInCart: ProductInCart object (1)>, <ProductInCart: ProductInCart object (2)>], [<ProductInCart: ProductInCart object (3)>]] I'm trying to segregate a queryset according to given … -
How best to implement the logic for determining the post rank in serializer in Django?
Now I have the serializer like: class PostTopSerializator(serializers.ModelSerializer): id_post = serializers.IntegerField(source='id') comment_count = serializers.SerializerMethodField('get_count_comment') rank = serializers.SerializerMethodField('get_rank') class Meta: model = Movie fields = ['id_post', 'comment_count', 'rank'] def get_count_comment(self, object_id): total_comments = Comment.objects.filter(movie_id=object_id).count() return total_comments def get_rank(self, object_id): return object_id.id the Post with the most comments gets rank 1, second place rank 2, and so on... And I get answer like: [ { "id_movie": 2, "comment_count": 5, "rank": 2 }, { "id_movie": 1, "comment_count": 4, "rank": 1 }, { "id_movie": 3, "comment_count": 4, "rank": 3 } ] how to implement the logic of the methoв: def get_rank(self, object_id): return object_id.id to get the same rank with the same number of comments and the output will be: [ { "id_post": 2, "comment_count": 5, "rank": 1 }, { "id_movie": 1, "comment_count": 4, "rank": 2 }, { "id_post": 3, "comment_count": 4, "rank": 2 } ] -
How to migrate old data to django-quill-editor
I had a textField in my model before. Now I want to upgrade it to quillfield. But I am unable the migrate the old data. I tried to just copy the text inside the quillfield in a management command but it gives QuillParseError then I looked the databse and figured that the fields are stored like: {"delta":"{\"ops\":[{\"insert\":\"text\\n\"}]}","html":"<p>text</p>"} in the database. I kept the delta empty and only filled the html. the html appeared in the databse but not in the admin. I then tried to fabricate the ops. without filling the html and that failed too. I can only think of fabricating the whole object but that would be a bit difficult. I was wondering if there is any sane way to migrate html/text data to quillfield or any other richtext editor. -
Django rest framework model viewset extra action responding always "Not found" error
why does setting customize actions for the model view set is not working well? from topbar.models import TopBar this is the relevant part in viewset code: from rest_framework import viewsets from rest_framework.decorators import action from rest_framework import permissions from rest_framework.exceptions import NotAcceptable from rest_framework.response import Response from rest_framework.decorators import action from topbar.serializers import TopBarSerializer class TopBarSet(viewsets.ModelViewSet): """ API endpoint from top bar content """ queryset = TopBar.objects.all() serializer_class = TopBarSerializer permission_classes = [permissions.IsAuthenticated] http_method_names = ['get', 'post', 'put'] @action(detail=True, methods=['get']) def set_topbar(self, request): return Response({'status': 'topbar set'}) I'm using routing exactly like the documentation: router = routers.DefaultRouter() router.register(r'topbar', TopBarSet, basename='topbar') -
Pushing a Django Python App to Heroku for web hosting. Creating superuser gets an Operational Error and could not connect to server
I am pushing a Django Python App to Heroku for web hosting. I am following a tutorial, the build was successful, and loads up fine as a Heroku app. Django Admin page loads up, but superuser cannot log in as the next step is database configuration. The tutorial then goes: heroku run python manage.py makemigrations heroku run python manage.py migrate heroku run python manage.py createsuperuser This creates the following error: psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Before running these commands, the tutorial attempted to login as superuser in the heroku app. The tutor got a 'programming error', but I had an 'operational error'. Now, somehow, I managed to make the database changes in settings.py for the next tutorial video already. I hope it's not this that has fudged things? -
running multiple tasks (ffmpeg) at the same time in a django app
at the title says it, I made a django app that cuts and merge files with ffmpeg while testing (me being the only user), it looks fine, but later when using the app from different browsers running tasks at the same time, looks like it's a queue of tasks and other users will wait for their turn, what I'm thinking about is, is there a possibility to run multiple tasks simultaneously at the same time, like (screens on linux) under django framework? thanks a lot -
how to mock a method which has both post and get api calls in django
This my actual code which performs get and then post api call to external service. And I have to write unit test for 'senduserdata'. Foo.py from requests_futures.sessions import FuturesSession def senduserdata(): usernames = getusername() postdata() def getusername: with FuturesSession() as session: futures = session.get() return futures.response def postdata(): with FuturesSession() as session: futures = session.post() return futures.response What I tried in unit test: Unittest.py from concurrent.futures import Future from unittest import mock from django.test import TestCase from django.urls import reverse @mock.patch('app.FuturesSession.post') def test_senduserdata(self, mock): self.mock_response(mock) senduserdata() mock_post.assert_called_with() def mock_response(self, mock): mock.reset_mock() future = Future() future.set_result(Response()) mock.return_value = future How can I add get mock in the same unit test -
How can I create unique pop up windows displaying different content in dtl and html?
I am wondering how to display different content on each pop-up window using django and html. Ι have the following code: {% for sect in sects %} {% if sect.name %} <p><div class="popup" onclick="myFunction()" id="{{ sect.name }}">{{sect.name}}</p> <span class="popuptext" id="myPopup"> <table class="table table-hover" style="text-align:left; width:100%" cellpadding="1"> <tr> <th>Περιγραφή</th> <th>{{sect.description| safe | linebreaks}}</th> </tr> <tr> // ... more stuff here..// </table> </span> </div> <script> // When the user clicks on <div>, open the popup function myFunction() { var popup = document.getElementById("myPopup"); popup.classList.toggle("show"); } </script> {% endif %} {% endfor %} So the result is to have a list of my sect items printed in my page, but only one (the same) pop-up. Trying to have a unique id (named after the sect.name) or trying to pass it as an argument to myFunction() does not seem to work. Could you please give me a hint on this? Thank you very much! -
How to change THIS specific text output in django admin?
Hey im working in django 3.1 and i literally only need to change the name of the sections (example ACCOUNT on the Blue bar) i know how to change the verbose name of the models but that does not affect the section name. Any help? i need to have this working on spanish and it's a little messy to rename the models to the spanish word. Any solution that only affects the output text??? not the whole File name (Account is the name of the file, wich contains the 3 class below) -
Django api response is late. is there any good solutions?
I'm using django and react to build a website and I faced the problem that before react get a response from api, react excutes the next line. I could combine the function calling api and the swipe function, but it will be hard to read. I want to separate them if I could. Here is my code. const liked_getter = (user) => { var liked_data axios.get(`${process.env.REACT_APP_API_URL}/swipe/detail/${user}/`) .then(res => { liked_data = res.data.liked }) return liked_data } const swiped = (direction, person) => { if (direction === 'right') { var liked_data = liked_getter(person.user) if (liked_data.includes(props.id)) { console.log('MATCH') } } } liked_getter get the data from api based on user id, and I store data in liked_data, but react executes the next line "if (liked_data.includes(props.id))" as liked_data=undefined. It worked when I combined these two functions like this. const swiped = (direction, person) => { setLastDirection(direction) alredyRemoved.push(person.name) if (direction === 'right') { props.Swipe(props.swipe_id, person.user, person.user) //var liked_data = liked_getter(person.user) axios.get(`${process.env.REACT_APP_API_URL}/swipe/detail/${person.user}/`) .then(res => { if (res.data.liked.includes(props.id)) { console.log('MATCH') } }) } else { props.Swipe(props.swipe_id, person.user, null) } } However it's hard to read and I'm going to add more code here. Is there any good ways to divide them? Thank you :) -
No module named "django.core.asgi"
I"m deploying django app based on channels and when i run daphne -b 0.0.0.0 -p 8001 repository.asgi:application then i get the error No module named "django.core.asgi". What should be done? -
Django not returning queryset despite using get,filter and all
Please I am a beginner and I'm trying to make a Hospital Management System.I want to display the Patient profile however it is only returning the first name in my queryset. I need all the data saved to my database displayed.I've tried filter, get and all.They return only the first name as defined in my str method. Views def ProfileView(request): profile = Patient.objects.filter(email=request.user.email) return render(request,'profile.html',{'profile':profile}) Models class Patient(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email= models.EmailField(unique=True) phone_number = models.CharField(max_length=11) address = models.CharField(max_length=255) def __str__(self): return self.first_name Profile.html {%extends 'base.html'%} {%load static%} {%block content%} <div class="container"> {{profile}} </div> {%endblock content%} Result that displays in html <QuerySet [<Patient: Kehinde>]> -
How integrate Liqpay in django python3?
How inegrate liqpay in python3??enter image description here -
django admin disable password change for specific user
I'm currently working on a SAAS project and I would like to create an admin user for demo that anyone can access. To remove change password, I tried using set_unusable_password() but it does not work as it says password is incorrect when I try to log in. This is the code I'm using : admin = Admin.objects.create_user('admin', password='admin') admin.is_superuser = True admin.is_staff = True admin.set_unusable_password() admin.save() After looking at the docs, I found out that set_unusable_password marks the user as having no password set, and doesn’t save the User object. This explains why I could not login at the first place. So clearly set_unusable_password is not the solution. What I actually want is to login as usual, but for that specific user, the change password should be disabled, as the demo account will be used by all other testers and therefore the password should not be changed by anyone. -
All orders are not showing
I want to show all orders in a table of my panel but its not showing.Its showing in django admin but not showing in my panel. Here is my Views.py: class AdminPanel(View): def get(self, request): products = Product.get_all_products() cats = Category.get_categories() orders = Order.get_all_products() args = {'products':products, 'cats':cats, 'orders':orders} return render(self.request, 'adminpanel/main.html', args) Here is my HTML file: <table class="table table-bordered"> <thead> <tr> <th scope="col">Sno.</th> <th scope="col">Date</th> <th scope="col">Invoice ID</th> <th scope="col">Customer Name</th> <th scope="col">Phone Number</th> <th scope="col">Product Quantity</th> <th scope="col">Status</th> <th scope="col">Total</th> </tr> </thead> <tbody> {% for order in orders %} {% if orders %} <tr> <th scope="row">{{forloop.counter}}</th> <td>{{order.date}}</td> <td>GNG#{{order.id}}</td> <td>{{order.fname}}</td> <td>{{order.phone}}</td> <td>{{order.quantity}}</td> <td>{{order.status}}</td> <td>{{order.price}}</td> </tr> {% else %} <h5 class="badge badge-danger">No Orders Found</h5> {%endif%} {% endfor %} </tbody> </table> -
Github best practices - various django applications
I have an application that consists of more than one django APP. Each APP works separately, has its own VM to process requests. Today we use the following structure in GITHUB: Project ├── application1 # this application works in a separated vm ├── application2 │ ├── app # app folder │ ├── requirements.txt #requirements file │ └── manage.py └── ... I was thinking of decoupling this project in more than one repository. Each will address an application. With this approach, I can build a CI / CD pipeline for each application I would like to know from you what is the best practice to solve this problem. Whether it’s good to keep all aspects of the project in one repository or split into more than one -
Sing in and Sing up in same page Django
i'm working on a project with django and i have a problem, i need to have Sing In and Sing Up in same page; I tried many code, but no one work, when i try to log in the page redirect me without log me. How can i solve this problem ? Views.py I think the error is here, but i don't know def Registrazione(request): if request.method == "POST": if 'Register' in request.POST: form = Registrazioneform(request.POST) if form.is_valid(): username = form.cleaned_data["username"] email = form.cleaned_data["email"] password = form.cleaned_data["password1"] if User.objects.filter(username=username).exists(): return HttpResponse ("<h1>Username gia presente</h1>") else: user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) email_subject = 'Activate Your Account' message = render_to_string('activate_account.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)),#decode(), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage(email_subject, message, to=[to_email]) email.send() elif 'Login' in request.POST: #username = request.POST['username'] #password = request.POST['password'] #user = authenticate(username=username, password=password) #if user is not None: #login(request, user) #return HttpResponseRedirect("/") username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request,user) return HttpResponseRedirect('/') else: print("NOT WORK") return HttpResponse("Your account was inactive.") else: print("Someone tried to login and failed.") print("They used username: {} and password: {}".format(username,password)) return HttpResponse("Invalid login details given") else: … -
How to differentiate multiple GenericForeignKey relation to one model?
I have the following model structure: class Uploadable(models.Model): file = models.FileField('Datei', upload_to=upload_location, storage=PRIVATE_FILE_STORAGE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Inspection(models.Model): ... picture_before = GenericRelation(Uploadable) picture_after = GenericRelation(Uploadable) I wonder how I can tell that one file was uploaded as a picture_before and another as picture_after. The Uploadable does not contain any information about it. Googled around for some time but did'nt find a proper solution. Thanks for the support! -
How to link anchor to another tab and also within the same tab in Django template
I'm building a page with dynamic tabs base on reference to document https://www.w3schools.com/howto/howto_js_tabs.asp I'm using Django framework. I'm facing issue on linking my tab internally within the tab itself, also from tab to tab. When the page is loaded, it will first holds 2 tabs: the Form Tab and the Summary Tab. If form is filled correctly, the flow will generates dynamic tabs, Check Tabs, IE Check 1, Check 2, Check 3 Tabs appending to the same page after Summary Tab. I managed to generate all the tabs but can't anchor item within 'Summary Tab' to 'Check Tab. Besides, I also fail to anchor within the same tab. Can someone gives suggestion how to solve this problem? I would like to avoid using a bootstrap if possible. My js file: function openSummary(evt, summaryName) { // Declare all variables var i, tabcontent, tablinks; // Get all elements with class="tabcontent" and hide them tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } // Get all elements with class="tablinks" and remove the class "active" tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } // Show the current … -
Django for windows, using WSGIPythonPath for multiple instances of Virtual Host
Im using Windows 10 In httpd.conf (Apache) how to use WSGIPythonPath for multiple instances of Virtual Host for different project and ports since WSGIDaemonProcess is not supported on Windows. httpd.conf LoadModule wsgi_module "c:/users/webdev/documents/mark/digos-logs/venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "C:\Users\WebDev\AppData\Local\Programs\Python\Python37" WSGIPythonPath "C:\Users\WebDev\Documents\Mark\digos-logs" where "C:\Users\WebDev\Documents\Mark\digos-logs" is my project root folder and "C:\Users\WebDev\Documents\Mark" is my parent folder of all my projects. Project 1 listen 9292 <VirtualHost *:9292> ServerName 127.0.0.1 # error occured (Example) WSGIPythonPath "C:\Users\WebDev\Documents\Mark\digos-logs" ######3 WSGIScriptAlias / "C:\Users\WebDev\Documents\Mark\digos-logs\app_ict\wsgi.py" <Directory "C:\Users\WebDev\Documents\Mark\digos-logs\app_ict"> <Files wsgi.py> Require all granted </Files> </Directory> DocumentRoot C:\Users\WebDev\Documents\Mark\digos-logs <Directory "C:\Users\WebDev\Documents\Mark\digos-logs\static"> Require all granted </Directory> </VirtualHost> Project 2 listen 9595 <VirtualHost *:9595> ServerName 127.0.0.1 # error occured (Example) WSGIPythonPath "C:\Users\WebDev\Documents\Mark\project2" ######3 WSGIScriptAlias / "C:\Users\WebDev\Documents\Mark\project2\app\wsgi.py" <Directory "C:\Users\WebDev\Documents\Mark\project2\app"> <Files wsgi.py> Require all granted </Files> </Directory> DocumentRoot C:\Users\WebDev\Documents\Mark\project2 <Directory "C:\Users\WebDev\Documents\Mark\project2\static"> Require all granted </Directory> </VirtualHost> -
Django website very slow using Apache and mod_wsgi
so today I tried to host a website using django on a Ubuntu vServer using Apache and mod_wsgi. First I tested it with a blank django project, and everything worked perfectly, but as soon as I put my django project on the server and set Apache up to run with that, the performance of the server dropped a lot. When accessing the website using apache, the response time is about 10 seconds per page, in contrast do about 100ms when using the django dev server. Does any body have any tips on what could be the cause of that? I've read that there may be problems with the some mpm workers, but i didnt really find the files i would need to adjust on my server. The apache server config looks like this(paths changed): <VirtualHost *:80> . . . Alias /static /home/sammy/myproject/static <Directory /home/sammy/myproject/static> Require all granted </Directory> <Directory /home/sammy/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-home=/home/sammy/myproject/myprojectenv python-path=/home/sammy/myproject WSGIProcessGroup myproject WSGIScriptAlias / /home/sammy/myproject/myproject/wsgi.py I would really appreciate any help or tips in general. -
Django not taking users to the "password_change" url
I'm trying to add a functionality for users to change their current password. But, when I click on the link to take me to the password change form, it takes me to the default django password change form, which is in the admin site. But I had built out a template for changing the users password. I have two apps: one called pages, and another called users. I have a templates directory both in my users and pages app. My base.html is in my users app. And, here is my project structure: My pages app template contains the home.html file. My base.html and signup.html is in my users app templates I have another folder called registration in my users/templates folder. In this registration folder, I have login.html, password_change_form.html and password_change_done.html Here is the line that links my base.html to my password_change_form.html: <a class="dropdown-item" href="{% url 'password_change'%}>Change password</a> I believe this should work, but I might be wrong, as I'm still new. Any help would be appreciated.