Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python calling a function that creates directory does not work as expected
I am calling a function inside my Django view. The code works but not when calling the function inside the view. I have simplified the code. import os def MakeDir(path): try: os.mkdir(path) #... some more logic... except OSError as e: print(e) def MydjView(request): MakeDir('/tmp/year') #function call but directory is not created return HttpResponse('okay') -
Django: UpdateView for Double Nested Forms
I currently have an error with writing UpdateView for double nested forms. My architecture is comprised of one template containing one form and two formsets. There's a large form for publisher. Someone can then add as many author formsets as they want and as many book formsets to each author as they want. So it looks like: Publisher -> Author1, Author2, Author3, ... Author1 -> Book1, Book2, Book3 Author2 -> Book4 Author3 -> Book5, Book6 Again, this is all listed in one create.html template. I wrote this using CreateView and it works fine. Now with writing UpdateView, I redirect to my html template for the creation of the forms and can correctly populate the form with data for publisher and author. However, when I try to populate the form with the book data, it populates every author instance with the same book instances rather than populate each author instance with their matching book instances. So it looks like: Publisher -> Author1, Author2, Author3, ... Author1 -> Book1, Book2, Book3 Author2 -> Book1, Book2, Book3 Author3 -> Book1, Book2, Book3 My models.py looks like : class Publisher(models.Model): name = models.CharField(max_length=255, unique=True) class Author(models.Model): name = models.CharField(max_length=255, unique=True) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) … -
The session is idle and there is no current transaction pgAdmin - Django
I'm really new in Postgres and PgAdmin. I'm trying to import new attributes in to my database class from Django project. This project is connected to pgAdmin Postgres. The problem is when I make migrations and migrate from django, this news attributes doesn't impact my database in pgAdmin. I see my migrations files in django project and the migration is successful, but when I see pgadmin it shows this message The session is idle and there is no current transaction pgAdmin I have searched in google but there is no so much information, so I really will appreciate your help. -
Django Rest Framework: How to filter only Many2Many data that matches the conditions
I have many related models and serializers and I want to return only the filtered result (including nested content). models.py class Screen(models.Model): title = models.CharField(max_length=100) class Item(models.Model): screen = models.ForeignKey(Screen, related_name='items', on_delete=models.CASCADE) title = models.CharField(max_length=100) class Card(models.Model): item = models.ForeignKey(Item, related_name='cards', on_delete=models.CASCADE) title = models.CharField(max_length=100) settings = models.ManyToManyField('Settings') class Settings(models.Model): sdk = models.IntegerField(default=1) drm = models.BooleanField(default=False) serializers.py class SettingsSerializer(serializers.ModelSerializer): class Meta: model = Settings fields = ['sdk', 'drm'] class CardSerializer(serializers.ModelSerializer): settings = SettingsSerializer(many=True, read_only=True) class Meta: model = Card fields = ['id', 'title', 'settings'] class ItemSerializer(serializers.ModelSerializer): cards = CardSerializer(many=True, read_only=True) class Meta: model = Item fields = ['id', 'title', 'cards'] class ScreenDetailSerializer(serializers.HyperlinkedModelSerializer): items = ItemSerializer(many=True, read_only=True) class Meta: model = Screen fields = ['id', 'title', 'items'] views.py class ScreenDetail(generics.RetrieveAPIView): serializer_class = ScreenDetailSerializer def get_queryset(self): qs = Screen.objects.all() params = {} settings_params = {} cards_params = {'settings__isnull': False} items_params = {'cards__settings__isnull': False} sdk = self.request.query_params.get('sdk', None) if sdk: params['items__cards__settings__sdk'] = sdk settings_params['sdk'] = sdk qs = qs.prefetch_related( Prefetch('items', queryset=Item.objects.filter(**items_params).distinct().prefetch_related( Prefetch('cards', queryset=Card.objects.filter(**cards_params).distinct().prefetch_related( Prefetch('settings', queryset=Settings.objects.filter(**settings_params).distinct()) )) )) ) return qs.filter(**params).distinct() Example of not filtered JSON: { "id": 1, "title": "Фильмы", "items": [ { "id": 1, "title": "Лучшие ужастики", "cards": [ { "id": 1, "title": "Проклятье Анабель", "settings": [ { "sdk": 1, "drm": true … -
Submiting multiple (unrelated) forms django, ajax same view same page
I'm trying to submit more than four forms in the same view and template in Django, each unrelated to the other. the challenge is that only one form is submitting successfully, while nothing happens to the other forms, Is there a way I can effectively solve this problem without having separate views for each form using ajax or? Here is my views.py def course_options(request): option1form = Choice1Form() option2form = Choice2Form() option3form = Choice3Form() educhoiceform = EduchoiceForm() if request.is_ajax(): option1form = Choice1Form(request.POST) option2form = Choice2Form(request.POST) option3form = Choice3Form(request.POST) educhoiceform = EduchoiceForm(request.POST) print(request.POST) if option1form.is_valid(): Choice1 = option1form.save(commit=False) Choice1.user = request.user option1form.save() return JsonResponse({ 'message': 'success' }) if option2form.is_valid(): Choice2 = option2form.save(commit=False) Choice2.user = request.user option2form.save() return JsonResponse({ 'message': 'success' }) if option3form.is_valid(): Choice3 = option3form.save(commit=False) Choice3.user = request.user option3form.save() return JsonResponse({ 'message': 'success' }) if educhoiceform.is_valid(): Educhoice = educhoiceform.save(commit=False) Educhoice.user = request.user educhoiceform.save() return JsonResponse({ 'message': 'success' }) return render(request, 'applyBugema/select.html', {'option1form': option1form, 'option2form': option2form, 'option3form': option3form, 'educhoiceform': educhoiceform}) template.html <div class="card2 card border-0 px-4 py-1" style="background-color: #e9ecef;"> <h2>Select courses you'd like apply for</h2> <hr> </div> <div class="row d-flex"> <div class="card2 card border-0 px-4 py-3" style="background-color: #e9ecef;"> <form method="POST" class="post-form" id="form">{% csrf_token %} {{ option1form|crispy }} <!-- <button type="submit" class="btn btn-outline-info">First … -
How do I render HTML returned from a filter in django template?
I have a md file which needs to be converted into html (for blog website). The filter (markdownify) converts md file into html tags. Now, html tags are shown on the website. How do I render this html on website (in django template). Is there any filter to do so? Or is there any other method to convert md into html in django? Code -> <p>{{ post.body | markdownify }}</p> md file -> ### h1 header *jh* * sdfs * ksdjfh * skdjkfhsk [link] (#) The output in web page: h1 header <em>jh</em> sdfs ksdjfh skdjkfhsk [link] (#) -
Delete records from 2 tables in join with Django ORM
I am using Django and have 2 tables and I want to delete records from the join. These are simplified model definitions: from django.db import models class MyModelA(models.Model): created = models.DateTimeField(null=True, blank=True) class MyModelB(models.Model): modela = models.OneToOneField( MyModelA, on_delete=models.DO_NOTHING, db_constraint=False ) created = models.DateTimeField(null=True, blank=True) If I used SQL, I could write a DELETE statement with a join, which would delete all records that are returned by the join like this: DELETE a, b FROM mymodela AS a INNER JOIN mymodelb AS b ON a.id = b.modela_id WHERE a.created < '<some date>' I would like to use the Django ORM and the delete() method. I could easily write the SELECT equivalent using: MyModelA.objects.filter(mymodelb__isnull=False) .filter(created__lt=<some date>) .select_related("mymodelb") However, when I chain the delete(), only records in MyModelA are deleted and the resulting SQL-query is something like this: DELETE FROM mymodela WHERE mymodela.id IN (<LIST OF IDs in JOIN>) I could of course use a different on_delete action or get the list of ids and delete the records table by table, but I would like to know: is it possible to get a DELETE a, b FROM... statement as shown above? -
How can pass my data into this particular serializer?
I'm currently working with data that looks like: { "events": [] } But, I'd like to transform it to: { "events": "added-to-calendar": [], "confirmed": [] } I've written out a serializer that looks like: class CalendarFeedSerializer(serializers.Serializer): """ Serializer for the Calendar Feed """ added_to_calendar = EventSerializer(many=True, read_only=True) confirmed = EventSerializer(many=True, read_only=True) class Meta: model = Event But, I'm not entirely sure how to pass my data into this Serializer. Here's the ListAPIView that I am working with to achieve { "events": [] }: class CalendarFeedView(generics.ListAPIView): serializer_class = serializers.EventSerializer def get_queryset(self): user = get_user_model().objects.get(id=self.request.user.id) added_to_calendar_events = user.events_in_calendar() confirmed_events = user.events_confirmed() return added_to_calendar_events | confirmed_events But, as you can see, I am using the base EventSerializer that I created to transform this list of Event's. What I want, is to somehow pass added_to_calendar_events and confirmed_events to my CalendarFeedSerializer so that I can have the desired data structure { "events": "added-to-calendar": [], "confirmed": [] } -
Retrieve Data From Database and display in HTML forms through AJAX in django
recently I'm working on blog application using django framework.Right now I dont know how to retrieve data from database through ajax in HTML form.For example if user wants to edit his own post the page will redirected to blog_post page along with his old published post.I want to set that published data to blog_post page.So whenever the user go for edit the post the published post would be already mentioned and user can edit them easily. Here is my code, blog_post.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Clean Blog - Start Bootstrap Theme</title> <!-- Bootstrap core CSS --> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <!-- Custom styles for this template --> <link href="{% static 'css/clean-blog.min.css' %}" rel="stylesheet"> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> </head> <body> <!--- --- Here is my ajax which I had tried ----- --- !> {% for i in blogs %} <script> $(document).ready(function(){ setInterval(function () { $.ajax({ type : "post", url : "{% url 'edit_post' %}", data: { "blogger" : {{ … -
How to update/create new jwt after user changed username
I use JWT(JSON Web Token) in my project(backend: Django), now I allow user to change his/her username. As we known, after user changed username, the token will invalid(since the token(payload) include the username info, so the current local saved token cannot be used further). Then what we can do? Logout? and let user re-login? create new jwt? but how to do this since backend don't have the password(as I know, password is needed to create new jwt). -
How to avoid to resend data and update page in django forms?
I have a modal form which is displayed clicking some buttons. When the user fill the form and submit it i can save the data and redirect the user to and index page. If the user return on the previous page he see the "old" form already filled, because the page isn't refreshed. What can i do? This is my wiew: def calendar(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form = ReservationForm(request.POST) # check whether it's valid: print('prima del form valid') if form.is_valid(): print("il form e' valido") reservation = form.save(commit=False) reservation.validation_code = get_random_string(length=32) reservation.delete_code = get_random_string(length=8).upper() reservation.reservation_confirmed = False reservation.save() return redirect('prenotazionicampo:index') # return render(request, 'prenotazionicampo/index.html') else: print(form.errors) # if a GET (or any other method) we'll create a blank form else: form = ReservationForm() -
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine Please give me a solution
Exception happened during processing of request from ('127.0.0.1', 63281) Traceback (most recent call last): File "c:\users\ramkumar\appdata\local\programs\python\python38-32\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "c:\users\ramkumar\appdata\local\programs\python\python38-32\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "c:\users\ramkumar\appdata\local\programs\python\python38-32\lib\socketserver.py", line 720, in init self.handle() File "D:\customerApplication\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "D:\customerApplication\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "c:\users\ramkumar\appdata\local\programs\python\python38-32\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine -
TypeError in view: Field expected a number but got SimpleLazyObject
I upgraded to django v3.1 and suddenly getting this error: Field 'id' expected a number but got <SimpleLazyObject: '23'>. The failing line of code is this: my_obj = get_object_or_404(MyModel, pk=kwargs.get('pk')) Any ideas what I might be doing wrong? Thanks! -
Django: AJAX request in generic class-based view does not assign class attribute with new value
I am currently creating a page using Django generic class-based view. However, whenever I made AJAX request, the class attribute is not assigned with the sent data/value. Code example: class CourseView(View): object = None # Other attributes and methods # POST method (AJAX url points to the same path) def post(self, request, *args, *kwargs): if request.is_ajax(): print("prev value:",self.object) self.object = self.POST['object'] print("new value:", self.object) return HttpResponseRedirect(success_url) From the code above, suppose that the value sent during the 1st AJAX request is "one", then the output from the console should be as follow (which is correct AT FIRST) prev value: None new value: one However, when I made the 2nd AJAX request with another value, for example "two", the output from the console shows prev value: None #suppose to be one new value: two Since I have assigned the class attribute with value "one" during the 1st AJAX request, shouldn't the attribute be overwrote and display "one" as the previous value, instead of the initial value None during the 2nd AJAX request? Or is there any other ways to do this. -
The database is not accepting the updated field values in django
I an currently learning django and i am just a beginner. I am making a basic social media app. I have programmed it to create a profile for every user that registers. I am also trying to add an edit profile function. But when a user tries to edit his/her profile pic, status or tries to change his/her account to private account nothing is happening i.e. the database is not saving the editted data. pls help me to rectify my mistakes. Thanks. My views.py(variables- private, status, image are not getting saved) def edit_profile(request): user = request.user user_profile = profile.objects.get(user__username=user) Profile = user_profile myuser = User.objects.get(username=user) follow1 = Follow.objects.filter(follow_user=user) follow2 = Follow.objects.filter(user=user) follow_by = follow1.count() follow_to = follow2.count() try: if request.method == 'POST': username = request.POST['username'] name = request.POST['name'] email = request.POST['email'] private = request.POST['private'] status = request.POST['status'] image = request.FILES.get('img') if private == 'on': paccount = True else: paccount = False if User.objects.filter(username=username).exists() and User.objects.get(username=username) != request.user: messages.error(request, 'username is taken') return redirect('edit_profile') elif User.objects.filter(email=email).exists() and myuser.email != email: messages.error(request, 'An account exists with this Email-id') return redirect('edit_profile') else: myuser.username = username myuser.first_name = name myuser.email = email myuser.save() Profile.user = myuser.username Profile.name = myuser.first_name Profile.private = paccount Profile.save() return … -
django .env EmailMessage auth troubles
im trying to secure my credentials while i want to configure email activation sending. So i have to import my .env values in correct place in settings.py while i do it, it tries to auth to another email mentioned in EmailMessage method. But while i leave it hardcoded in settings.py everything works smoth with credentials from settings.py. Why django tries to authenticate to noreply@sendsite.com in EmailMessage method? #settings.py ACCOUNT_UNIQUE_EMAIL = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') PASSWORD_RESET_TIMEOUT_DAYS = 1 ####################################### #part of views.py if form.is_valid(): user = form.save() user.is_active = False user.save() current_site = get_current_site(request) email_body = { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), } link = reverse('activate', kwargs={ 'uidb64': email_body['uid'], 'token': email_body['token']}) email_subject = 'Activate your account' activate_url = 'http://' + current_site.domain + link email = EmailMessage( email_subject, 'Hi ' + user.username + ', Please the link below to activate your account \n' + activate_url, 'noreply@sendsite.com', [user.email], ) email.send(fail_silently=False) ########### #.env EMAIL_HOST_USER=**********@gmail.com EMAIL_HOST_PASSWORD=****** -
Django annotate NumericRange - AttributeError: 'NumericRange' object has no attribute 'resolve_expression'
I have DRF custom filter and I'm struggling with building query for NumericRange. I need to create NumericRange(or other range for integers) with two calculated values and then use that field to filter it using __overlap. def filter_range(queryset, name, value): queryset = queryset.annotate( number_range=ExpressionWrapper( NumericRange(F(f"{name}_base"), F(f"{name}_base") + F(f"{name}_extend")), output_field=NumericRange(), ), ).filter(number_range__overlap=(value.start, value.end)) When I use this filter, I'm getting: 'NumericRange' object has no attribute 'resolve_expression' I think that maybe I'm using the wrong range field or something but I couldn't find anything better. -
How to change in Django Admin the default form (dropdown list) for a foreignKey model?
I want to change in my django administration page the form of a field. In my model I have the 'user' as foreign key to another model. When I create a new 'programare' in the administration page the default form-field for user it's a dropdown with all entries of 'Cont' model. It's dizzy to search the right one, so I want to change that dropdown with a plain-text input or an autocomplete form. class Programare(models.Model): user = models.ForeignKey(to=Cont, on_delete=models.CASCADE, related_name='programari') ... -
django3.1 error "TypeError: expected str, bytes or os.PathLike object, not NoneType"
welcome I have problem in django 3.1 : TypeError: expected str, bytes or os.PathLike object, not NoneType [27/Aug/2020 14:56:53] "GET /static/js/scripts.js HTTP/1.1" 500 83625 -
Django test set created_at field
I have following model in Django (models.py) from django.db import models # Create your models here. class Session(models.Model): session_token = models.TextField(default="") code = models.CharField(max_length= 5, default="") active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Now, I have following function to be tested. def get_active_session_older_than_hours(older_than_hours): older_date_time = datetime.datetime.now() - datetime.timedelta(hours=older_than_hours) data = Session.objects\ .filter(active=True, updated_at__lte=older_date_time)\ .values_list('code') return data I want to test it. from django.test import TestCase #Working fine class ActiveSessionsNotPreset(TestCase): def test(self): data = get_active_session_older_than_hours(3) self.assertEqual(len(data), 0) #This is not working. #It is not getting the result. class ActiveSessionPresent(TestCase): def setUp(self): older_date_time = datetime.datetime.now() - datetime.timedelta(hours=4) Session.objects.create(session_token='', code='US', active=True, created_at=older_date_time, updated_at=older_date_time) def test(self): data = get_active_session_older_than_hours(3) print("DEVENDER data " + str(data)) self.assertEqual(len(data), 1) In the second test case, I am not getting any result. What is the correct way to force created_at and updated_at? -
Django singe models show in html
I want to show only body_text, how do I do that? I do not want to use for loop because it adds text to all . For example when I add body1 in Text-1 and then text-2 I want a new one to appear and delete text-1. this is my code . This is models.py # Create your models here. class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField() def __str__(self): return self.name class Entry(models.Model): blog = models.ForeignKey(Blog,on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() authors = models.ManyToManyField(Author) rating = models.IntegerField() def __str__(self): return self.headline and this is html ```<h2>{{posts.body_text}</h2>``` this is views.py template = 'aries.html' forms = Entry() posts = Author.objects.all() args = {'forms':forms,'posts':posts} return render(request,'Zodiac/aries.html',args)``` -
In Django is it possible to obfuscate or hide client IP from logging on certain pages?
We have a need to allow a user of our internal Django site to send an anonymous email via a contact form to an internal email box. I have all of the framework in place and the messages arrive and are not obviously traceable. However, the Django logs do record the IP address along with a timestamp of all requests. I am curious if it would be possible to some how hide or perhaps proxy the client IP when the form is submitted to help protect their anonymity? I have found many articles on how to get the client IP but my searches have not hit upon anything that does the reverse. I could perhaps alter the Django Logging format to exclude the client IP but it would be good to leave it on for the rest of the site for debugging etc. thank you in advance. -
Best approach to handle large files on django website
Good morning all. I have a generic question about the best approach to handle large files with Django. I created a python project where the user is able to read a binary file (usually the size is between 30-100MB). Once the file is read, the program processes the file and shows relevant metrics to the user. Basically it outputs the max, min, average, std of the data. At the moment, you can only run this project from the cmd line. I'm trying to create a user interface so that anyone can use it. I decided to create a webpage using django. The page is very simple. The user uploads files, he then selects which file he wants to process and it shows the metrics to the user. Working on my local machine I was able to implement it. I upload the files (it saves on the user's laptop and then it processes it). I then created an S3 account, and now the files are all uploaded to S3. The problem that I'm having is that when I try to get the file (I'm using smart_open (https://pypi.org/project/smart-open/)) it is really slow to read the file (for a 30MB file it's taking … -
Facing problem with database models after deploying to heroku
Need Help From Django Developer... Project is deployed on heroku But i was facing problem in data mapping through postgresql to server side(heroku). The data is not being displayed on the html page which is stored in postgresql database. And if you know anything please leave a message for sure... Thankyouenter image description here -
RelatedObjectDoesNotExist at / User has no customer
when I try to create a new user and when I log in using that user it show that error it automatically doesn't create that user as a customer and shows that error views.py from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.http import JsonResponse import json import datetime from .models import * from .utils import cookiesCart, cartData, guestOrder def store(request): data = cartData(request) cartItems = data['cartItems'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'store/store.html', context) def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'store/cart.html', context) # @login_required def checkout(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'store/checkout.html', context) def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('Product:', productId) customer = request.user.customer(user=request.uses) product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif action == 'remove': orderItem.quantity = (orderItem.quantity - 1) orderItem.save() if orderItem.quantity <= 0: orderItem.delete() return JsonResponse('Item was added', safe=False) def processOrder(request): transaction_id = datetime.datetime.now().timestamp() …