Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docusign retrieving and saving the retrieved signed document
I am trying to retrieve and save the DocuSign signed document to my django backend. I have been able to retrieve a path-like string following this code: # You would need to obtain an accessToken using your chosen auth flow api_client = ApiClient() api_client.host = base_path api_client.set_default_header('Authorization', 'Bearer ' + access_token) envelopes_api = EnvelopesApi(api_client) account_id # accountId for your DocuSign account envelope_id # envelopeId that you are working on # produce a PDF combining all signed documents as well as the CoC results2 = envelopes_api.get_document(account_id, 'combined', envelope_id) #TODO - use results file to write or send the file for your use But what results2 returns is something like this: '/tmp/04142042_040424_047446_this_document.pdf' How can I actually retrieve the pdf document from this and save it to my models? I have tried saving it as it is, tried to add the base_url before it and retrieve the file using get request, tried to read it, tried to get the content from it but to no avail. How can I get the actual file from this? -
how to merge two views functions with minor differences
I just wrote two view functions for two different models but they are very similar and only different in some names. what is the best way to merge these two view functions to prevent code repetition? these are the view functions: def manager_scientific(request, *args, **kwargs): context = {} if request.user.role == 'manager': template = loader.get_template('reg/scientific-manager-dashboard.html') users = User.objects.filter(role='applicant', isPreRegistered=True, scientificinfo__is_interviewed=True).order_by('-date_joined') approved = ScientificInfo.objects.filter(is_approved__exact='0').all() context['users'] = users context['all_users'] = len(users) context['approved'] = len(approved) context['survey_choices'] = SURVEY_CHOICES if request.GET.get('user', 'all') == 'all': users = users if request.GET.get('user', 'all') == 'new': users = users.filter(scientificinfo__is_approved__exact='0') field_list = request.GET.getlist('field') if field_list: if 'None' in field_list: users = users.filter(fields__title=None) | users.filter(fields__title__in=field_list) else: users = users.filter(fields__title__in=field_list) gender_list = request.GET.getlist('gender') if gender_list: users = users.filter(gender__in=gender_list) education_list = request.GET.getlist('education') if education_list: users = users.filter(educationalinfo__grade__in=education_list) work_list = request.GET.getlist('work') if work_list: users = users.filter(workinfo__position__in=work_list) province_list = request.GET.getlist('province') if province_list: if 'None' in province_list: users = users.filter(prevaddress__address_province__in=province_list) | users.filter( prevaddress__address_province=None) else: users = users.filter(prevaddress__address_province__in=province_list) query_string = request.GET.get('query_string') if query_string: name_query = None for term in query_string.split(): if name_query: name_query = name_query & (Q(first_name__contains=term) | Q(last_name__contains=term)) else: name_query = Q(first_name__contains=term) | Q(last_name__contains=term) users = users.filter(name_query | Q(educationalinfo__field__contains=query_string) | Q(educationalinfo__tendency__contains=query_string) | Q(educationalinfo__university_name__contains=query_string) | Q(workinfo__organization__contains=query_string) | Q(ngoinfo__ngo_name__contains=query_string) | Q(melli_code__contains=query_string)) users = users.distinct() context['grade_choices'] = [] … -
Django Admin CSS and JS loaded but didn't applied
show image As shown in the image above, I received CSS and JS, but it is not applied. I tried refresh and delete cookies and caches. I don't know how to fix this. machine info: Centos 7.9 python 3.6.8 Django 4.0.6 Nginx -
django forms how to insert auto-generated id from the same fields
I'm trying to insert an item with the following fields (studid,office,sem,sy) and I have another column in my db which will be generated automatically after submitting the form called cl_itemid. This column should based on what I put in office/sem/sy fields for example. I have this form Studid:2021-69420 Office:Dorm Sem:1 SY:2021-2022 |Submit| When I press submit. In my database it's. cl_itemid | studid | office_id | sem | sy | Dorm2021-2022-1 2021-69420 Dorm 1 2021-2022 How can I achieve this? views.py def create_view(request): context = {} form = CreateForm(request.POST or None) if form.is_valid(): form.save() context['form'] = form return render(request, "clearance/insert.html", context) forms.py class CreateForm(forms.ModelForm): class Meta: model = ClearanceItem fields = [ 'studid', 'office', 'sy', 'sem', ] insert.html <form method = "post" enctype="multipart/form-data"> {% csrf_token %} <table> <tr> <td>Studid:</td> </tr> <tr> <td>{{form.studid}}</td> </tr> <tr> <td>Office:</td> </tr> <tr> <td>{{form.office}}</td> </tr> <tr> <td>Sem:</td> </tr> <tr> <td>{{form.sem}}</td> </tr> <tr> <td>SY:</td> </tr> <tr> <td>{{form.sy}}</td> </tr> </table> <input type="submit" value="Submit"> </form> -
Pycharm : Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings
I was trying to get Django installed onto my Pycharm. In Terminal, I typed in python -m pip install Django When I pressed enter on the information, It told me: Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. I already have Python installed and put it as the base interpreter for the file. Not sure why Pycharm wants me to install it from the Microsoft store??? Please help! -
Can't hear voice and sound while sharing screen in Agora.io
I have some issues with screen sharing. I can't hear any sounds from viewer site. What can i do this for? I am new to this. Source from dennis ivy:https://www.youtube.com/watch?v=QvNzL_FmzLQ&t=33273s let toggleScreenShare = async() => { if (sharingScreen){ sharingScreen = false await rtcClient.publish([localScreenTracks]) toggleVideoShare() document.getElementById('screen-btn').innerText ='Share screen' }else{ sharingScreen = true document.getElementById('screen-btn').innerText ='Share camera' localScreenTracks = await AgoraRTC.createScreenVideoTrack() document.getElementById('video__stream').innerHTML ='' let player = document.getElementById(`user-container-${rtcUid}`) if(player != null){ player.remove() } player = `<div class="video-container" id="user-container-${rtcUid}"> <div class="video-player" id="user-${rtcUid}"></div> <div class="live-location"> <span class="live-tag">LIVE</span></div> </div> </div> ` document.getElementById('video__stream').insertAdjacentHTML('beforeend', player) localScreenTracks.play(`user-${rtcUid}`) await rtcClient.unpublish([localTracks[0], localTracks[1]]) await rtcClient.publish([localScreenTracks]) } -
contenttype field in serializer without model
Here is the class that only takes object_id and content_type as post request and for that I want to create contenttype field in serializerclass which must show all contenttype object of project while passing data from browsable api. Can somebody know how to do that And my code look like: in views.py from rest_framework.views import APIView class Snippetviews(APIView): serializer_class=SnippetSerializer def post(self,request): data = request.data object_id = data.get("object_id",None) content_type = data.get("content_type") ctype = ContentType.objects.get(model=content_type) obj_model = ctype.get_object_for_this_type(id=object_id) in serializers.py class SnippetSerializer(serializers.Serializer): object_id=serializers.IntegerField() #for this field i don't know what to do.. content_type = -
How to Login with Gmail account in Django
I am having a Login button with Gmail account in Django....Here when I am login with Gmail account means I want extra add information from the user and I want to Store that Information in the auth_user table. Please Help me If I login with Gmail means I will Redirect to that Register Page With Some More Extra Informations. It will Successfully Login but I don't Know How to Save the Extra Information in the auth_user table.Here I am having Extra Register Form with Extra Information to add User but I don't Know how to save that Information in auth_user table in Postgresql.Please Help me I am stuck here Please Help me someone -
Django: How to embede a video in <iframe> using the URL sourced from the database in Django?
I have a Django app that displays a list of videos (ListView). On clicking each item in the ListView, I get directed to DetailView where that specific video is displayed. I am trying to accomplish this by: I can see that the URL as a text is modeled properly. This is how it's supposed to look. The image below shows the embedded video by hard passing the URL in the . But I want to pass the URL dynamically to the src="<URL sourced to database>" from the database. Please help me. Thank you in advance. -
In djangorestframewokr how to apply group by in django serializer using queryset?
models.py Sharing two mapping table where in CategoryLessonMapping, category is mapped with lesson and in UserLessonMapping, user is mapped with lesson ------- category mapped with lesson -------------------- class CategoryLessonMapping(models.Model): category = models.ForeignKey(MasterCategory, on_delete=models.CASCADE, blank=True, null=True) lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, blank=True, null=True) class Meta: db_table = 'category_lesson_mapping' ------- user mapped with lesson -------------------- class UserLessonMapping(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, blank=True, null=True) class Meta: db_table = 'user_lesson_mapping' views.py ------- getting lesson and category related to lesson in json format -------------------- class PatientLessonListView(ListAPIView): serializer_class = PatientLessonSerializer queryset = UserLessonMapping.objects.all() permission_class = (permissions.IsAuthenticated,) def get_queryset(self): user_lesson = self.queryset.filter(user=self.request.user) user_lesson_id = user_lesson.values_list("lesson_id", flat=True) return CategoryLessonMapping.objects.filter(lesson_id__in=user_lesson_id) serializers.py --------- get lesson serialized data ------------- class LessonSerializer(serializers.ModelSerializer): class Meta: model = Lesson fields = ('id', 'lesson_type', 'content', 'description') depth = 1 --------- get category serialized data ------------- class CategorySerializer(serializers.ModelSerializer): class Meta: model = MasterCategory fields = ('id', 'name', 'code') --------------- getting lesson and category related to user ----------used in views.py------------ class PatientLessonSerializer(serializers.ModelSerializer): lesson = LessonSerializer() category = CategorySerializer() class Meta: model = CategoryLessonMapping fields = ['lesson','category'] then json format in which i'm getting it is [ { "lesson": { "id": 1, "lesson_type": { "id": 1, "lesson_type": "Video", "lesson_code": "VIDEO", "is_active": 1, "created_at": … -
How at get user profile details from Django using React?
I have created an Api using django rest framework (localhost/users/profile) that gets the user's details if they are logged in. It works perfectly when I call the API in the backend when user is logged in the backend. enter image description here But when I try to access the same API from my React front end, it doesnt work. import React, { useEffect, useState } from "react" import AuthContext from '../context/AuthContext' import {Link} from 'react-router-dom' const ProfilePage = () => { const [profiles, setProfiles] = useState([]) const fetchData = async () => { const response = await fetch("http://127.0.0.1:8000/users/profile") const data = await response.json() setProfiles(data) console.log(data) } useEffect(() => { fetchData() }, []) return ( <div> {profiles.length > 0 && ( <ul> {profiles.map(profile => ( <li key={profile.id}>{profile.name}</li> ))} </ul> )} </div> ) } export default ProfilePage error from console enter image description here error from Backend server enter image description here -
Django Admin Page not found (404), urls.py + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Going to http://127.0.0.1:8000/admin returns this error: Using the URLconf defined in the_food_blog.urls, Django tried these URL patterns, in this order: admin/ [name='home'] <slug:slug>/ [name='post_detail'] ^(?P<path>.*)$ The current path, admin, matched the last one. urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urls.py urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] Removing + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) fixes this but why? -
How can I prevent one USER from writing multiple reviews for the same movie in djnago?
What you want to achieve I want to prevent one USER from writing multiple reviews for the same movie. I got the movie information from TMDB, so I didn't know how to change it and asked. Current code def view_movie_detail (request, movie_id): if not (Movie.objects.filter (id = movie_id)): Movie (id = movie_id) .save () movie = Movie.objects.get (id = movie_id) if request.method == "POST": form = Comment_movie_CreateForm (request.POST) if form.is_valid (): Comment_movie ( comment = form.cleaned_data ['comment'], user = request.user, stars = form.cleaned_data ['stars'], movie = movie ). Save () return redirect ('view_movie_detail', movie_id = movie_id) else: else: form = Comment_movie_CreateForm () data = requests.get (f "https://api.themoviedb.org/3/movie/{movie_id}?api_key={TMDB_API_KEY}&language=en-US") recommendations = requests.get (f "https://api.themoviedb.org/3/movie/{movie_id}/recommendations?api_key={TMDB_API_KEY}&language=en-US") comments = reversed (Comment_movie.objects.filter (movie_id = movie_id)) average = movie.average_stars () context = { "data": data.json (), "recommendations": recommendations.json (), "type": "movie", "comments": comments, "average": average, "form": form, } return render (request, "Movie / movie_detail.html", context) class Movie (models.Model): id = models.CharField (primary_key = True, editable = False, validators = [alphanumeric], max_length = 9999) def get_comments (self): return Comment_movie.objects.filter (movie_id = self.id) def average_stars (self): comments = self.get_comments () n_comments = comments.count () if n_comments: return sum ([comment.stars for comment in comments]) / n_comments else: else: return 0 … -
Django Admin CSRF issue on Cloud Sutdio
I am learning Django through Django official documentation on Cloud Studio,which can let people develop website online.However,a CSRF issue occurred when I tried to log in the Admin page Django carried originally.I didn't change anything in admin.py enter image description here enter image description here -
How to use d3-cloud in django?
I want to use d3 cloud (https://github.com/jasondavies/d3-cloud) in my django project. but the library source is compiled by Node JS.. so that is like var dispatch = require("d3-dispatch").dispatch; module.exports = function() { var size = [256, 256], text = cloudText, But I can't use Node JS in my django project..how can i use that library in my project? T_T -
Cannot find Django admin static file (404 not found)
My Django project deployed on EC2 instance. Everything is fine except static files. Here is my project directory path tree my_project └─admin ├── admin │ ├── admin │ ├── keywords │ ├── manage.py │ └── static ├── README.md And this is my settings.py setting code about staticfiles # settings.py debug=False BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ROOT_DIR = os.path.dirname(BASE_DIR) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'my_project/static') STATICFILES_DIRS = [ STATIC_ROOT ] And this is my nginx.conf files root /usr/share/nginx/html; location = /favicon.ico { access_log off; log_not_found off; } location /static { alias /static/; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/devel/run/gunicorn.sock; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } And also my machine's environments: Centos 7.9 python 3.6.8 Django 4.0.6 I already did python manage.py collectstatic command. When I enter into this project's Admin page, Every UI have loaded without CSS and JS though. Is somewhere of my setting is wrong? I wonder why django cannot find any static files. -
How do I call model function in groupBy queryset inside View? Django
So this is get_project function I have made in this model which return project details based on billingId class ReportLog(models.Model): billing_id = ... caller_id = ... ... @property def get_project(self): return Project.objects.get(billing_id=self.billing_id) My question is how do I call or integrate this get_project method in this below groupby query I have written in the View so later on in the template page I can access the fields of Project model. bounce_log = ReportLog.objects.all().values('billing_id', 'caller_identity', 'from_addr').annotate(total=Count('billing_id')).order_by('-total') context = { "report_list": bounce_log, } In the template page, where I am iterating report_list I tried accessing with post.get_project.title however, it's returning empty. How do I access it? -
pythonanywhere: Something went wrong :-(
When I'm uploading my DRF app to pythonanywhere, the server shows the following log error: 2022-07-15 01:06:14,933: ModuleNotFoundError: No module named 'Rest_API_Framework.settings'. However, I don't understand why, since if we look at /var/www/art1x_pythonanywhere_com_wsgi.py folder, everything looks fine to me: import os import sys path = 'home/art1x/Rest_API_Framework' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'Rest_API_Framework.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() In addition, the settings.py folder in my django app: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Rest_API_Framework.settings') Please point out any mistakes -
How can API request be "routed" through Django Backend when I want to call it from the frontend?
I am trying to make an API request to a 3rd-party server from my NextJS frontend project which requires a secret API key to be stored as an environmental variable. I used NEXT_PUBLIC_API_KEY in this case, but realized that this exposes the variable to the browser. The documentation of a 3rd-party API says " Production requests must be routed through your own backend server where your API key can be securely loaded from an environment variable or key management service." I am using Django REST as my backend; How do I "route the API through backend" when calling the API from the frontend? I see a lot of resources for node.js, but I am struggling to figure it out for Django. This is how I understood it so far, but I am not sure if it's correct and how to implement. API_KEY is stored in .env of Django server User event in frontend -> sends the data for API request to backend Backend makes the actual 3rd party API request Backend returns the API result back to frontend -
IntegrityError at /tickets/1/comments/new/ NOT NULL constraint failed: comments_comment.ticket_id
Getting an integrity error when creating a separate comments app for my ticket project. Not sure why, I have already assigned the logged in user as author in the get_absolute_url method on my Comment object and so now I'm not sure on how to proceed. Any help is much appreciated Here is my comment model models.py class Comment(models.Model): ticket = models.ForeignKey(Ticket, related_name='comments', on_delete=models.CASCADE) title = models.CharField(max_length=20) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('tickets: ticket-detail', kwargs={'pk': self.ticket_id}) Here is my views.py class CommentCreateView(LoginRequiredMixin, CreateView): redirect_field_name = 'tickets/ticket_detail.html' model = Comment fields = ['title', 'content'] def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] form.instance.author = self.request.user return super().form_valid(form) -
ModuleNotFoundError: No module named 'django'
enter image description here enter image description here enter image description here enter image description here So i just tried to install django 4.0.6 and the terminal says it was successfully installed. However, when I tried to import, it says "ModuleNotFoundError: No module named 'django'" (as provided in the picture). Anyone knows what's going on there? -
CORS issue with HTTP requests when sendign http get request to host IP
I have a development environment with python's django web server running locally. I had setup django to respond to API requests and whenever I send http GET requests to http://localhost:8000/api/service/ the server responds as expected. The issue happens whenever I send the same request using the host IP, i.e, http://192.168.15.66:8000/api/service/ (I realized the issue when trying to get the api data from another host in the LAN) I'm using postman to send the requests in order to validate whether it's working or not, though, I'm developing a javascript react application that already consumes the api data. Through the web javascript application, there's a bit more information. The browser's console presents the error message: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.15.66:8000/api/service/. (Reason: CORS request did not succeed). Status code: (null). I've been searching around and tried a few suggestions, such as: setting server/setting.py ALLOWED_HOSTS to: ['192.168.15.66'] , to [] and to ['*'] whitelisting with CORS_ORIGIN_WHITELIST to: ['192.168.15.66'] and to ['*'] Here's my setting.py MIDDLEWARE varible value: MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] Any clues what I could be missing? -
How do I find all descendant models in a child/parent relationship?
Consider the following model: from django.db import models class Person(models.Model): name = models.CharField(primary_key=True, max_length=50) parent = models.ForeignKey('self', null=True, default=None, on_delete=models.SET_NULL) a = Person.objects.create(name='A') b = Person.objects.create(name='B') c = Person.objects.create(name='C', parent=a) d = Person.objects.create(name='D', parent=b) e = Person.objects.create(name='E', parent=c) Is there an easy way to find all descendants of an instance? Example of desired output: a.descendants >>> [a, c, e] -
How do I query for "greater than" on a textfield in Django?
I have a certain field in my database which is a textfield. However, for a certain use I have a set of records that only include numbers (saved as a string of course) and I want to query them using "gte" (greater than). Normally I would do: MyTable.objects.filter(text_field__gte=100) However, this does not return any results. It seems that I need to cast this field as an integer. Can I do that within this same query? The actual query is more cumbersome and involves external tables (something like MyTable.objects.filter(associated_table__other_table__text_field__gte=100)), but I am simplifying above for clarity. -
How would i go about displaying more information of objects in a ModelForm?
I've tried googling this for hours and i just can't seem to understand it. So i have a model (called Vare) that has 8 different fields with information and containes a str function. I have another model called (Rett) where you store 3 different fields and a field where you store Vare objects. I've managed to make a form for this that displayes the 3 fields + the Vare objects field, but the Vare objects field only shows the name of Vare in a dropdownbox (presumebly from the str function). Now i want to display these with more information from the 7 other fields of vare and put the into a nice looking list element instead of just a drop-down showing the name. But i can't seem to find out how you are supposed to do it. What i want is kinda like looking at amazone where you can see lots of information about the different Vare (like date crated, who is selling, price) in a nice orderly list instead of a dropdown with just the name. Currently i am just using the basic ModelForm with a meta class and i accsess it in my template as {{ rett_form.as_p }}. …