Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Text after space character cut off in password text field using django
I tried to get the password field using the POST method in Django views. It showing the first halfword after space word it can't be shown. I will search for why it's happening. So the number of persons told the problem is in HTML page quotes are not properly used. but I will check my code all quotes are properly used. but I could not get the full text. how to solve this issue. Html Page <div class="form-control"> <input type="password" name="passwd1" value="{{ selected.passwd1 }}" class="input-lg" placeholder="Password" /> </div> <div class="form-control"> <input type="password" name="passwd2" value="{{ selected.passwd2 }}" class="input-lg" placeholder="Confirm Password" /> </div> How to solve this Issue. -
How to use Python FFmpeg Video Stream with Django?
I try to use Python FFmpeg Video Streamin like this web. I create function like this in views.py . def movie(request): video = ffmpeg_streaming.input('/static/media/images/Introduction.mp4') _360p = Representation(Size(640, 360), Bitrate(276 * 1024, 128 * 1024)) _480p = Representation(Size(854, 480), Bitrate(750 * 1024, 192 * 1024)) _720p = Representation(Size(1280, 720), Bitrate(2048 * 1024, 320 * 1024)) hls = video.hls(Formats.h264()) hls.representations(_360p, _480p, _720p) video_out = hls.output('/static/media/images/Introduction.m3u8') return render(request, 'index.html', {'movie':video_out}) When I run server it's show error like this. FileNotFoundError at / [WinError 2] The system cannot find the file specified Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.3 Exception Type: FileNotFoundError Exception Value: [WinError 2] The system cannot find the file specified Exception Location: C:\ProgramData\Anaconda3\lib\subprocess.py, line 1307, in _execute_child Python Executable: C:\ProgramData\Anaconda3\python.exe Python Version: 3.8.3 Python Path: ['c:\\DjangoMax\\maxmodify', 'C:\\ProgramData\\Anaconda3\\python38.zip', 'C:\\ProgramData\\Anaconda3\\DLLs', 'C:\\ProgramData\\Anaconda3\\lib', 'C:\\ProgramData\\Anaconda3', 'C:\\ProgramData\\Anaconda3\\lib\\site-packages', 'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\win32', 'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\Pythonwin'] I have the problem at line video_out = hls.output('/static/media/images/Introduction.m3u8') It's not show error when I comment this line. How to use Python FFmpeg Video Stream with Django? -
Remove a queued task if the related object does not exist
I am trying to delete a queued task (using Celery) which is triggered when an object is created. If, the task is to be triggered 2 min before an event and the object is deleted already, the queued messages remain. task.py @app.task def send_notification(): # do some stuff # return something models.py class ABC(models.Model): description = models.TextField() views.py def abc(request): # create the ABC object send_after=timezone.now() + timedelta(minutes=5) send_notification.apply_async(eta=send_after) # return something So, when the object ABC is deleted right after creating one, the related queued message should also be deleted. Any idea on how to handle this ? -
Possible to delete an object's specific row in django?
I have model that creates several different rows. Like this... class Myteam(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) QB = models.CharField(max_length=80, null=True) RB1 = models.CharField(max_length=80, null=True) WR = models.CharField(max_length=80, null=True) TE = models.CharField(max_length=80, null=True) D = models.CharField(max_length=80, null=True) K = models.CharField(max_length=80, null=True) In my template, I'm looping through the rows and displaying them as html table rows. I've added a delete function to each row because I'd like the app's user to be able delete a player from their "Myteam" object. Problem is, I can only delete the entire object because there's only one id which is for the entire object. The template looks like this right now. Here's two rows as an example. <tbody> {% for t in team %} <tr> <td id="" > {{ t.QB }} <a href="{% url 'delete_player' t.id %}">Delete</a> </td> <tr> <td> {{ t.RB1 }} <a href="{% url 'delete_player' t.id %}">Delete</a> </td> </tr> <tr> I did come across one possible solution here which suggested using {{ forloop.counter }} to assign individual id's to the row, but I can't get this to work how I would like. Just in case, here's the views.py def delete_player(request, id): player = Myteam.objects.get(id=id) player.delete() return redirect('show') I feel like there's probably … -
Retrieving UUIDs in Django
I wrote a model that has a UUID generated as the primary key. When a POST request is made to add an entry to the table, the fields that are sent in the request are all the fields except for the uuid. Once I have added the new entry to the table, how can I retrieve its generated UUID? -
Django - Crispy Forms Layout Not Working as Expected
I'm aiming to add a '$' onto an input box of a form. Below is the form: class StgAccrualForm(ModelForm): class Meta: model = Stg_Monthly_Accrual exclude = ['stg_location_param', 'date_of_service'] localized_fields = '__all__' def __init__(self, *args, **kwargs): super(StgAccrualForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.helper.layout = Layout( PrependedText('rev_amount', '$')) I'm rending the rev_amount field of Stg_Monthly_Accrual as {{ rev_amount | as_crispy_field }}; however, the input box for rev_amount does not have a '$'. I'm bringing in the appropriate tags {% load crispy_forms_tags %} as well. What am I missing? Is it that layout does not work with as_crispy_field and only {% crispy form %}? -
How to use IN query in Django ORM?
How do I run the Where IN query in Django ORM and iterate it? The following returns nothing: user_ids = Wallet.objects.filter(customer_id=[sender_id,reciever_id]) print(user_ids) -
How to periodically change the order of two elements in each row of a div
In one of the HTML files of my Django project, I have a div that contains a col-6 for an image and a col-6 for a text. {% if automotives %} {% for automotive in automotives %} <div class="row"> <div class="col-6 mb-4 mb-md-0 my-5 pl-5"> <h3 class="font-weight-bold">{{ automotive.title }}</h3> <p class="text-muted">{{ automotive.description|safe }}</p> </div> <div class="col-6 mb-4 mb-md-0 my-5 pr-5"> <div class=" overlay z-depth-1-half"> <img src="{{ automotive.cover.url }}" class="img-fluid" alt="cover"> </div> </div> </div> {% endfor %} {% endif %} I read title and description and cover from the database. I want to periodically change the order of image and text in each row. I have no idea how to do it. and I don't know much about js or jquery. any help is appreciated. -
How can i use order_by for persian list in django?
There is list of name ['هاشمی','آذری','واحدی'] ,i want to sort this list that is out put of drf in django .but order_by in django works for arabic language do not work for persian language. for example in persian language after sort it must be ['آذری','واحدی','هاشمی'] ... but it has problem and after sort it is ['آذری','هاشمی','واحدی']. -
I want the data of table row, the table whose checkbox is checked. My table row is in for loop
I want the data of table row, the table row whose checkbox is checked. My table row is in for loop.I want anyone to come and check the checkbox and submit the form and store the complete data of that table row in the database.i tried with ajax but i think may be it can be done by django-template. here is my index.html : <form name="form" method="POST" id="form"> {% csrf_token %} <table class="table table-bordered table-responsive" id="flip-scroll"> <thead> <tr> <th scope="col">Visa Option</th> <th scope="col">Processing Type</th> <th scope="col">No. Of Visa</th> <th height="60" scope="col">Travel Date</th> <th scope="col">Price</th> </tr> </thead> <tbody> {% for j in package %} <tr class="valid-container" data-id="{{ j.id }}"> <td style="cursor:pointer;" width="200"><input type="checkbox" name="c1">&nbsp; <output class="visa_type" style="font-size:14.5px !important;">{{ j.visa_type }}</output></td> <td height="52" width="158"> <select class="custom-select processing_type" name="processing_type" required> <option value="{{ j.price }}" selected>Normal</option> <option value="{{ j.express_price }}">Express</option> </select> </td> <td height="52"> <select class="custom-select no_of_person" name="no_of_person" required> <option value="1" selected>1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> </select> </td> <td width="190" height="60"> <div class="input-group date" data-date-format="dd.mm.yyyy"> <div class="input-group mb-2"> <input type="text" class="form-control travel_date" name="travel_date" value="dd.mm.yyyy" placeholder="dd.mm.yyyy"> <div class="input-group-text"><i class="ti-calendar"></i></div> <div class="input-group-addon"> </div> <div class="input-group-prepend"> </div> </div> </div> </td> <td width="166">{{ j.currency_type … -
Can Django do a flexible `JOIN TABLE` like SQL Alchemy?
According to my current understanding, Django can not do a left join table as flexible and easy as SQLalchemy. For example we have these two table: Table: Transport_Rules Type Origin_id Destination_id Cross country 4 1 Cross state 4 5 Table: Mapping_Country Name ID New York 4 California 5 Paris 1 Target: Finding the type in the table Transport_Rules with inputs are destination_name and origin_name. Provided: ori_name = New York dest_name = California How I did it in SQL Alchemy: map1 = aliased(Mapping_Country, name='map1') map2 = aliased(Mapping_Country, name='map2') rule = Session.query( Transport_Rules.type, Transport_Rules.origin_id, Transport_Rules.destination_id ).join( map1, Transport_Rules.origin_id == map1.ID ).join( map2, Transport_Rules.destination_id == map2.ID ).filter( and_( map1.Name==ori_name, map2.Name==dest_name ) ).all() How I did it in Django: provided no assign foreign key in setting up model since I have not understood the logic of it yet. origin_id = Mapping_Country.objects.filter(name = ori_name).values('ID')[0]['ID'] destination_id = Mapping_Country.objects.filter(name = dest_name).values('ID')[0]['ID'] rule = Transport_Rules.objects.filter(Origin_id = origin_id, Destination_id = destination_id ).values() Even through, visually, Django may looks shorter but if we have multiple joins. Doing it would be very annoying. Main Question: Can Django do left join making connection like SQL query. Is the only solution to define foregin key in models setting ? -
Add verify field with each field in dhango model
I am creating a table for user detail. After user registration, Admin verify every detail with documents uploaded by user. Like Name, Surname with Passport. class User(AbstractUser): name = models.CharField(max_length=30) surname = models.CharField(max_length=30) I am trying this. add a json field verified_fields ({'fields': ['verified', 'fields', 'name']}) in model. I will add fields in value of "fields" which has been verified. But I think I may have problems using this data in templates. Is there any better method to do this. User also have multiple status. I have to save time when user's status changes. like user activated on 12, became employee on 20, became something else on 30. I am thinking another table to save these changes. table with fields user, new_status(that has been changed to) and date. If anyone have better idea, please suggest. -
How to raise or return 405 method not allowed in Django
I want to raise or return a 405 Method not allowed but I cannot find how. Like in Flask you could do abort(405). Is there anyway to raise or return a Django 405 exception. -
django_admin - command not found
Followed the installation steps but I'm getting an error zsh: command not found: django-admin I can see django and django-admin.py present under /Users/simd/Library/Python/2.7/lib/python/site-packages/bin but for some reason not able to access it. I've even tried chmod command suggested in the Django documenation, but no luck. I'd be really grateful if someone can help me out, Thanks! I'm using MacOS Catalina -
drf authtoken Unable to log in with provided credentials
i'm using token authentication with customuser and also have customemail backend. i also tried to use custome token serializer because its using email for auth. it seems to be working with user created by admin but user created by rest api not able to login showing this error. loginview: @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def login(request): serializer = AuthCustomTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=status.HTTP_200_OK) serializer.py: class AuthCustomTokenSerializer(serializers.Serializer): ''' Changing Token auth to use email instead username ''' email = serializers.EmailField(label=_("Email")) password = serializers.CharField( label=_("Password",), style={'input_type': 'password'}, trim_whitespace=False ) def validate(self, attrs): email = attrs.get('email') password = attrs.get('password') print(email, password) if email and password: user = authenticate(username=email, password=password) print("this is user", user) # The authenticate call simply returns None for is_active=False # users. (Assuming the default ModelBackend authentication # backend.) if not user: msg = _('Unable to log in with provided credentials.') raise serializers.ValidationError(msg, code='authorization') else: msg = _('Must include "username" and "password".') raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user return attrs class CustomUserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=False) class Meta: model = CustomUser fields = ('id', 'first_name', 'last_name', 'email', 'mobile_number', 'password', 'is_active', 'user_type', 'otp') def create(self, validated_data): user = CustomUser( email=validated_data['email'], mobile_number=validated_data['mobile_number'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], user_type=validated_data['user_type'], ) user.set_password(validated_data['password']) … -
Send date to Template of django
in my project, user after register can complete his information in another form. after completed this form and submitted it every time he visits this page, he sees the completed form. but i have a problem in this form, calender of user's birthday field works well at the first time when field is empty, but after the form is completed and submitting when the user wants to change it the calendar looks like this: models.py: from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): ED_CHOICES = [ ('hs', 'High school'), ('bc', 'Bachelor'), ('ms', 'Master'), ('do', 'Doctor'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(max_length=13) birthday = models.DateField() education = models.CharField(max_length=20, choices=ED_CHOICES) gender = models.CharField(max_length=15) forms.py: class ProfileForm(forms.ModelForm): ED_CHOICES = [ ('hs', 'High school'), ('bc', 'Bachelor'), ('ms', 'Master'), ('do', 'Doctor'), ] phone = forms.CharField( widget=forms.TextInput(attrs={'class': 'input--style-4'}), label='' ) birthday = forms.DateField( widget=forms.DateInput(attrs={'class': 'input--style-4 js-datepicker'}), label='' ) education = forms.CharField( widget=forms.Select(choices=ED_CHOICES, attrs={'class': 'select-dropdown'}), label='' ) gender = forms.CharField( widget=forms.TextInput(attrs={'class': 'radio-container m-r-45'}), label='' ) class Meta: model = models.UserProfile fields = ['phone', 'birthday', 'education', 'gender'] views.py: from django.shortcuts import render, redirect from . import forms, models from django.contrib.auth import get_user_model my_user = get_user_model() my_profile = models.UserProfile first = True def profile(request, slug): … -
One Form for Two Models in Django and get thread ID after it's created
Okay, so I'm creating a function that creates a new thread for a forum software. I pass in the category that the new thread is going into, through the URL. Currently, for the new thread, I have title, body, author which are passed through a hidden input, and the category which is also passed in through hidden input. Now what I want to do is, whenever I create the thread, I want the same details to be posted into a different model. So the Thread model has name (title), body (content), author, and forum_id. The Post model which I want it to go into has post_body (content), (author), and post_thread. Now the important part is post_thread is the current thread that we are about to create that we haven't created yet. How can I get the ID of this thread AFTER it's created and then pass into that Post model? Basically, when you create a new thread, it creates the first post in that thread and attaches itself to it. I know this is kinda confusing but anybody who has experience with forum software should have an easier time getting what I'm trying to do here. Models.py class Thread(models.Model): name … -
django count rows by column
I have a model like this class tbl_invoice(models.Model): invoice_id = models.IntegerField(blank=True, null=True) client_id = models.ForeignKey(tbl_customer, on_delete=models.CASCADE) invoice_number = models.IntegerField(blank=True, null=True) date = models.DateField(blank=True, null=True) total_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) total_tax = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) discount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) paid_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) balance = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) a client can obviously have multiple invoices and I want to show all the invoices according to clients in a table like Customer Total Invoices Total Amount Total Tax Client1 10 50000 200 Client2 8 10000 500 I tried this tbl_invoice.objects.values('client_id').order_by().annotate(Count('client_id')) but this gives <QuerySet [{'client_id': 19, 'client_id__count': 5}, {'client_id': 21, 'client_id__count': 10}, {'client_id': 24, 'client_id__count': 15}]> this does give the count of rows but how can I get other data?? sorry if this is a duplicate, but I just can't figure out this simple query. -
How to execute redis-server.exe in Heroku?
I'm following this tutorial and faced the problem how to execute redis-server.exe in heroku. https://www.youtube.com/watch?v=Wv5jlmJs2sU&list=PLLRM7ROnmA9EnQmnfTgUzCfzbbnc-oEbZ&index=1 Procfile web: gunicorn mysite.wsgi --log-file - Should I add something on setting.py or Procfile? I am a newbie btw. any suggestion and advice is welcome! thank you! -
create directory function is not working in django production server
create directory function not working in django production server (using nginx ) and also not show any error in nginx logs but when we run django prebuild server manually (python3 manage.py runserver 0.0.0.0:8000) then all functions work properly. if request.method == 'POST': prefix = request.POST.get('prefix', '') log_usr = request.user subprocess.call('mkdir -p '+'/home/django/usr/'+str(log_usr)+'/'+str(prefix), shell=True) I am using above code for create directory -
Django modelling a rules based engine
Hi I am building a calculator and a rules engine. I am struggling how to model this table in the database. where it will be easier if parameters change to be adjusted in the django admin rather than redeploy code The lower and upper are income based and depending if they have children (dependents) you can add to the expenses if > 2 and then you add a fixed amount (Single add dep) and (couple add dep) for each child above 2. If someone can assist it would be greatly appreciated -
Trouble getting Salesforce login working with dj-rest-auth + django-allauth
My app has a Django 3.1 backend with django-allauth and dj-rest-auth (actively supported fork of django-rest-auth). My mobile and web frontends can already sign in using Facebook and Google via REST. I'm now trying to add Salesforce as a 3rd REST social login method, but am running into issues. I've followed the django-allauth instructions for Salesforce: Created a Salesforce Connected App with id and openid scopes (along with some others), and set the callback URL to https://www.mywebdomain.com/accounts/salesforce/login/callback/ Created a SocialApplication in Django with client ID, secret, and login URL in the "Key" field (https://login.salesforce.com/) Included allauth.socialaccount.providers.salesforce in INSTALLED_APPS I've been using client-side JSforce to kick off the Salesforce auth request in the frontend, but I'm open to other methods if they are simpler/better/etc. Running jsforce.browser.login() in my clients' JS code opens a Salesforce login popup. After entering Salesforce login credentials, the Salesforce system redirected to my defined callback URL, resulting in a page that shows the following text: Social Network Login Failure An error occurred while attempting to login via your social network account. The URL in the address bar on that page looks something like this: https://www.mywebdomain.com/accounts/salesforce/login/callback/#access_token=00D3t000004QWRm%21ARwAQPfHWiM6jdB43dlyW6qjEw._34mjzGi_Jv6YCXp0QssT.9F9lCge5_YaH8gqTy3Od6SywCs8X9zOGv145SyviBVeGdn0&instance_url=https%3A%2F%2Fna123.salesforce.com&id=https%3A%2F%2Flogin.salesforce.com%2Fid%2F00D3t000004QWRmEAO%2F0053t000008QBetAAG&issued_at=1606802917608&signature=KvxAX0WBCFQYY%2BO25id9%2FXxpbh2q2d2vWdQ%2FFV5FCBw%3D&state=jsforce0.popup.c0ockgct29g&scope=id+api+web+refresh_token+openid&token_type=Bearer I tried to debug and print the error in my backend, but … -
Changing the inner Element of HTML using Javascript to present Django For Loop
I am currently in the process of the basics of Javascript and I know Django. So I am trying to use javascript to show elements in HTML for a Django For Loop. The purpose of doing this is that I understood that presenting data using Javascript doesn't require the page to be refreshed, so I decided to give it a try. To explain more my question here is an example of what I did. I have a list of name of users who likes a posts and there are presented in the following format in the template: <div class="dropdown-menu" aria-labelledby="dropdownMenuLink"> {% for user in post_likes %} <span class="dropdown-item" >{{ user.username }}</span> {% endfor %} So I added an id to the span and added the following script related to javascript: <div class="dropdown-menu" aria-labelledby="dropdownMenuLink"> {% for user in post_likes %} <span id="id01" class="dropdown-item" >{{ user.username }}</span> {% endfor %} </div> <script> var element = document.getElementById("id01"); element.innerHTML = "{{ user.username }}"; </script> When a new user likes the post his name should appear directly in this loop without the page refreshing but it is not happening and the name of the logged-in user is the one and appearing. I am not sure … -
Django Comment on Blog System
So I am trying to build up comment system in my instagram-like app. My main problem is that i can't get access to comment(s) of each post in my PostListView which inherits from ListView of Django Model of Comment: class Comment(models.Model): post = models.ForeignKey(Post, on_delete = models.CASCADE, related_name ='comments') user = models.ForeignKey(User, on_delete = models.CASCADE) content = models.TextField() View of PostList: class PostListView(LoginRequiredMixin,ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-created_on'] urls.py path('',PostListView.as_view(), name='blog-home'), all the imports have been coded properly. The problem is that within my PostListView I also want to display comment(s) of each post. Pretty much like instagram where we can find posts and comments in the same page(we should not necessarily click on post and go to detail of a particular post) -
TypeError: 'QuerySet' object does not support item assignment when creating an object in Django
I get a " TypeError: 'QuerySet' object does not support item assignment " error message when trying to create an object in Django. Here is my code: for ing in ingredient_list: print(ing['name']) target = Ingredient.objects.filter(name=ing['name'], brand=ing['brand'],price=ing['price'],igd_type=ing['igd_type']) # If there are no ingredient, create ingredient. if len(target) == 0: temp = 0 print(ing['quantity']) tempPicture = "carrot.png" price = ing['price_normalized'] if ing['price_normalized'] != 0 else ing['price'] normPrice = 0 if (ing['price_normalized'] or ing['quantity']==0) else ing['price']/ing['quantity'] quantity = float(ing['quantity']) target[0] = Ingredient.objects.create(name=ing['name'], brand=ing['brand'], price=price, igd_type=ing['igd_type'], quantity=quantity, price_normalized=normPrice, picture=tempPicture ) target[0].save() print(target[0]) I get the error at picture. Why can't I assign?? I would really appreciate the help!