Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add apple-app-site-association file to Django project
I am new to Django. I need to test how Universal Links works with web-site which is on Django. I added my site url to xcode Associated Domains and added apple-app-site-association file to root folder on my server which is used as root foolder by Django. This way doesn't work. My apple-app-site-association file works nice, I have alredy done that with github pages and it works fine. But i think there is another to add apple-app-site-association file in Django. Thank you in advance for help! -
Django Is Inserting instead of Updating the AutoField?
I am trying to perform crud operations but when i try to update then django add's a new row in the db with the new pk 'id'. I am using autofield set to primary_key = True(default). Views.py @login_required def edit(request,id): note = UserCreatedNote.objects.filter(pk=id,user=request.user) if request.method == 'POST': form = AddNoteForm(request.POST,note[0]) if form.is_valid(): form_data = form.save(commit=False) form_data.user = request.user //cause i have excluded this field in form. form_data.save() form = AddNoteForm(instance=note[0]) context={'note':note[0],'u_form':form} return render(request,'edit_note.html',context) -
Django elasticsearch_dsl only 10 results getting returned
currently my Django elasticsearch view only returns 10 results where I expect at least 15 results to be returned. After some searching on the web I figured out that size = 10 See more here: How to Get All Results from Elasticsearch in Python But I don't understand how my syntax has to look like, this is how i query for post objects: post = PostDocument.search().query("multi_match", query=qs, fields=["title", "content", "tag"]).to_queryset() I also tried: post = PostDocument.search(size=1000).query("multi_match", query=qs, fields=["title", "content", "tag"]).to_queryset() But with no success. Can smb. tell me how to change the default size to a higher value than 10 using elasticsearch_dsl with Django. Thanks in advance -
Unit test django inline formset factory
I'm working on a project using Python(3.8) and Django(3.1) in which I have few models as Course, Module etc and for the forms, I have created an Inline Formset factory (to provide the user a better experience while adding modules to courses). Now I want to unit test that form, what should be the approach and how it can be achieved? Here's my forms.py: MYFormSet = inlineformset_factory(Course, Module, fields=['title', 'short_descp'], extra=1, can_delete=True) and here are my models: class Course(models.Model): instructor = models.ForeignKey(Account, related_name='courses_created', on_delete=models.CASCADE) subject = models.ForeignKey(Subject, related_name='courses', on_delete=models.CASCADE) title = models.CharField(max_length=200) overview = models.TextField() created = models.DateTimeField(auto_now_add=True) students = models.ManyToManyField(Account, related_name='courses_joined', blank=True) course_image = models.ImageField(upload_to='images') class Meta: ordering = ['-created'] def __str__(self): return self.title class Module(models.Model): course = models.ForeignKey(Course, related_name='modules', on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(blank=True) order = OrderField(blank=True, for_fields=['course']) def __str__(self): return f'{self.order}. {self.title}' class Meta: ordering = ['order'] -
Django queryset keyword from string
This is my model class Mymodel(models.Model): title = models.CharField(max_length=150) author = models.CharField(max_length=150) I have a json like this stored in db q = {"field_name": "title", "value":"django"} and this is what I am trying to do. Mymodel.objects.filter(q["field_name"]=q["value"]) It is not working. Getting the error SyntaxError: keyword can't be an expression How can i make this working ? I have tried things like Mymodel.objects.filter(getattr(event_model, q["field_name"])=q["value"]) It is possible to make it work like many if elif conditions like below but the code becomes ugly. Is there any cleaner way to do this ? if q["field_name"] == "title": Mymodel.objects.filter(title=q["value"]) elif q["field_name"] == "author": Mymodel.objects.filter(author=q["value"]) -
Django Models: Have Trouble with 2 Subqueries (No Foreign Keys)
I have 2 models: TeamsDatabase and EmployeeDatabase EmployeeDatabase has the following columns: emp_id emp_name emp_status emp_team_id emp_role TeamsDatabase has the following columns: team_id reporting_1 I would like to query EmployeeDatabase and join the column reporting_1 from TeamsDatabase where team_id equals emp_team_id. From the resulting reporting_1 (which is the equivalent of emp_id in EmployeeDatabase) value, I want to display the employee name from EmployeeDatabase. (I am limiting my query set to 1.) My django code is below: subquery1 = Subquery(TeamsDatabase.objects.filter(team_id=OuterRef('emp_team_id')).values('reporting_1')) subquery2 = Subquery(EmployeeDatabase.objects.filter(emp_id=subquery1).values('emp_name')) emp_qs = EmployeeDatabase.objects.values('emp_id', 'emp_status', 'emp_team_id', 'emp_role').annotate(reporting_1=subquery2).filter(Q(emp_status='ACTIVE') | Q(emp_status='SERVING NOTICE')).order_by('emp_team_id')[:1] df = read_frame(emp_qs) The expected result is this: Instead, row 1 has JOHN DOE under reporting_1 column, in place of YULISSA HERNANDEZ. (Of note, the text BRAZIL displayed under the column emp_team_id below is the display choice for team ID 1000). In fact, all my rows have JOHN DOE under reporting_1 column. The employee ID of JOHN DOE is 302052. When queried separately where team_id = 1000: SELECT reporting_1 FROM teamsdatabase WHERE team_id = 1000; the result is 150115016 When queried separately where emp_id = '150115016': SELECT emp_name FROM employeedatabase WHERE emp_id = '150115016'; the result is YULISSA HERNANDEZ In PgAdmin using the raw SQL, I get the same … -
Getting a proper dropdown List in ManyToMany Field in django form
These are the two models i am working on: class Category(models.Model): Name = models.CharField(max_length=20) class Listing(models.Model): Category = models.ManyToManyField(Category, verbose_name="Categories") ...... This is the form class in forms.py: class NewForm(ModelForm): class Meta: model = Listing fields = [....., 'Category'....] Now, when i declare form = NewForm(), the input field shown is something like this: Category object (1) Which is understandable as Category model is a ManyToMany field to the model Listing. But what i want is the options to show the "Name" attribute of class Category. But i don't understand how to get it done. -
how to view and download pdf of my current html page in django
i need to view and download pdf format of my current html page in django.can you please reffer me some code to resolve this issue. views.py def pdf(request): date_from=request.POST.get("date_from") print(date_from,"date frommmmmmmmmm==========") date_to=request.POST.get("date_to") print(date_to,"datetoooooooooooo=================") a=db_orderritem.objects.all().filter(timestamp__lte=date_to,timestamp__gte=date_from) b=db_orderr.objects.all().filter(timestamp__lte=date_to,timestamp__gte=date_from) pdf = render_to_pdf('pdf/report.html', {'odl':a,'od':b}) return HttpResponse(pdf, content_type='application/pdf') -
Django administration for two Django projects
I have two Django projects(not apps). their database will be combined in one db cluster. So half models will be in one project and half in another. My question - how can I create Django administration site for models from two projects? I don't understand^ because I can't register models from second project in adminpy. Any suggestions please? -
Why did the Django database receive duplicate posts using fetch in Javascript?
I have an email form in inbox.http, and wanted to send the form to my Django database - the email model. The email form was submitted to the database using the JavaScript function. When I submitted the email form, sometime two same emails were received or stored in the email model on the Django database, sometime six emails. I do not know why that has happened and how to resolved the issues. Your explanations and resolutions would really be appreciated. The form in inbox.html <div id="compose-view"> <h3>New Email</h3> <form id="compose-form"> <div class="form-group"> From: <input disabled class="form-control" value="{{ request.user.email }}"> </div> <div class="form-group"> To: <input id="compose-recipients" class="form-control"> </div> <div class="form-group"> <input class="form-control" id="compose-subject" placeholder="Subject"> </div> <textarea class="form-control" id="compose-body" placeholder="Body"></textarea> <input type="submit" value="Send" class="btn btn-primary"/> </form> </div> The email model: class Email(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="emails") sender = models.ForeignKey("User", on_delete=models.PROTECT, related_name="emails_sent") recipients = models.ManyToManyField("User", related_name="emails_received") subject = models.CharField(max_length=255) body = models.TextField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) archived = models.BooleanField(default=False) def serialize(self): return { "id": self.id, "sender": self.sender.email, "recipients": [user.email for user in self.recipients.all()], "subject": self.subject, "body": self.body, "timestamp": self.timestamp.strftime("%m/%d/%Y, %H:%M:%S"), "read": self.read, "archived": self.archived } The JavaScript functions document.addEventListener('DOMContentLoaded', function() { document.querySelector('#compose').addEventListener('click', compose_email); document.querySelector('#compose-form').addEventListener('click', sendEmail); }); function compose_email() { // … -
How to pass additional data to serializer?
I need to add 2 variables in serializer for for calculations in logic serializer serializer = MoviesTopFrameSerializator(topMovie) How can i do this ? and how to handle inside of serializer -
how to access django server only with flutter app?
While I'm using Django as my backend and flutter as my front end. I want only the flutter app to access the data from django server. Is there any way to do this thing? -
Django Error: NoReverseMatch at / Reverse for 'like-post' not found
I'm developing a simple blog with Django. I tried adding ajax functionality to my like button. But got this error: Reverse for 'like-post' with arguments '('',)' not found. 1 pattern(s) tried: ['like/(?P[0-9]+)$'] PS: I followed this video to create a like button and this video add ajax functionality views.py class PostDetailView(FormMixin, DetailView): model = Post form_class = CommentForm def get_success_url(self): return reverse('post-detail', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) postid = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = postid.total_likes() context['form'] = CommentForm(initial={'post': self.object}) context['total_likes'] = total_likes return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.save() return super(PostDetailView, self).form_valid(form) def LikeView(request, pk): post = Post.objects.get(id=pk) #post = get_object_or_404(Post, id=request.POST.get('post-id')) post.likes.add(request.user) context = { 'post': post, 'total_likes': post.total_likes, } if request.is_ajax(): html = render_to_string('blogsite/like_section.html', context, request=request) return JsonResponse({'form': html}) return HttpResponseRedirect(reverse('blogsite-home')) urls.py urlpatterns = [ path('', PostListView.as_view(), name='blogsite-home'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('like/<int:pk>', LikeView, name='like-post'), ] base.html <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click', '#like', function(event){ event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: '{% url "like-post" post.pk %}', data: {'id':pk, 'csrfmiddlewaretoken':'{{ csrf_token }}'}, dataType: 'json', success: function(response){ $('#like-section').html(response['form']) console.log($('#like-section').html(response['form'])); … -
Django form logs out user
Today i have this issue: I wrote a Sign-in Sing-out web application with the Django framework. When a user is logged in, he is redirected to the index page. There he can see "posts" by other users and has the option to like a "post". When the like button is clicked, the user gets logged out and the like view is not accessed at all. Can some one tell me why is that? I will provide some code below. If it's not enough here is my projects github: https://github.com/palm-octo-chainsaw/the-end main url.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls', namespace='core')), path('accounts/', include('accounts.urls', namespace='accounts_app')), path('djrichtextfield/', include('djrichtextfield.urls')), ] core.views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate, login from core.models import Core from django.contrib.auth.models import User def home(req): ctx = { 'posts': Core.objects.all(), } return render(req, 'pages/index.html', ctx) @login_required(login_url='accounts_app:login') def likes(req): if req.method == 'POST': if req.user: return redirect('core:home') def create(req): pass core.urls.py from django.urls import path, include from core.views import home, likes, create app_name = 'core' urlpatterns = [ path('', home, name='home'), path('like/', likes, name='like'), path('create/', create, name='create') ] accounts.views.py from django.shortcuts import render, redirect from django.contrib.auth.models import … -
How to reinstantiate the ckeditor form with existing data to edit a note in django?
Hi all, i want to edit my note which was written using django ckeditor. I have no idea how we can do it. Please help me. -
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