Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to append a paperclip icon in email body - Gmail
I have integrated Gmail in Python and it's working great. Now I need to append a paperclip icon in the list view of email just like the Jira appends to its emails. (But no physical image is actually attached) . I'm unable to do so in my scenario because there's no physical attachment in my email. So I'm wondering how Jira is doing it. Does anyone get the same scenario? A screenshot is also attached for further clarification. Happy Learning. -
How to deploy django app on given domain name?
I have been given domain name 'example.com'. I can access all files using FileZilla. I am creating website using django. Currently there is only one page in website named as 'index.html'. I have .htaccess file. my website is running on my local machine. I want to deploy this app on given domain name. How can i deploy django website on given domain name. .htaccess file : - AuthName "Username and password required" AuthUserFile /var/www/somename/example.com123/.htpasswd AuthType Basic Require valid-user order deny,allow deny from all allow from ip1 allow from ip2 allow from ip3 allow from ip4 Satisfy Any #####Apache################## Options +SymLinksIfOwnerMatch #####Rewrite#################### RewriteEngine on #####Rewrite################# <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </IfModule> #####index.html RewriteCond %{THE_REQUEST} ^.*/index.(html|htm|shtml|shtm|php) RewriteCond %{REQUEST_URI} !(^/phpMyAdmin/) RewriteRule ^(.*)index.(html|htm|shtml|shtm|php)$ example1.com <Files ~ ".(js|gif|ico)$"> Header set Cache-Control "max-age=2592000, public" </Files> <Files ~ ".(jpe?g|png)$"> Header set Cache-Control "max-age=86400, public" </Files> wsgi.py """ WSGI config for mysite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() -
TypeError at /login/home/ || argument 1 must be a string or unicode object
My app is trying to connect to an existing Microsoft SQL server and print a set of variables from the database (Sage 200) When the app moves to the home page (Where the data is supposed to be printed) it gives the above-mentioned error message. Here is the error in more detail: TypeError at /login/home/ argument 1 must be a string or unicode object Request Method: GET Request URL: http://localhost:8000/login/home/ Django Version: 3.2 Exception Type: TypeError Exception Value: argument 1 must be a string or unicode object Exception Location: C:\Users\KylePOG\Documents\GMA Programming\accConnect\main\views.py, line 17, in home Python Executable: C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.4 Python Path: ['C:\\Users\\KylePOG\\Documents\\GMA Programming\\accConnect', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Mon, 23 Aug 2021 06:24:37 +0000 Traceback Switch to copy-and-paste view C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\KylePOG\Documents\GMA Programming\accConnect\main\views.py, line 17, in home 'UID=[UID] ;' 'PWD=[PWD];') def home(request): query = "SELECT top 10 * FROM [[DBNAME]].[dbo].[_etblGLAccountTypes]" conx = pyodbc.connect(cnxn) … cursor = conx.cursor(); cursor.execute(query); data = cursor.fetchall() return render(request , 'main/home.html' , {"data":data}) ▶ Local vars The code that it is trying to execute in the views tab … -
Manytomany field custom display objects in Django
I'm developing a site where I can manually add photographers to the Django adminpanel and then upload the images taken by them. I used the default User system in Django and added a field here that shows this user is a photographer or not : from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): is_photographer = models.BooleanField(default=True) Also, in the model that I need to put the images, I used ManyToMany field for photographers (because these photos may have been taken by several people) : from registration import User class Photo(models.Model): ... photographers = models.ManyToManyField(User) The problem is that when adding a new image to the admin panel, users who are not photographers and the is_photographer is False, is also displayed in the Photographers. I want only users who are photographers to be displayed and not normal users. -
Extract specific data from a bunch of data in python
How can I extract the companies name from the given below data without using NLP in python, Although it works perfectly with NLP but my task is to complete it without NLP........... ['working as associate ui developer in tarang software technologies bangalore from august 2014 excellent decision making skills with a positive approach work experience working as associate ui developer in tarang software technologies bangalore from august 2014 working as associate ui developer in tarang software technologies bangalore from august 2014 to till date worked as software engineer in centre for educational and social studies cess bangalore from'] None july 2012 to august 2014 technical skills to till date worked as software engineer in centre for educational and social studies cess bangalore from july 2012 to august 2014'] -
Get disctinct values from in a queryset django?
I have modelwith 2 foreignkeys. class NewModel(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) user_g_id = models.ForeignKey(User, on_delete=models.CASCADE) This is my queryset. It counts the number of male users but i want distinct number of male users from both the fields. male_count = newmodelqueryset.filter( Q(user_id__gender_id=male['id']) | Q(user_g_id__gender_id=male['id'])).count() -
SearchFieldError - Cannot search with field "body". Please add index.SearchField('body') to Page.search_fields
I have a elasticsearch backend (7.14.0) and wagtail (2.14.1) and I want to include a fulltext-search at the body field of my page. When search something in frontend, I get SearchFieldError at /search/ Cannot search with field "body". Please add index.SearchField('body') to Page.search_fields. Request Method: GET Request URL: https://my.site/search/?query=impres Django Version: 3.2.4 Exception Type: SearchFieldError Exception Value: Cannot search with field "body". Please add index.SearchField('body') to Page.search_fields. Exception Location: /var/www/vhosts/my.site/dev4/venv/lib/python3.6/site-packages/wagtail/search/backends/base.py, line 163, in check Python Executable: /var/www/vhosts/my.site/dev4/venv/bin/python Python Version: 3.6.9 Python Path: ['/var/www/vhosts/my.site/dev4/venv/bin', '/var/www/vhosts/my.site/dev4/mysite/mysite', '/var/www/vhosts/my.site/dev4/mysite', '/var/www/vhosts/my.site/dev4', '/usr/share/passenger/helper-scripts', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/var/www/vhosts/my.site/dev4/venv/lib/python3.6/site-packages'] Server time: Mon, 23 Aug 2021 05:24:18 +0000 my views.py: from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.template.response import TemplateResponse from wagtail.core.models import Page from wagtail.search.models import Query def search(request): search_query = request.GET.get('query', None) page = request.GET.get('page', 1) # Search if search_query: #search_results = Page.objects.live().search(search_query) # exclude some search results search_results = Page.objects.live()\ .exclude(title='Sie sind nun ausgeloggt.')\ .exclude(title='Sie sind nun eingeloggt.')\ .exclude(title='Passwort erfolgreich geändert.')\ .search(search_query, fields=["title", "body"]) query = Query.get(search_query) # Record hit query.add_hit() else: search_results = Page.objects.none() # Pagination paginator = Paginator(search_results, 10) try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) return TemplateResponse(request, 'search/search.html', { 'search_query': search_query, 'search_results': search_results, }) my models.py: … -
Serial request to TokeView of django rest framework social oauth2 causes error
I have mobile backend created with django and I use django rest framework social oauth2 TokenView to refresh access token. from rest_framework_social_oauth2 import views as auth_views urlpatterns = [ path('my-token-path', auth_views.TokenView.as_view(), name = 'my-token-path'), ] The mobile app automatically try to re login when any api request receives Http 401. My mobile app makes several api request at launch. When the app launches and toke was expired, several api requests receives 401 thus each one accesses TokenView to re login using refresh token. When this happens, some requests to TokenView fails with error log saying datbase is locked. How can I prevent this error? -
Django List Based Off Previous List
I am trying to make a dynamic list of choices. That is, the choices change based on a previous answer. For example, if country = ["USA", "Canada", "Mexico"], then click "USA" will generate a list with the 50 US States, state = ["Alabama", "Alaska"]. I tried to do an if statement, however, that did not seem to work. I am not sure what the best option for this is. class Property(models.Model): address = CharField(max_length = 200) city = CharField(max_length = 200) COUNTRY_LIST = [ ("USA", "United States"), ("CAN", "Canada") ] country = CharField(max_length = 3, choices = COUNTRY_LIST) USA_STATE_LIST = [ ("AL", "Alabama"), ("AK", "Alaska"), ("AZ", "Arizona") ] CAN_STATE_LIST = [ ("AL", "Alberta"), ("BC", "British Columbia") ] state = CharField(max_length = 2, choices = ?) -
How do i add another field to Django's default user model. For instance, adding a field called matricule
I am working on a project where by users needs to use their matricules and password as a form of authentication. Please how do i go about adding a matricule to Django's default user model -
How to generate form elements from the forms.Form classe in Django?
In my project, a feature has multiple possible scopes. class ProjectForm(forms.Form): features = Feature.objects.all() i = 0 for feature in features.iterator(): scopes = RectificationAssetMultiField( required=False, queryset=Scope.objects.filter(feature=feature.pk), widget=forms.CheckboxSelectMultiple, ) i+=1 class Meta: model = Project I need to create groups of "RectificationAssetMultiField". With my current code, only the last set of scopes are desplayed with {{ form.scopes }}. I only could think of variable name generation (scopes0, scopes1... for each feature) but I'm not sure if it's the right way and if it can work or not. How could I achieve that? -
How to edit a form field to add some condition using Django template
I have a form (ModelForm, Model and view). Everything works fine but there is a new requirement in the project and one of the text-input is no longer simple, I need to use some Django template (if condition). This is exactly the HTML representation of the input that I need (and it works separately): <input class="form-control ts_project" id="ts_project" name="ts_project" type="text" {% if entry.project %}value="{{ entry.project.id }}: {{ entry.project.name }}"{% endif %}> What I have tried: edit the attributes of the widget in the forms.py so that it looks as close as possible to the HTML code above but it has been impossible for me. forms.py: from django.forms import ModelForm from django import forms from expense.models import Expense class ExpenseForm(ModelForm): class Meta: model = Expense fields = ['project'] widgets = { 'project': forms.TextInput( attrs={ 'class': 'form-control ts_project', 'id': 'ts_project', 'name': 'ts_project', {% if entry.project %} 'value':'{{ entry.project.id }}: {{ entry.project.name }}' {% endif %}, } ) } The code doesn't work but I can't think of another way to make it work. class, id and name working as expected if I delete value and all the Django template code. models.py (truncated): from django.db import models from django.contrib.auth.models import User from project.models … -
socket.gaierror: [Errno 11001] getaddrinfo failed django - paho mqtt
initialized paho mqtt in django urls.py . when i run django i am getting this error socket.gaierror: [Errno 11001] getaddrinfo failed. -
Python Django Cannot go the wanted link within another page
I am currently working on a website and I have a navigation bar in it. When I click the "about" button I need website to open localhost:8000/about/ link. But when I'm in a different page like localhost:8000/chapter/3/ It directs me to localhost:8000/chapter/3/about/ (The website is about a web novel thats why there is chapters) How can I make it so that wherever I click that "about" button from I want it to direct me to localhost:8000/about/. How can I make it happen? Note: I tried using ../ but didn't work for me Assume that urls and views are properly set up -
How do I create custom type for graphql using django?
class PostsType(DjangoObjectType): class Meta: model = models.Post fields = "__all__" I am using graphene for graphql with django. I have three model entities named Post, Comment, and Like. Whenever I query posts, I would like to return all posts with their respective likes and comments. How do I create a custom PostsType to achieve that? -
Django call a Model method inside another method of the same Model (in models.py)?
I want to call a model method inside another model method in models.py but i receive the error AttributeError: module 'my_website.models' has no attribute 'my_model_method' Here is my model: class SaleCode(models.Model): #my fields and methods... #the method I want to call def generate_token(self, apply=True, length=5): # stuff return { "token": token, "self-applyed": apply } #save() method override def save(self, *args, **kwargs): if not self.pk: #self.code is one of my fields self.code = self.generate_token()["token"] #the line that generates the error super(SaleCode, self).save(*args, **kwargs) What I have tried: I tried to place @classmethod (and @staticmethod) over the generate_token(...) declaration and then to call it as SaleCode.generate_token(): @classmethod def generate_token(self, apply=True, length=5): ... self.code = SaleCode.generate_token()["token"] #the line that generates the error I wrote the function outside the method and then called it as a normal function (it worked but it does not seem to be a "clear" way to do that.) -
Django - Why user did not pass IsAdminUser, but django does not throw exception of unauth?
Here is my sample code of using Token Authen: class test_api(generics.GenericAPIView): permission_classes = (IsAdminUser, IsAuthenticated) def get(self,request): return HttpResponse("You call random test api") I am using Token Authen, with my header of request like this, this is a Token of NOT AdminUser Authorization : Token fc823d7a1d8973056e11e9c8b974f17e351c4263 When I call the api, It print out of terminal these lines False [23/Aug/2021 10:39:20] "GET /user/get-user HTTP/1.1" 200 13 I suppose the False got print out from IsAdminUser permission. However, the code still reponse 200 and give me response of You call random test api. Only when I give the wrong Token, I receive 403 Unauth response. -
How to extend access token validity days of ConvertTokenView of Django rest framework social oauth2
I use Django rest framework social oauth2 ConvertTokenView to return access token. It seems by default tokens are valid for a day. How to extend token validity days? -
Django Herkou deployment retuning Not Found Error
I'm stuck in a loop of problems with running my Django app on Heroku. I'm facing with an Not Found Error and a Server Error (500) when i check the admin site don't seem to understand why? From my understanding, it seems like the Heroku build was successful, however it seems to be throwing an error with the static files that it is searching for? How can i resolve this issue? My project structure is built as : |-frontend(vuejs) |-server |-mysite |-settings |-__init__.py |-base.PY |-local.py |-production.py |-urls.py |-wsgi.py |-db.sqlite3 |-asgi.py |-__init__.py |-manage.py |-Procfile |-requirements.text The following is the Heroku logs: 2021-08-23T02:10:06.042544+00:00 app[web.1]: [2021-08-23 02:10:06 +0000] [7] [INFO] Worker exiting (pid: 7) 2021-08-23T02:10:06.042595+00:00 app[web.1]: [2021-08-23 02:10:06 +0000] [4] [INFO] Handling signal: term 2021-08-23T02:10:06.243215+00:00 app[web.1]: [2021-08-23 02:10:06 +0000] [4] [INFO] Shutting down: Master 2021-08-23T02:10:06.334633+00:00 heroku[web.1]: Process exited with status 0 2021-08-23T02:10:09.033247+00:00 heroku[web.1]: Starting process with command `gunicorn --pythonpath server plur.wsgi` 2021-08-23T02:10:11.272467+00:00 app[web.1]: [2021-08-23 02:10:11 +0000] [4] [INFO] Starting gunicorn 20.1.0 2021-08-23T02:10:11.273980+00:00 app[web.1]: [2021-08-23 02:10:11 +0000] [4] [INFO] Listening at: http://0.0.0.0:38843 (4) 2021-08-23T02:10:11.274025+00:00 app[web.1]: [2021-08-23 02:10:11 +0000] [4] [INFO] Using worker: sync 2021-08-23T02:10:11.276846+00:00 app[web.1]: [2021-08-23 02:10:11 +0000] [7] [INFO] Booting worker with pid: 7 2021-08-23T02:10:11.305556+00:00 heroku[web.1]: State changed from starting to up 2021-08-23T02:10:11.368570+00:00 … -
__init__() got an unexpected keyword argument 'request'
A silly question: why do we get TypeError on the super's __init__ only? Aren't they supposed to take the same arguments? class MyModelForm(forms.ModelForm): class Meta: model = MyModel def __init__(self, *args, **kwargs): # self.request = kwargs.pop('request') super().__init__(*args, **kwargs) If it's the same method of the same forms.ModelForm class, why does the first one accept request and the second doesn't? -
Django views not returning a value from a multiple parameter request?
I've been using vanilla Django as a backend to my React frontend. I'm trying to make a POST request using axios that passes a dictionary of 2 values to my django view, and so far on my front end the values are valid, the connection to the django url is made, but the only issue is the actual data being processed in the view. If I try to print the value, it returns as None. Heres what I have so far: Relevant Code views.py def render_data(request): reddit_url = request.POST.get('reddit_url') sort = request.POST.get('sort') print(reddit_url, sort) users_data, count = run_data(reddit_url, sort) data = { 'users_data': users_data, 'count': count, } return JsonResponse(data) component.jsx const APIcall = () => { axios .post( `http://127.0.0.1:8000/reddit_data/`, { reddit_url: location.state.link, sort: location.state.sort, }, { headers: { "Content-Type": "application/json", "X-CSRFToken": location.state.token, }, withCredentials: true, //cors requests } ) .then((res) => { console.log("YESSIR"); setLoading(false); }); }; Expected/actual output Ideally, the output would print the values from the request, but the actual result is just None, None. What I tried I tried using request.POST['reddit_url'] with no different results Double checking the frontend values to make sure the POST call is going through with the correct values I'll be honest I havent … -
Cannot import Django modules
Hello, the image is from my visual studio. I installed Django and tried to look at it. However, it seems like I cannot import Django modules. What is the problem? -
How can i get the SUBSCRIPTION values from this QUERYSET in Django
i want to access to all value of 'SUBSCRIPTION', but nothing work' i'm using for loop and more, but this send some responses like this. AttributeError: 'dict' object has no attribute 'SUBSCRIPTION' or TypeError: QuerySet indices must be integers or slices, not str. AttributeError: 'QuerySet' object has no attribute 'objects' so, how can i loop this querySet.. ??? -
Do queries involving tables with geometry that don't query the geometry itself take longer to query than a table without geometry?
I have a postgis table in a geodjango application that contains around 45,000 rows with a multipolygon geometry type. I would like to know if querying this table is slowed by the presence of the geometry when the geometry is not involved in the query, or in other words, if I related the geometry field with a one-to-one relationship would this boost performance? -
CSRF-cookie not set when sending a Delete request
I'm using django rest fro backend and reactnative for front, on my backend i have two models one for image and one for files, i can delete the files with a delete request but when i try to delete an image i get 403 forbidden crf cookie not set. Image view: def UploadsDetails(request,pk): try: image=Uploads.objects.get(pk=pk) except Uploads.DoesNotExist: return HttpResponse(status=404) if request.method =='DELETE': image.delete() return HttpResponse(status=204) urls: from django.urls import path from .views import Upload_list,login from .views import UploadsDetails urlpatterns=[ path('Uploads/',Upload_list), path('Uploads/<uuid:pk>/',UploadsDetails), path('login/', login) ] the files view : def FileDetails(request,pk): try: file=File.objects.get(pk=pk) except File.DoesNotExist: return HttpResponse(status=404) if request.method =='GET': serializers=Fileserializers(file) return JsonResponse(serializers) elif request.method =='PUT': serializer=Fileserializers(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors,status=404) elif request.method =='DELETE': file.delete() return HttpResponse(status=204)