Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deploy each app of a Django project into different servers
For Example: I have developed a django Application which contains four apps inside called app_1, app_2, app_3 and app_4. Now I want to deploy app_1 on server_1, app_2 on sever_2, app_3 on server_3 and app_4 on server_4. Is it possible?? -
How to testing model.Serializer in pytest-django?
I'm trying to learn how to use tests in a DRF project, but I can't go out to test serializers, I can't add an image and primary keys, please show an example how you do it my test: def get_image(name='test.png', ext='png', size=(50, 50), color=(256, 0, 0)): file_obj = BytesIO() image = Image.new("RGBA", size=size, color=color) image.save(file_obj, ext) file_obj.seek(0) return File(file_obj, name=name) @pytest.mark.django_db def test_valid_poster_serializer(): valid_serializer_data = { "title": "new poster", "description": "poster description", "image": get_image(), "address": "foo", "phones": "89991234586", "price": 100, "site": "https://foo-bar.com/", "latitude": 123456.0, "longitude": 123456.0, "categories": { "title": "new" }, } serializer = PosterSerializer(data=valid_serializer_data) assert serializer.is_valid() assert serializer.validated_data == valid_serializer_data assert serializer.data == valid_serializer_data assert serializer.errors == {} error text: it looks like the image field expects nothing but in the model this field is required E Common items: E {'address': 'foo', E 'categories': OrderedDict([('title', 'new')]), E 'description': 'poster description', E 'latitude': 123456.0, E 'longitude': 123456.0, E 'phones': '89991234586', E 'price': 100, E 'site': 'https://foo-bar.com/', E 'title': 'new poster'} E Differing items: E {'image': None} != {'image': <File: test.png>} E Full diff: E { E 'address': 'foo', E - 'categories': {'title': 'new'}, E + 'categories': OrderedDict([('title', 'new')]), E 'description': 'poster description', E - 'image': <File: test.png>, E + 'image': … -
"<ClaimDocument: test>" needs to have a value for field "id"
After adding ManyToMany field to ClaimDocument I'm getting this error: "<ClaimDocument: test>" needs to have a value for field "id" before this many-to-many relationship can be used. But I have no test field in my ClaimDocument model. Here are my codes: models.py: class Document(models.Model): created_date = models.DateTimeField(default=timezone.now) added_by = CurrentUserField() assigned = models.ManyToManyField(CustomUser, related_name='assigned', blank=True, null=True) forms.py: class CreateClaimDocumentForm(ModelForm): def save(self, commit=False): document = super(CreateClaimDocumentForm, self).save(commit=False) ClaimDocument.objects.create( assigned = document.assigned, ... -
Error the requested resource was not found on this server after reverse proxying Nginx+Docker+Django project
I am having a problem when I attempt to access localhost/auth/ this is possibly because of the nginx configuration or may be another other issue. The following is the result I get from nginx logs after attempting to make a request to the proxied address localhost/auth/ reverse-proxy | 0.0.0.0 - - [28/Aug/2020:08:21:47 +0000] "GET /api/ HTTP/1.1" 404 159 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) When I access http://localhost/admin/ the Admin login page renders as expected as shown below. Also at http://localhost/doc/ the redocs documentation page renders as well. Project Structure ├── nccggbot │ ├── chatbot/ │ └── core/ │ │ ├── __init__.py │ │ ├── asgi.py │ │ ├── settings.py │ │ ├── urls.py │ │ ├── wsgi.py │ ├── static/ │ │ ├── admin/ │ │ ├── django_extensions/ │ │ |── drf-yasg │ │ ├── rest_framework │ │ │ ├── Dockerfile │ ├── manage.py │ ├── requirements.txt │ │ ├──reverse_proxy/ │ ├── default.conf │ └── Dockerfile ├──docker-compose-deploy.yml ├──README.md core/urls.py from django.contrib import admin from django.urls import include,path from drf_yasg.views import get_schema_view from drf_yasg import openapi from rest_framework import permissions from django.conf import settings from django.conf.urls.static import static schema_view = get_schema_view( openapi.Info( title="NCCG ChatBot API", … -
PostgresQL Altering BigAutoField on large table
I am currently trying to alter a normal Autofield to a Bigautofield using PostgesQL (and Django as framework). The process is going on for one day now and it seems that this is going to take forever as my database reached 2.147.483.647 rows. Is there any workaround to shift around this issue? Any hacks? Thanks in advance -
How to insert a foreign key dynamically after or before POST request Pyton Django
I am trying to assign foreign key during runtime,dynamically. I want that each user that is logged in can add new contacts to his own list. I understand that i need to use foreign key with Many-To-One relationship but I don't know how to implement this. The main goal is to assign the new contact that is added to the user that is logged in and adding him right now,I need to connect between them. model.py from django.db import models from django.contrib.auth.models import User class UserProfileInfo(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,blank=True,null=True,editable=False) #model calss to add adinonal info that the default user does not have #for ex: llike titles Titles = ( ("1", "Mr"), ("2", "Mrs"), ("3", "Miss"), ("4", "Dr"), ("5", "Prof")) Title=models.CharField(max_length=1,choices=Titles,blank=False,default=Titles[0]) first_name=models.CharField(max_length=128,blank=False) last_name=models.CharField(max_length=128,blank=False) def __str__(self): return self.user.username forms.py from django import forms from first_app.models import UserProfileInfo,Login,newContactInfo from django.contrib.auth.models import User class newUserForm(forms.ModelForm): class Meta: model=UserProfileInfo fields='__all__' class loginForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model=Login fields="__all__" class UserForm(forms.ModelForm): password=forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields=('username','email','password') class ContactForm(forms.ModelForm): class Meta: model = newContactInfo exclude=['user_profile_info'] views.py def contact(request): if request.method == "GET": contact_form = ContactForm() return render(request,"first_app/add_contact.html",context={'add_contact':contact_form}) if request.method=="POST": add_contacts_form = ContactForm(request.POST) # contact profileNameForm = newUserForm(request.POST, request.FILES) if add_contacts_form.is_valid() and profileNameForm: new_record = add_contacts_form.save(commit=False) new_record.user_profile_info=profileNameForm … -
Attempt to connect react admin and django via graphql. What is the problem?
React settings are taken from https://www.npmjs.com/package/ra-data-graphql-simple // in App.js import * as React from 'react'; import { Component } from 'react'; import buildGraphQLProvider from 'ra-data-graphql-simple'; import { Admin, Resource, ListGuesser } from 'react-admin'; import { CountryList } from './countries'; class App extends Component { constructor() { super(); this.state = { dataProvider: null }; } componentDidMount() { buildGraphQLProvider({ clientOptions: { uri: 'http://localhost:8000/graphql/' }}) .then(dataProvider => this.setState({ dataProvider })); } render() { const { dataProvider } = this.state; if (!dataProvider) { return <div>Loading</div>; } return ( <Admin dataProvider={dataProvider}> <Resource name="countries" list={ListGuesser} /> </Admin> ); } } export default App; Django Settings: //in project/app/schema.py import graphene from graphene_django.types import DjangoObjectType from .models import Organization, Project, Country class CountryType(DjangoObjectType): class Meta: model = Country fields = ("id", "title") class CreateCountry(graphene.Mutation): id = graphene.Int() title = graphene.String() class Arguments: title = graphene.String() def mutate(self, info, title): country = Country(title=title) country.save() return CreateCountry( id=country.id, title=country.title, ) class InforgMutation(graphene.ObjectType): create_country = CreateCountry.Field() class InforgQuery: countries = graphene.List(CountryType) country = graphene.Field(CountryType, pk=graphene.Int()) def resolve_countries(self, info, **kwargs): print(info) return Country.objects.all() def resolve_country(self, info, **kwargs): if 'pk' in kwargs: return Country.objects.get(pk=kwargs['pk']) return None // Djago settings GRAPHENE = { 'SCHEMA': 'config.schema.schema', } //in project/main_schema.py import graphene from app.schema import InforgQuery, … -
Django - RichText - Ckeditor - how to update content on site
I spent a lot of time trying to solve the issue but I am not able to find some good tutorial on how to update data in CKEditor on the site (not in the admin of Django) I am using the normal text field or textbox, I will just load get the data and put it under attribute value and the site will display it in the textbox, then I can edit it and post it back. But I am struggling with how to put data from the model to view and view it on-site in CKEditor, so I can change it. My environment looks like this: Forms.py class TestingContent(forms.ModelForm): content = forms.CharField(widget=CKEditorWidget( attrs={ 'width':'100%', } ) ) Models.py class GITCTesting(models.Model): text = RichTextField(default="Not_set") . . . View.py def gitc_testing_detail(request, Testing_id, GITC_id): gitctask = GITCTask.objects.filter(Q(idofgitc=GITC_id) & Q(related_control_id=Testing_id)) gitccontrol = GITCTesting.objects.get(Q(idofgitc=GITC_id) & Q(id=Testing_id)) post = get_object_or_404(GITCTesting, id=Testing_id) form = TestingContent(request.POST or None, request.FILES or None, instance=post) return render(request, 'rc_new/rcda_testing_detail.html', menu_contex) HTML template <div class="row"> {{ form.media }} {{ form.content}} </div> I basically tried to make "instance=post" in the form in view but I get and that it is not expected argument. I tried to change some code and get another error … -
DRF create method in viewset or in serializer
What is the difference between customizing the "create" method in DRF viewset or customizing it in the serializer? I understand the serializer is responsible to deserialize the data, i.e. the way the data is presented in the POST query; however, I can also create objects in related fields in the serializer. #views.py def create(self, request): pass #serializer.py def create(self, validated_data): return Model.objects.create(**validated_data) When should I customize views/create vs. serializer/create? -
Do you have any suggestion about my database structure?
According to my project, I have the following tables Bot -> Spider -> Market ->{Product,Trade}(Sub Tables) Bot: Bot_name Spider: Spider_class,spider_name Market: market_name, market_url,Market_location Trade: exchange_rate, currency Product: product_name, price, quantity So I am using Django and MySQL and I try like this: class market(models.Model): market_name = models.CharField(max_length=50,verbose_name="Market Name") market_url = models.CharField(max_length=50,verbose_name="market Link") market_location = models.CharField(max_length=50,verbose_name="Shop location") class product(models.Model): product_name = models.ForeignKey(market,on_delete=models.CASCADE) price = models.CharField(max_length=50,verbose_name="Price") quantity = models.CharField(max_length=200,verbose_name="Quantity") First I try something about a foreign key but after migration, it gives me product_name_id on MySQL and I just want to write product_name and I want to get all product_name's information from the market. So I couldn't figure out how to prepare the structure of my database. -
What is the best way to change the hash password on new Django?
Bcryptpasswordhasher was removed on Django2.1. https://docs.djangoproject.com/en/3.1/releases/2.1/#removed-bcryptpasswordhasher-from-the-default-password-hashers-setting How should I change the password of existing user? Should I switch to another hasher and then let the user change the password? Also, which hasher is best to use? -
The requested resource was not found on this server error while deploying Django/VueJs app on Heroku
I have been able to deploy my django/vuejs app on heroku successfully. The Django backend uses the django rest framework to serve the api endpoints while vuejs handles the frontend. I have set up the app on Heroku, added NodeJs and Python buildpacks, and then added my config vars. However, when i try to open the app on browser, i get Not Found. The requested resource was not found on this server.. heroku logs --tail shows the following: 2020-08-28T07:58:53.956114+00:00 app[web.1]: tmp_upload_dir: None 2020-08-28T07:58:53.956114+00:00 app[web.1]: secure_scheme_headers: {'X-FORWARDED-PROTOCOL': 'ssl', 'X-FORWARDED-PROTO': 'https', 'X-FORWARDED-SSL': 'on'} 2020-08-28T07:58:53.956115+00:00 app[web.1]: forwarded_allow_ips: ['*'] 2020-08-28T07:58:53.956115+00:00 app[web.1]: accesslog: - 2020-08-28T07:58:53.956115+00:00 app[web.1]: disable_redirect_access_to_syslog: False 2020-08-28T07:58:53.956116+00:00 app[web.1]: access_log_format: %(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" 2020-08-28T07:58:53.956116+00:00 app[web.1]: errorlog: - 2020-08-28T07:58:53.956117+00:00 app[web.1]: loglevel: debug 2020-08-28T07:58:53.956118+00:00 app[web.1]: capture_output: False 2020-08-28T07:58:53.956118+00:00 app[web.1]: logger_class: gunicorn.glogging.Logger 2020-08-28T07:58:53.956119+00:00 app[web.1]: logconfig: None 2020-08-28T07:58:53.956119+00:00 app[web.1]: logconfig_dict: {} 2020-08-28T07:58:53.956119+00:00 app[web.1]: syslog_addr: udp://localhost:514 2020-08-28T07:58:53.956120+00:00 app[web.1]: syslog: False 2020-08-28T07:58:53.956120+00:00 app[web.1]: syslog_prefix: None 2020-08-28T07:58:53.956120+00:00 app[web.1]: syslog_facility: user 2020-08-28T07:58:53.956121+00:00 app[web.1]: enable_stdio_inheritance: False 2020-08-28T07:58:53.956121+00:00 app[web.1]: statsd_host: None 2020-08-28T07:58:53.956121+00:00 app[web.1]: dogstatsd_tags: 2020-08-28T07:58:53.956122+00:00 app[web.1]: statsd_prefix: 2020-08-28T07:58:53.956122+00:00 app[web.1]: proc_name: None 2020-08-28T07:58:53.956122+00:00 app[web.1]: default_proc_name: mysite.wsgi 2020-08-28T07:58:53.956123+00:00 app[web.1]: pythonpath: mysite 2020-08-28T07:58:53.956123+00:00 app[web.1]: paste: None 2020-08-28T07:58:53.956124+00:00 app[web.1]: on_starting: <function OnStarting.on_starting at 0x7f10994d2488> 2020-08-28T07:58:53.956124+00:00 app[web.1]: on_reload: <function OnReload.on_reload at 0x7f10994d2598> 2020-08-28T07:58:53.956125+00:00 … -
How to use easy-thumbnails with static in template?
I wonder how (if it is possible) load thumbnail for static files with easy-thumbnails package. I tried: <img src="{% thumbnail 'img/V.png' 50x0 %}" /> <img src="{% thumbnail static 'img/V.png' 50x50 %}" /> <img src="{% static thumbnail 'img/V.png' 50x50 %}" /> but nothing works. -
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.