Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail add thumbnail image to PageChooserPanel
How is it possible to customize the explorer/list view of the PageChooserPanel? I would love to add a thumbnail image here to make life easier for the editors. Their task is to pick out a few dozen artworks (pages) from a large archive. A preview image (and possibly a few additional columns) would greatly simplify this work. I am aware of the get_admin_display_title of a Page as mentioned here. How about a custom version of the PageChooserPanel? I found the AdminPageChooser widget in there, but did not understand how the table of the explorer view is rendered finally. Not sure if it is necessary to get into the weeds to this extend. Would love to see a simple hook like the ModelAdmin list view with its ThumbnailMixin. # wagtail/admin/panels.py from wagtail.admin.widgets import AdminPageChooser class PageChooserPanel(FieldPanel): # ... def get_form_options(self): opts = super().get_form_options() if self.page_type or self.can_choose_root: widgets = opts.setdefault("widgets", {}) widgets[self.field_name] = AdminPageChooser( target_models=self.page_type, can_choose_root=self.can_choose_root ) return opts -
Saving django data field into another field of same table
Adding + 10 to (session field) and trying to save the data into (totalsession field),So that totalsession display on a table in the frontend in a new raw everytime the button is clicked. THANK YOU VIEWS.PY @api_view(['POST']) def swimmersReduce(request, pk): sw = get_object_or_404(Swimmers,id=pk) # gets just one record current_sessions = sw.sessions + 10 sw.sessions = current_sessions # updates just the one in memory field for sw (for the one record) sw.save() # you may want to do this to commit the new value serializer = SubSerializer(instance=sw, data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, safe=False, status=status.HTTP_201_CREATED) return JsonResponse(data=serializer.errors, safe=False, status=status.HTTP_400_BAD_REQUEST) MODELS.PY class Swimmers(models.Model): name = models.CharField(max_length=200, blank=False) lastname = models.CharField(max_length=200, blank=False) idno = models.CharField(max_length=200, blank=False, null=True) sessions = models.IntegerField(blank=False) totalsessions = models.IntegerField(blank=True, null=True) dateofpayment = models.CharField(max_length=200, blank=True) -
I am trying to make a webpage in django everything works well
How to write django code inside css style tag to link images from static directory -
after editing any task
I am using paginator in my list view. Every page listed 10 item. If I edit an item from page 5 then I want to redirect back to page 5. Right if I edit an team from page 5, it's redirecting me every time in page 1 -
How can i keep the Searched thing in search bar after searching something in Django?
Whenever i am searching for something in search bar. My search functionality is working properly but the thing i had searched gets disappear. How can i keep the text in search bar after searching? -
rest_framework.exceptions.ParseError: JSON parse error - 'utf-8' codec can't decode byte 0x89 in position 135: invalid start byte
While Uploading an image from Angular 8 to Django, rest_framework.exceptions.ParseError: JSON parse error - 'utf-8' codec can't decode byte 0x89 in position 135: invalid start byte getting this error,while try the API in POSTMAN it got success The code in views.py file is: def post(self, request): image = request.data['image'] request_data = { "image": image, } image_serializer = ImageSerializer(data=request_data) if image_serializer.is_valid(): image = image_serializer.save() response = self.response(is_success=True, status=status.HTTP_201_CREATED, data=self.get_data(image), token="", message="Success") return response -
Python Virtual Environment: changed path of enviroment - can't find packages anymore (How to show the enviroment where its packages are located)
I have a issue with my virutal enviroment and I couldn't find a clear and straightforward awnser for it. I had a fully working virtual enviroment with a lot of packages. My directory changed from "../Desktop/.." to "../Cloud_Name/Desktop/.." and lets assume i can't change that anymore. I'm now able to cd into my eviroment and activate it. If I now want to use any kind of command I get: Fatal error in launcher: Unable to create process using "C: ..." "C: ..." the system cannot find the specified file. I tried sofar to change the directory in "eviroment/Scripts/activate" and "eviroment/Scripts/activate.bat", but it doesn't work. I don't want to install a new enviroment. I'd be very thankfull if someone has a working solution to show my eviroment where its packages are. Thank you in advance for your time and have a great day! -
Django mass email - get single recipient address in every email template
I'm sending email in Django: ... recipient_list = ['first@recipient.com', 'second@recipient.com',] mail = EmailMessage('Subject', 'content body', [sender@email.com], recipient_list) mail.send() In the template I'm rendering I would like to extract single recipient like this. template.html ... This message was sent at {{ datetime_sent }} to address {{ recipient_address }}. I don't want to pass recipient_list in every email in case of mass email, but rather a single recipient address. Is this possible? -
Django: Running dumpdata command programmatically fails
I want to run django's dumpdata command programmatically, however from django.core.management import call_command call_command('dumpdata', 'asdf', indent=2, output=filePath) fails with Unable to serialize database: 'ascii' codec can't encode character '\xdf' in position 83: ordinal not in range(128). running python3 manage.py dumpdata --indent=2 --output=dump.json.gz asdf from the command line works fine though! why won't it work with call_command()? python version: 3.6.9 django version: 3.2.13 $LANG is set to en_US.UTF-8 $LC_ALL is set to en_US.UTF-8 $LC_CTYPE is set to UTF-8 -
How to Deploy Django App on Centos server having domain secured With SSL?
I have a Django App which I want to deploy on a Centos Linux server having a global/public IP which is assigned to a domain and is secured with SSL. The System configuration is as: centos-release-6-10.el6.centos.12.3.x86_64 Apache/2.2.15 (CentOS) When I run the server using: python manage.py runserver 0.0.0.0:8000, then it is only accessible from the browser by passing a local IP say http://192.xxx.xx.xxx:8000/django_app/home But I want to access it from the public/global IP, but it gives an error when I replace the local IP with Global/Public IP or domain assigned to the public IP as: 105.168.296.58 took too long to respond. Try: Checking the connection Checking the proxy and the firewall Running Windows Network Diagnostics ERR_CONNECTION_TIMED_OUT When I simply put this public IP in the browser as https://105.168.296.58 then it redirects the browser to the app/website say https://mywebsite.com/home which is running at port 80 on Apache, and shows the assigned domain instead of IP, so IP is working fine. in settings.py: all hosts are allowed as ALLOWED_HOSTS = ['*'] Methods tried are: by using django-extensions as: python manage.py runserver_plus --cert certname 0.0.0.0:8000 by using django-sslserver as: python manage.py runsslserver 0.0.0.0:8000 The app runs from both of these methods only locally … -
Write a title that summarizes the specific problem The title is the first thing potential a
Write a title that summarizes the specific problem The title is the first thing potential answerers will see, and if your title isn't interesting, they won't read the rest. So make it count: -
I have configured Django REST Framework API Key, I want to expose one API to call without API key in Authorization header, What configuration needed?
This is the code block I have added to my settings.py file. Is there any way to expose an API that can be called without an authorization header? I don't want to use the JWT token. There is no user interface in the application its an integrator project. Please suggest here... Thanks "DEFAULT_PERMISSION_CLASSES": [ "rest_framework_api_key.permissions.HasAPIKey", ] }``` -
AttributeError: 'MiddlewareTests' object has no attribute 'request'
class MiddlewareTests(TestCase): def SetUp(self): self.middleware = MiddlewareClassName() self.request = Mock() def test_logging(self): with self.assertLogs() as captured: MiddlewareClassName.__call__(self, self.request) self.assertEqual(len(captured.records), 1) When I try to run the test_logging, I come across the error "AttributeError: 'MiddlewareTests' object has no attribute 'request'". Why? -
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?