Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Revealing form fields after checkbox is checked django
Im trying to create a form in which, when a user checks the box, the form shows more values to input. For example, I have the following class ExampleForm(forms.Form): example_name = forms.charField(label='Name here') custom_message_check = forms.booleanField(required=False, initial=False) custom_message = forms.charField(label='Custom message here') Is it there a way to make custom_message field appear only when custom_message_check is activate? I read django docs and didnt find a widget for this, can this be done with django or do I need to create a custom html form? -
How to clear ordering when using .first() in django
I have a query in database as follows. Whenever I try to do a .first() on the query, The equivalent query that gets run in the database is as follows SELECT * FROM “user" WHERE UPPER("user"."email"::text) = UPPER(%s) ORDER BY "registration_user"."id" ASC LIMIT 1 I want to get rid of the order by clause as it interferes with indexes being applied correctly in the db and is also a costly operation. How can I refactor the code below? users = User.objects.filter(email__iexact=email) users.query.**clear_ordering**(True) if users.count() > 0 : return users.first() -
I want to upload multiple files using Django
I want to upload multiple files or a folder in form , The html form uploads the multiple files successfully but when it comes to django handling it is showing me night-mares in day light . I have created my html form like this <input type="file" name="file" multiple /> I have created a model like this File=models.FileField(upload_to="documents/") And views.py like this file=request.FILES.get('file') I pass the file into the model i have created but only the last file gets inserted and shown in Admin Panel Now I get only last file (if I select 3 files then get 3rd file). How to get all files or folder ? And even want to show in Django Admin Panel -
Deploy Django App serverless on GCP cloud functions
I have come across serverless deployment of Django apps on AWS Lambda. Here is one such example source: Is a similar thing possible using GCP cloud functions? -
Temporary database model in django
I want this Temporary models in django to be implimented in django 3.0. -
Django error, CSRF Failed: CSRF token missing or incorrect
I have Backend = Django+Django Rest+Djoser(Token based user auth app) Fontend = React JS + Axios. In Local Host/Development I could do user login and authentication using token. It did'nt give error in Postman too. In production mode It gives error as CSRF failed. Why is so ? I think CSRF token only needed in session authentication. I tried removing session auth but resulted in server crash REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), .... } middlewares MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] installed apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'shop', 'corsheaders', 'frontend', 'djoser', 'rest_framework.authtoken', 'users' ] -
no module name fcntl in windows and niether downloading
Traceback (most recent call last): File "c:\programdata\anaconda3\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\programdata\anaconda3\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\ProgramData\Anaconda3\Scripts\gunicorn.exe\__main__.py", line 4, in <module> File "c:\programdata\anaconda3\lib\site-packages\gunicorn\app\wsgiapp.py", line 9, in <module> from gunicorn.app.base import Application File "c:\programdata\anaconda3\lib\site-packages\gunicorn\app\base.py", line 11, in <module> from gunicorn import util File "c:\programdata\anaconda3\lib\site-packages\gunicorn\util.py", line 9, in <module> import fcntl ModuleNotFoundError: No module named 'fcntl' -
I Want To Make Website Like Youtube Which python Framework is Best For Back-end Flask Or Django [closed]
Help Me to Choose Modern And Best Frameworks -
Setting a directory path in django (windows)
Hello guys I don't have much experience with django or python, I have to provide path for ffmpeg in django settings, I am currently working in windows 10, how do I specify the path in django settings. like FFMPEG_PATH == ? My file is located at c:\ffmpeg\bin.. is there a way to mention the path in django way? Thanks -
How to resolve the django migration conflict?
There was a situation when a message appeared on the server CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0063_auto_20200530_1040, 0062_merge_20200527_1444 in vendors). To fix them run 'python manage.py makemigrations --merge' I followed the command, but now a new migration file has appeared during the execution Created new merge migration /home/ubuntu/spend-matters/apps/vendors/migrations/0064_merge_20200601_0807.py But the local machine and github don't have this file, so every time I pull a new code from github to the server, there will be a problem with the difference in migrate. How do I fix this correctly? -
Object received a naive datetime (...) while time zone support is active
I've been looking for an answer for this with no luck. I'm creating and object that has an attribute called "accessdate" When I create the object I receive the next warning RuntimeWarning: DateTimeField Consumption.addedtime received a naive datetime (2020-06-01 13:07:47.222534) while time zone support is active The thing is that what the object is reciving is NOT a naive datetime because it has the tzinfo filled with "Europe/Madrid" timezone. These are the relevant imports I'm using: import datetime from django.utils.timezone import make_aware This is how I create my datetime variable: date_object = datetime.datetime.strptime(data_from_request['FECHA ACTIVACION'], '%d/%m/%Y') # data_from_request['FECHA ACTIVACION'] = '01/01/2020' access_date = make_aware(date_object) And this is how I create the object consumption = Consumption.objects.create( client=client, rule=rule, course=course, provider=provider, usercode=data_from_request['CODIGO USUARIO'], username=data_from_request['NOMBRE USUARIO'], accessdate=access_date, billable=data_from_request['FACTURABLE'], status=data_from_request['VALIDADO'] ) How is this possible? I'm debugging my code and when I check for the "access_date" variable content I can see the tzinfo filled Why am I still getting this warning? Thank you guys ! -
How can I check my Instance username with all username in database to filter
forms.py class ChangeProfile(UserChangeForm): class Meta: model = User fields = ['username' ] In the below code i Want to filter butits not getting filter as I want to show a exception message of username taken.Please help me out class EditProfile(View): def get(self,request): form = forms.ChangeProfile return render(request,'editProfile.html',{'form': form }) def post(self,request): form = forms.ChangeProfile(request.POST , instance = request.user) if form.is_valid(): if User.objects.filter(username = username).exists(): messages.info(request,'Username Taken. Please try a different username') return render(request,'editProfile.html',{'form': form }) else: form.save() return redirect(reverse_lazy('login')) else: form = forms.ChangeProfile(instance =request.user) return render(request ,'editProfile.html',{'form' : form } ) -
Vote only once in Django to posts and comments
I have two models called Post and Comment and a User that can upvote or downvote that post or comment. I want to restrict each user however to be able to to vote only once to a certain Post or Comment. I could do something on the model level to Post and Comment and instead tally up total votes for the specific post or comment. However, I think it's a bit more scalable to create a separate Vote model where: total votes can be tallied with one query (SELECT count(*) FROM votes where user_id=, etc...) voting once per user can be enforced with unique_together Currently I have figured out something like this: import uuid from django.db import models from django.contrib.auth import get_user_model from django.db import models # Create your models here. class Post(models.Model): LINK = "link" VIDEO = "video" IMAGE = "image" POST_TYPE_CHOICES = ((LINK, "Link"), (VIDEO, "Video"), (IMAGE, "Image")) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=300) url = models.URLField(max_length=300) category = models.CharField(max_length=50) score = models.DecimalField(default=0, max_digits=20, decimal_places=2) votes = models.IntegerField(default=0) views = models.IntegerField(default=0) post_type = models.CharField(max_length=5, choices=POST_TYPE_CHOICES, default=LINK) text = models.CharField(max_length=40000) owner = models.ForeignKey('users.User', related_name='posts', on_delete=models.CASCADE) def __str__(self): return self.title class Meta: ordering = ["-created"] … -
Deploy a django app that allows user file downloads
I am new to django and i am building a site that allows people to download pdf files. I can upload files easily but i now need help in allowing users to download files. I have seen something like: def document_view(request, document_id): document = Document.objects.get(id=document_id) response = HttpResponse() response.content = document.file.read() response["Content-Disposition"] = "attachment; filename={0}".format( document.pretty_name) return response html: <a id="download" download="" href="">download</a> and i hear its not a good idea for production and its slow. Nginx + uWSGI combination is recommended but i use a windows machine and i am not comfortable moving to Linux. Is there another way to use Nginx on a windows platform ? -
How create one query?
One author has many books. There are many authors with books in the database. It is required to get the latest books of authors. In one query. class Autor(models.Model): name = models.Charfield() class Book(models.Model): name = models.Charfield() author = models.ForegnKey("Autors", models.CASCADE) created_at = models.DatetimeField(auto_now_add=True) # its a many queries last_books = [] for author in Autor.objects.all(): last_book = Book.object.filter(autor=autor).latest("created_at") last_books.append(last_book) # need one query -
Django: Integrate paypal payments to be added my custom wallet database
I am trying to use ajax to submit paypal payments to my model once paypal api approves the payments.The paypal successful transaction alert is executing but the ajax part is not being excuted. Is my jquery version the issue? Is there another approach i can use that the two events will happen asynchronously on approval? Is there another approach to pass the input value to the server side in view? The model: class ClientWallet(models.Model): client = models.ForeignKey(Client,null=True,on_delete=models.SET_NULL) current_amount = models.FloatField("cuurent_amount",null=True) added_amount = models.FloatField("added_amount",null=True) deducted_amount = models.FloatField("deducted_amount",null=True) The view: @csrf_protect def GetInputValue(request): input_value = request.POST['quantity'] print(input_value) return HttpResponse(input_value) The url: path('target_view/', views.GetInputValue), The jquery version: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> The input field and the paypal buttons: <label for="deposit_amount">Amount to deposit:(PayPal)</label> <input type="number" name="deposit_amount" id="deposit_amount"/> <div id="paypal-button-container"></div> The PayPal script: var deposit_amount = document.getElementById('deposit_amount').value; var deposit_string = deposit_amount.toString(); paypal.Buttons({ createOrder: function(data, actions) { console.log(deposit_amount) // This function sets up the details of the transaction, including the amount and line item details. return actions.order.create({ purchase_units: [{ amount: { value: deposit_string, } }] }); }, onApprove: function(data, actions) { $.ajax({ url: '/target_view/', method : 'POST', data: {quantity: deposit_amount}, beforeSend: function() { // things to do before submit }, success: function(response) { alert(response) } }); // This … -
Django - ModuleNotFoundError: No module named 'background-task'
Python 3.7.0, django 3.0.3, django-background-tasks 1.2.5 Trying to use django-background-tasks as explained here https://django-background-tasks.readthedocs.io/en/latest/, but as soon as I add 'background_task' to INSTALLED_APPS, when I run python manage.py migrate I get "ModuleNotFoundError: No module named 'background-task'" -
Django - Create proposals from many tables
Have a look at the following code snippet: def post_proposals(count): post_elements = chain( PostModel1.objects.all(), PostModel2.objects.all(), PostModel3.objects.all(), ) post_elements_list = list(post_elements) post_proposals = random.sample(post_elements_list, count) return post_proposals Where it's requiered to generate a list of proposals from 3 different Post tables, how to optimize a disgn flaw like this? Already came accorss the idea to build a Index table where all PKs of all my PostModel{1..3} are stored, so that I just have to query 1 table instead of three. Does smb. have a practical idea on how to solve this or at least optimizing it? -
How can I reduce loading speed while sending mail - Django
The below code, basically is a form, which is when submitted will send a mail. But the mailing part takes around 20 secs to redirect back to the next page. I just want it to redirect to tasks list and send mails that runs behind the process. views.py if form.is_valid(): task_name = form.cleaned_data["task_name"] order_id = insta.id emp = form.cleaned_data["emp"] task_desc = form.cleaned_data["task_desc"] t = Task(task_name=task_name, task_desc=task_desc, emp=emp, order_id=order_id ) t.save() request.user.task.add(t) subject = "You've got a task!" msg = "Hey buddy , You need to complete this task - "+task_name+" ,"+task_desc from_mail = settings.EMAIL_HOST_USER rcp = request.user.employee.filter(name=emp).values_list('email',flat=True)[0] to = [rcp] send_mail(subject,msg,from_mail,to,fail_silently=True) return redirect('task_list',id=order_id) -
Django DRF issues when running session & token (knox) authentication simultaneously
I have a site that I am moving to single page application design. I need the old site and the new site to be able to run simultaneously, the old site uses the DRF API too. In my settings.py, I have the following: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'knox.auth.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), } The problem that I am having is that, if I am logged into the old site and try to log onto the new site from a different browser window, I get the error message: 'CSRF Failed: CSRF token missing or incorrect'. If I log out of the old site then I can log into the new site and everything works fine. -
Class view with post, get and data
I have practically finished the microblogging application and I want to change to class base views now. I read about generic views, but it looks like each of them has specific properties. In my index view I display two models and two forms, so I created IndexView (View) and put the get and post functions there and it works, but it doesn't look like there are any benefits of class views, so I'm probably doing something wrong. Currently, several views repeat a lot of code, and I thought that class views would solve this problem. I would like an example of how such a view should be written as class view with reusable get. if request.method == 'POST': post_form = AddPostForm(request.POST) comment_form = AddCommentForm(request.POST) if post_form.is_valid(): new_post = post_form.save(commit=False) new_post.author = request.user new_post.tags = '' content = '' for word in new_post.content_post.split(): if '#' in word: new_post.tags += f"{word} " content += f"{word} " else: content += f"{word} " new_post.content_post = content new_post.save() for word in content.split(): if '@' in word: print(word) user_to_notificate = CustomUser.objects.get(username=word[1:]) new_notification = TalkAbout() new_notification.where = new_post new_notification._from = new_post.author new_notification.to = user_to_notificate new_notification.sended = False print(new_notification) new_notification.save() post_form = AddPostForm() if comment_form.is_valid(): new_comment = comment_form.save(commit=False) … -
Javascript Shopping cart replace order button with plus minus button
I am creating e-commerce website in django and I am creating order button. I want that when I click order button it should be replaced by + and - button for setting the value. Everything is working fine except +- button are not responsive aas i am not getting console output.. Please help. I am using local storage for this. {% extends "base.html" %} {% block style %} <style type="text/css"> .dot_active { height: 15px; width: 15px; background-color: #82E0AA; border-radius: 50%; display: inline-block; } .dot_closed { height: 15px; width: 15px; background-color: #E74C3C; border-radius: 50%; display: inline-block; } #myInput { display: inline-block; background-repeat: no-repeat; width: 100%; font-size: 16px; padding: 12px 20px 12px 40px; border: 1px solid #ddd; margin-bottom: 12px; } </style> {% endblock style %} {% block content %} {% load static %} <link href="{% static '/DataTables/css/jquery.dataTables.min.css' %}" rel="stylesheet"> <script src="{% static '/DataTables/js/jquery.dataTables.min.js' %}"></script> <script> $(document).ready(function () { $('#myTable').dataTable(); }); </script> <center><H1>Menu</H1></center> <table id="myTable" class="table table-striped table-bordered table-sm"> <thead class="thead-dark"> <tr> <th>Restaurant Name</th> <th>Dish Name</th> <th>Food Type</th> <th>Price</th> <th>Description</th> <th>Actions</th> </tr> </thead> <tbody> {% for content in content %} <tr> <td>{{ content.restaurant.restaurant.restaurant_name }}</td> <td>{{ content.dish_name }}</td> <td>{% if content.dish_type == "veg" %}<span class="dot_active"></span> {{ content.dish_type}}{% endif %} {% if content.dish_type == "nonveg" … -
unique constraint on the basis of foreign model field value django
I have three model in django applications. for example: class A(models.Model): field1 = models.CharField(..) field2 = models.CharField(...) class B(models.Model): field1 = models.CharField(..) field2 = models.CharField(...) class C(models.Model): field1 = models.ForeignKey(A, ..) field2 = models.ForeginKey(B, ..) Now I want to make sure that value of field1 and field2 is unique together. I know i can use unique_togher = ('field1', 'field2'). but it only compare object id of model A and object id of model B. But here actually i want to compare with actual field2 value of modelB somethings like, unique_together = ('field1', 'field2.field2') -
How to create .gitignore file in the root directory of django project in pycharm automatically?
I am doing a django project using pycharm IDE. When i have initialized a git repository by using pycharm, it has created a gitignore file automatically. But, the problem is that the file is located in idea folder (.idea.gitignore), Not in the root directory. Is that possible to create the gitignore file in the root directory automatically (when initialized)? -
JavaScript to django template language
Can I access a javascript variable in a django template language loop? and if so, how to do it right? My code doesn’t really work: <script> var current_url = window.location.pathname; current_url = current_url.split('/')[2]; console.log(current_url); </script> <h5 class="sb"> {% if folder_0.uri != current_url %} <a href="/catalog/{{folder_0.uri}}/"> {{folder_0.name}} </a> {% else %} {{folder_0.name}} {% endif %} </h5>