Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> -
How To Click A Link Within An Email
Im testing my website with Selenium. After a user registers, they must click a link emailed to them in order to log in. I am able to get the email, but do not know how to click the link. This selects the email confirmation_email = mail.outbox[0] Now I just need to find a link within it and press it. The email link will be something like: http://localhost:52348/accounts/confirm-email/MQ:1jfhcf:4ZqeOcmY4fdfh1lhA0feBl7eeUBk3440/ Thank you. -
why my django slug is not working properly
I want to allow user to search in database for the topic. and show the topic name in url. I already created slug field in database but when i am trying to fetch the data from the database the url is not showing correctly. url is showing: http://127.0.0.1:8000/topic/<slug:topicname>/ what I want to show: http://127.0.0.1:8000/topic/introduction-to-python/ My urls.py file from django.urls import path from . import views urlpatterns = [ path('', views.apphome), path('topic/<slug:topicname>/', views.searchtopic, name = 'searchtopic'), ] My model for the project class blogposts(models.Model): topic = models.CharField(max_length = 200) slug = models.SlugField(max_length = 150, null=True, blank = True) post = models.TextField(max_length = 500) def __str__(self): return self.topic This is my view def searchtopic(request,topicname): if request.method == 'POST': topicname = request.POST.get('searchtopicname') mypost = mypostlist.objects.filter(slug = topicname) context = { 'mypost':mypost, } return render(request, 'blog/result.html',context) My form for searching topic <form action="topic/<slug:topicname>/" method="POST"> {% csrf_token %} <input type="search" placeholder="Search topics or keywords" name="searchtopicname"> <button type="submit">Search</button> </form> -
How to know the Project name when we have multiple applications in django project
I have recently got added into a new project in django hired by a company, They have nearly 38 folders in same directory that of manage.py and have also changed the folder name in which manage.py is situated . Is there any way to know which folder is the main project ?? -
Can anyone tell me why I am getting error.(django&people API)
I was following this documentation to get people name in a Gmail id. I am not getting an authorization window to authenticate the Gmail account. https://developers.google.com/people I provided the client id and secret key. from django.shortcuts import render from inviteapp.forms import InviteForm import httplib2 from apiclient.discovery import build from oauth2client.file import Storage from oauth2client.client import OAuth2WebServerFlow from oauth2client.tools import run_flow def index(request): if(request.method=="POST"): email='' invite=InviteForm(data=request.POST) if invite.is_valid(): email=invite.cleaned_data['email'] # Set up a Flow object to be used if we need to authenticate. This # sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with # the information it needs to authenticate. Note that it is called # the Web Server Flow, but it can also handle the flow for # installed applications. # # Go to the Google API Console, open your application's # credentials page, and copy the client ID and client secret. # Then paste them into the following code. FLOW = OAuth2WebServerFlow( client_id='xxxx', client_secret='xxx', scope='https://www.googleapis.com/auth/contacts.readonly', user_agent='xxx') # If the Credentials don't exist or are invalid, run through the # installed application flow. The Storage object will ensure that, # if successful, the good Credentials will get written back to a # file. storage = Storage('info.dat') credentials … -
how to set extra fields in django inlineformset dynamically
i'm working on a projects for a mobile store which working with IMEI of mobiles each single mobile has its own imei , and the owner of the store selling phone depend on its IMEI's , now when the admin add new mobile in MobileStorage for example quantity= 20 mobile iphone11X have 20 different IMEI's , i want to allow the admin whenever he add new mobile and then select the quantities (20) then extra fields will be 20 , if he filled 10 in quantity field extra fields for IMEI will be 10 class MobileStorage(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) mobile = models.ForeignKey(Mobile,on_delete=models.CASCADE) imei = models.ForeignKey(Imei,on_delete=models.CASCADE,verbose_name='IMEI') quantity = models.PositiveIntegerField() class Imei(models.Model): imei = models.CharField(max_length=50,verbose_name='IMEI',unique=True) class Mobile(models.Model): mobile = models.CharField(max_length=50,unique=True) my forms.py class MobileStorageForm(forms.ModelForm): mobile = forms.ModelChoiceField(queryset=Mobile.objects.all(),empty_label='') class Meta: model = MobileStorage fields = [ 'mobile','quantity' ] class ImeiForm(forms.ModelForm): class Meta: model = Imei fields = ['imei'] i want to control extra fields depend on the quantity in MobileStorage model , and the create for example 20 instance in Imei model MobileStorageFormInlineSet = inlineformset_factory( MobileStorage,Imei,form=ImeiForm,fields=('imei'),extra=2,can_delete=False ) anyone have an idea i appreciate it -
cached_property and classmethod doesnt work together, Django
I am trying to use cached_property and classmethod decorators together in a viewset but it doesnt work regardless of their mutual position. Is it any chance to make it work together or cached_property doesnt work with classmethod? Tnanks. @cached_property @classmethod def get_child_extra_actions(cls): """ Returns only extra actions defined in this exact viewset exclude actions defined in superclasses. """ all_extra_actions = cls.get_extra_actions() parent_extra_actions = cls.__base__.get_extra_actions() child_extra_actions = set(all_extra_actions).difference(parent_extra_actions) return (act.__name__ for act in child_extra_actions)