Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sencha ExtJS PDF Download
I have a rather complex frontend in Sencha ExtJS with a Python/Django Backend. I need to download PDFs via the Django Backend, which needs authentication. I tried an iFrame and window.open but I can not pass the auth token with this approach. How can I accomplish the pdf download from the backend with authentication? Thanks in advance, Reto -
How to get related to ID objects from database
I am creating a website where i am using django database.The database will have one def called categories and one called gifi.So a gif will belong to a category and when one category will be clicked it will send the user to a page where all gifs that belong to that category will show up.I know that i should do something like requesting ID but i dont know the code This is the models: from django.db import models class categorite(models.Model): name = models.CharField(max_length=100) id = models.AutoField(primary_key=True) class Gifi(models.Model): foto = models.ImageField(upload_to='website/static/') emri = models.CharField(max_length=100) Source = models.CharField(max_length=100) Kodet = models.CharField(max_length=12) categoryId = models.ForeignKey(categorite, on_delete=models.CASCADE) id = models.AutoField(primary_key=True) This is views: from django.shortcuts import render,get_object_or_404 from .models import Gifi,categorite # Create your views here. def home(request): return render(request, 'website/home.html') def categories(request): content = { 'view': categorite.objects.all() } return render(request, 'website/categories.html',content) def PostaCode(request): return render(request, 'website/PostaCode.html') def Contact(request): return render(request, 'website/Contact.html') def category(request,id): content = { 'view': categorite.objects.get(id=id) } return render(request, 'website/category.html',content) This is urls: from django.urls import path from . import views urlpatterns = [ path('Home/',views.home, name='home'), path('Categories/', views.categories, name='categories'), path('PostaCode/', views.PostaCode, name='PostaCode'), path('Contact/', views.Contact, name='Contact'), path('Category/<int:id>/', views.category, name='category'), ] This is the code that i use to show categories on … -
Django FileNotFoundError at /admin
I have model registered on admin page: admin.py from django.contrib import admin from .models import Question admin.site.register(Question) and I can see a database through admin page: https://i.stack.imgur.com/SuCcX.png but I can't click on any record of the table and modify it due to an error: https://i.stack.imgur.com/M6W5a.png I did it many times since now, and I have never encountered such an error. Does anybody have an idea how to fix it? -
How to sort source argument for nested serializer field in Django REST Framework?
I have 2 models: Page and Section. A Page object may have 1-to-many Section objects. In models.py: class Page(models.Model): name = models.CharField(max_length=100, help_text='Name of the page.') class Section(models.Model): page = models.ForeignKey(Page, on_delete=models.CASCADE) name = models.CharField(max_length=100, help_text='Name of the section.') index = models.IntegerField(blank=True, help_text='Index number to sort section.') index in a Section object indicates its ordering (position) among the rest of Section objects that have same Page object as their foreign key. In serializers.py: class SectionSerializer(serializers.ModelSerializer): page = serializers.PrimaryKeyRelatedField(queryset=Page.objects.all(), many=False, required=True) class Meta: model = Section fields = ['id', 'page', 'name', 'index'] class PageSerializer(serializers.ModelSerializer): sections = SectionSerializer(source='section_set', many=True, required=False) # problem is here. # can I do something like source="section_set.order_by('index')" class Meta: model = Page fields = ['id', 'name', 'sections'] With sections attribute in PageSerializer I can get all Section objects that have the same Page object as foreign key. But not ordered by their index field. When I query Page.objects.all using PageSerializer I got this result in browsable API: { "id":1, "name":"Home", "sections":[ { "id":10, "page":1, "name":"second_section_for_page_1", "index":2 }, { "id":11, "page":1, "name":"first_section_for_page_1", "index":1 }, { "id":12, "page":1, "name":"third_section_for_page_1", "index":3 } ] } I would like the result to be ordered by index. Like this: { "id":1, "name":"Home", "sections":[ { … -
Django >= 3.1 and is_ajax
HttpRequest.is_ajax() is deprecated starting with version 3.1. I want to return html if the page is requested from a browser and as JsonResponse if called from javascript or programmatically. I am seeking guidance on how to do that. https://docs.djangoproject.com/en/3.1/ref/request-response/#django.http.HttpRequest.is_ajax -
Unable to display image | Django | React js
This is my component file where i want to load my profile image uploaded by user <React.Fragment> <div id="profile_name" onClick={expand}> <div id='user_name'>{ user.User_info.userdetails.full_name }</div> <div id="profile_img"> <img src= { user.User_info.userdetails.profile_img } height="40px" alt='profile' /> </div> </div> <div id='profile_log'> <span onClick={() => window.location.href="/accountdetails" }>Profile <img id='ico' src={profile}></img></span> <span>Requests<img id='ico' src={request}></img></span> <span>Your Books<img id='ico' src={bookico}></img></span> <span onClick={ Logout }>Logout<img id='ico' src={logout}></img></span> </div> </React.Fragment> The response from api which is set in user state is { "user": "exist", "password": "valid", "userdetails": { "user_name": "laxman1006", "full_name": "ajay nagpal", "user_email": "Laxman@9451", "college_name": "iitd", "city": "luckonow", "country": "india", "profile_img": "/images/profile_image/laxman1006/laxman1006.jpg" } } My settings.py file STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,"frontend/build/static") ] MEDIA_ROOT=os.path.join(BASE_DIR,'images') And this is my url.py file from django.contrib import admin from django.urls import path , include,re_path from .views import index from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('api/bookdetails/', include('backend.api.urls', 'api')), path('', index , name='index'), ] urlpatterns += static(settings.MEDIA_URL,document_root= settings.MEDIA_ROOT) When i am opening my image file directly from browsers URL its working but when i am including in src of image its not working there is no src in my image So anyone can tell what could be the possible reason?? -
Referring Css and Bootstrap files
I have just started learning django and need some help. I have attached settings file with HTML code and its output. My HTML code is linking my css file. Am I linking it correctly or do I need to change something in settings.py file. Also I wasn't able to use bootstrap so I copied navbar example for W3school website and it ran fine. but when I replace the bootstrap link from the W3school to the one from bootstrap wesbite, it again doesn't work. And of course when I try to link downloaded bootstrap link, it doesn't work as well. Please help me with this. I'm using django 3.1.enter image description here Settings.py -
Select2 wont display the initital value set on the django forms
I have been working on the select2 and django forms, I would like to display the first object of model to select to I used this code: class SchoolForm(forms.Form): school = forms.ModelChoiceField( label=_('Campus'), queryset=School.objects.none(), required=False, ) def __init__(self, *args, **kwargs): self.school_sys = kwargs.pop("school") super(SchoolForm, self).__init__(*args, **kwargs) school_campus = self.school_sys.school_set.all() self.fields['school'].queryset = school_campus if school_campus.exists(): self.fields['school'].initial = school_campus.first() and spit this to the html however the select2 is showing all school but no initial first value on select2 Or just I can do it in on jquery? Thank you -
What is the best way to transfer session from a PHP application to Django without migrating database in Django
I have tried sending a post request from PHP application to Django View Function. I can access the request.POST parameters and check in database for the user details. But how can I start the session in Django without migrating database. I tried accessing request.COOKIES and request.Sessions details but they were empty. Any suggestions are appreciated. Thanks :) -
How to sort model object fields written in Cyrillic?
I need to sort my model objects. I know that there are two main ways to do this in Django, either by adding ordering to the Meta class of my model, or using order_by in the view. However, when the words are written in the Cyrillic alphabet, the ordering fails. I've managed to solve this problem for strings by using the icu library with the following method: def sort_strings(string, locale=None): import icu if locale is None: return sorted(string) collator = icu.Collator.createInstance(icu.Locale(locale)) return sorted(string, key=collator.getSortKey) But this doesn't work when trying to sort model objects. Does anybody know how to do this? -
Override Django model managers bulk_create method and use a pre_save signal on each item
I have a table that uses a custom_primary_key as an id which is a combination of 4 fields in the current table. I created a pre_save signal to concatenate the 4 fields to use it as an id. It is working fine with the save() and create() methods but I also wanted to implement the same logic with the bulk_create() method, how can I send each item in bulk_create to use the pre_save signal that generates the primary key value? This is a sample code of what I'm trying to achieve but it seems that it is not reading the signals from the bulk_create method. The error says Failing row contains (null, 1, 2, 3, 4). CustomManager(models.Manager): def bulk_create(self, objs, **kwargs): for obj in objs: pre_save.send(obj.__class__, instance=obj) return super().bulk_create(objs, **kwargs) class MyModel(models.Model): objects = CustomManager() id = models.BigIntegerField(primary_key=True) field1 = models.IntegerField() field2 = models.IntegerField() field3 = models.IntegerField() field4 = models.IntegerField() def generate_custom_id(sender, instance, **kwargs): instance.id = {}{}{}{}.format(instance.field1, instance.field2, instance.field3, instance.field4) pre_save.connect(generate_custom_id, sender=MyModel) -
Difference between get() and filter() of python django? Does filter() does not consider associated table while fetch data? [duplicate]
models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_img = models.ImageField(upload_to='ProfileImg', default='ProfileImg/default-avatar.png') feedback = models.CharField(max_length=100, null = True) views.py While using objects.get() user = User.objects.get(id=request.user.id) user.userprofile.feedback = sentiment_Value user.save() it is working fine. but while using objects.filter() user = User.objects.filter(id=request.user.id) user.userprofile.feedback = sentiment_Value user.save() I'm getting error user.userprofile.feedback = sentiment_Value AttributeError: 'QuerySet' object has no attribute 'userprofile' and the user returns user: <QuerySet [<User: snegi8005>]> I don't know why this is happening. I thought both get() and filter() function work same the only difference is get() raises exception if nothing found and filter() return none if no match found. how get() and filter() works? Please correct me if i'm wrong and help me solving this. i want to get the user's data of a user.id and the associated table userprofile data also. in case data not found it should return none or should not raise exception. I know i can use get() with try/except block but that would be too much of code for me. -
Custom user view/edit permissions related to same table for different users in django admin panel
i am making an survey/polling app using django rest framework. I have a polls table, and personality's table (with a django country Field in it) related to poll table. I am using rest-auth for user model (not related to personality table). Now i need set some permissions in django admin panel that a certain admin can only view a poll for certain country only. like for example, if there is an admin for US, then he can view/add/change only the polls related to US only. is there any way to set such permissions. NOTE: these permissions are needed to be set for admin panel -
401 (Unauthorized) error while using AutoDesk APIs
I have a Django application and I'm working with .stl, .stp and .igs files in it. I have to display these files in a HTML template and I'm trying to use the AutoDesk APIs for that. I have created an account first and authenticated but I'm getting trouble with displaying the images. here is the view which it contains authentication and uploading image to the bucket: def viewer(request): req = { 'client_id' : CLIENT_ID, 'client_secret': CLIENT_SECRET, 'grant_type' : 'client_credentials','scope':'code:all bucket:create bucket:read data:read data:write'} resp = requests.post(BASE_URL+'/authentication/v1/authenticate', req) if resp.status_code == 200: TOKEN = resp.json()['access_token'] else: print('Get Token Failed! status = {0} ; message = {1}'.format(resp.status_code,resp.text)) TOKEN = "" filepath = "C:/Users/imgea/desktop/" filename = '55.stl' my_file = Path(filepath + filename) #check package file (*.zip) exists if my_file.is_file(): filesize = os.path.getsize(filepath + filename) # encoding the file name if sys.version_info[0] < 3: encodedfilename= urllib.pathname2url(filename) else: encodedfilename= urllib.parse.quote(filename) resp = requests.put(BASE_URL + '/oss/v2/buckets/'+'bucket'+'/objects/'+ encodedfilename, headers={'Authorization': TOKEN,'Content-Type' : 'application/octet-stream','Content-Length' : str(filesize)},data= open(filepath+filename, 'rb')) if resp.status_code == 200: urn = resp.json()['objectId'] else: print('Upload File to Bucket of Data Management Failed! status ={0} ; message = {1}'.format(resp.status_code,resp.text )) urn = "none" else: print(' ' + filename + ' does not exist') urn = "none" context = … -
TemplateDoesNotExist error in django with celery
I am learning to use celery with django through this tutorial. In this tutorial, the person is developing a webscraping tool with django and celery. I am trying to follow the tutorial but I am facing the following error message TemplateDoesNotExist at / home.html, scraping/products_list.html this is how my files are arranged . ├── celerybeat-schedule.db ├── celerydjangotutorial │ ├── __init__.py │ ├── asgi.py │ ├── celery.py │ ├── settings.py │ ├── templates │ │ ├── base.html │ │ └── home.html │ ├── urls.py │ ├── views.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py └── scraping ├── __init__.py ├── admin.py ├── apps.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_auto_20200827_0735.py │ ├── __init__.py │ └── __pycache__ │ ├── 0001_initial.cpython-38.pyc │ ├── 0002_auto_20200827_0735.cpython-38.pyc │ └── __init__.cpython-38.pyc ├── models.py ├── tasks.py ├── tests.py └── views.py where celerydjangotutorial is the django project and scraping is a django application. In the tutorial, the person places the templates into the project directory. he also creates a views file in the project directory. I followed him as he does in the tutorial. here is my code. celerydjangotutorial/urls.py from django.contrib import admin from django.urls import path, include from .views import HomePageView urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('admin/', … -
Django models in multithreaded scrapers
I am using Django models to store the data scraped. The scrapers are multithreaded due to slow response from website and interval of scraping is like every 2 or 3 or 10 minutes. The problem is that the database connections are left IDLE and after sometime I am getting OperationalError. After googling I used connections.close() from django.db.connections at the end of each function wherever database interaction is done. It worked but for a few days and then in one of the scraper again I got OperationalError saying connection was closed by admin. I scheduled the scrapers using a management command and used schedule package. I am using PostgreSQL as my database. Please tell me a solution to this. -
Django ORM sync_to_async error FATAL: remaining connection slots are reserved for non-replication superuser connections
I am trying to implement Asynchronous support(https://docs.djangoproject.com/en/3.1/topics/async/) for Django ORM to write many records in Database(Postgres). I am getting the ERROR:root:FATAL: remaining connection slots are reserved for non-replication superuser connections I am creating coroutines add adding them to running the asyincio loop # Helper Class class ModelsHelper: @staticmethod @sync_to_async def __handle_resource_data(data): // Some calculation to create kwargs dict return Resource.objects.get_or_create(**kwargs) async def store_data(metric): // some calculation to get data return await ModelsHelper.__handle_resource_data(data) # Main File def get_event_loop(): loop = None try: loop = asyncio.get_event_loop() except Exception as e: print(" New Event Loop ".center(50, '*')) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) return loop loop = get_event_loop() future = asyncio.ensure_future( asyncio.gather(*[ModelsHelper.store_data(metric) for metric in metrics]), loop=loop ) loop.run_until_complete(future) -
Fetch all record from model and it's related model
Say for example I have two table, Author and Books. class Author (models.Model ): name = models.CharField(...) class Book (models.Model ): author_id = models.ForeignKey('Author') book_name = models.CharField(...) Author table will contain the entry of authors irrespective of if they have written any book. And also one author can have multiples books. So I want to query all the authors name with their respective written books ( containing book_name ) even if they haven't written any book. -
Using a variable to for loop using django
I'm very new to python and django framework. I'm facing a minor issue of not being able to assign a variable to my for loop. In my html file there are buttons and a list (rendered using a loop). for ex: Buttons <li><a class="layer-item" href="#" onclick="selectLayer('base')" title="Base layer">Base layer</a></li> <li><a class="layer-item" href="#" onclick="selectLayer('soil')" title="Soil layers">Soil layers</a></li> Inside script tags i'm updating the variable value as <script> var layerType = ""; function selectLayer(layer){ layerType = layer; } </script> Also i have a loop like following in the same html file {% for layer in base %} <div class="col-4"> <span class="base-layer-title d-block">{{layer.title}}</span> </div> {% endfor %} Here i want to replace base according the button clicked. For ex: <a class="layer-item" href="#" onclick="selectLayer('soil')" title="Soil layers">Soil layers</a> Clicking on the above button should make the for loop as {% for layer in soil %} <div class="col-4"> <span class="base-layer-title d-block">{{layer.title}}</span> </div> {% endfor %} From i read you can do something like this to assign a value to a variable. {% with name="World" %} But not sure how to implement it in my issue. Any help is appreciated -
Handle HTTP Status Codes using @json_response decorator
Im looking for a solution to handle HTTP status codes using @json_response decorator from Django. Actually I use the view in this form: @json_response def any_view(request): return {'this will be': 'JSON'} But this always returns the 200 OK status code. It's possible to handle this status code? Thanks in advance. PD: I know how to use the return JsonResponse({'this will be': 'JSON'}, status=200) solution. But this not uses the decorator. -
Django - How to call a view function from an OnChange event in html template?
Django Newbie here. So basically when a user fills the first input field (eg. his name), I want to populate other fields automatically from data stored in database(eg. his age, height, weight etc.). For this, my logic is to use onchange event listener on the name input field and when it is triggered, the name value should be passed to a view function. The database is queried for the required results. Finally the data from query is displayed in html template fields. Hence, I would like to know how to call view functions based on onChange event. -
TypeError: Direct assignment to the reverse side of a related set is prohibited. Use thumbnails.set() instead
I'm trying to get my serializer to work but I've run into this error: TypeError: Direct assignment to the reverse side of a related set is prohibited. Use thumbnails.set() instead. And I'm not sure how to fix it. I've tried googling the problem but only found this docs which I have no idea of how to implement in my code: class YoutubeSnippetSerializer(serializers.ModelSerializer): thumbnails = YoutubeThumbnailSerializer(many=True) class Meta: model = YoutubeSnippet fields = ['publishedAt', 'channelId', 'title', 'thumbnails', 'channelTitle', 'liveBroadcastContent', 'publishTime'] def create(self, validated_data): thumb_data = validated_data.pop("thumbnails") snippet = YoutubeSnippet.objects.create(**validated_data) YoutubeThumbnails.objects.create(snippet=snippet, size="default", **thumb_data.pop("default")) YoutubeThumbnails.objects.create(snippet=snippet, size="medium", **thumb_data.pop("medium")) YoutubeThumbnails.objects.create(snippet=snippet, size="high", **thumb_data.pop("high")) return snippet The problem arises when the thumbnails variable is added. (thumbnails = YoutubeThumbnailSerializer(many=True) & 'thumbnails') Code: class YoutubeVideoSerializer(serializers.ModelSerializer): youtubeId = YoutubeIdSerializer(many=True) snippet = YoutubeSnippetSerializer(many=True) class Meta: model = YoutubeVideo fields = ['kind', 'etag', 'youtubeId', 'snippet'] def create(self, validated_data): id_data = validated_data.pop("youtubeId") snippet_data = validated_data.pop("snippet") video = YoutubeVideo.objects.create(**validated_data) for data in id_data: YoutubeId.objects.create(youtubeVideo=video, **data) for data in snippet_data: YoutubeSnippet.objects.create(youtubeVideo=video, **data) return video class YoutubeThumbnailSerializer(serializers.ModelSerializer): class Meta: model = YoutubeThumbnails fields = ['url', 'width', 'height'] Models: class YoutubeVideo(models.Model): kind = models.CharField(max_length=255, null=True) etag = models.CharField(max_length=255, null=True) class YoutubeSnippet(models.Model): publishedAt = models.DateTimeField(null=True) channelId = models.CharField(max_length=255, null=True) title = models.CharField(max_length=1084, null=True) channelTitle = models.CharField(max_length=255, null=True) liveBroadcastContent … -
I done a todo list using Django
I done a todo list using Django. My problem is after deploy my to app to heroku. When I change my "Debug=true" to "Debug=false" my app wont working. Tasks that are written in my mobile are also visible in my friend mobile as well. Any help. -
Django Rest Framework endpoint for total current visitor online
I am trying to implement total current visitor online with django rest framework. I found many tutorial and those for django and html server side rendering. But i am using django rest framework and reactjs in frontend. I am trying to show total current visitor online. What is the best possible way to show this? -
I have a problem in testing the django model values attached to signals
Scanario: #tests.py class TestModelValues(TestClass): @classmethod def setUpTestData(cls): cls.a = modelA.objects.create(...) #also creating its respective foreign key instances cls.b = modelB.objects.create( fk_attribute = cls.a, attr_x = 10, #involved in the problem ) #this is optional info abt my problem, included just in case :D def test_modelC_instance_is_created_on_creation_of_modelB_instances(self): #post_save signal in signals.py to create modelC instances modelB_count = modelB.objects.count() modelC_count = modelC.objects.count() self.assertEquals(modelB_count,modelC_count) #and a for loop to check if the instances of modelB in model C exists and saved properly #this workes fine #the problem def test_modelC_is_updated_on_updation_of_modelB_instances(self): #pre_save signal in signals.py to update it self.b.attr_x = 50 self.b.save() print(self.b.attr_x) #prints 50 correctly but #when i print the updated field in modelC below print(modelC.objects.get(OneToOneFieldToModelB__pk = self.b.pk).updated_attr) #This still prints 10 (the old value )while the print function in signals.py clearly changed it to 50 #THIS IS THE PROBLEM #assert line #signals.py #i have just shown the pre_save method here @receiver(pre_save, sender=modelB) def update_modelC_field(sender, instance, **kwargs): if instance.pk!=None: obj = modelC.objects.get(OneToOneFieldToModelB__pk=instance.pk) #code for updation obj.save() print(obj.updated_attr) #This prints 50 currently I tried using the refresh_from_db method, but that also showed no change. I am really new to testing in Django. I did not know how to create mock things and all. That's why I …