Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Foreign key reference disappears on save
In a simple model structure like that: class News(models.Model): name = models.CharField(max_length=50) class Book(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey('News', on_delete=models.CASCADE) I'm having a problem when assigning ForeignKey "parent" field. Its value disappears when I'm trying to save an object: >>> news = News(name='TestNews') >>> book = Book(name='TestBook', parent=news) >>> news.save() >>> str(book.parent) 'News object (2)' >>> book.save() Traceback (most recent call last): File "...\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "...\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: sample_book.parent_id It's there right before saving, but it's gone on save. It works fine when (re)assigning parent after saving the first object, but in the actual project I need to call bulk_save or at least use transaction.atomic >>> news = News(name='TestNews') >>> news.save() >>> book = Book(name='TestBook', parent=news) >>> book.save() >>> book.parent <News: News object (3)> The strangest thing is that I'm sure that it worked the other day with the bulk_save and there is a lot of similar examples in the docs. -
Django prefetch_related
I have a relational model set that has 5 tables each with a one to many relationship. I'm having trouble accessing model information after the 2nd table. ex. class TableA(models.Model): pass class TableB(models.Model): tablea = models.ForeignKey(TableA, oncascade...) class TableC(models.Model): tableb = models.ForeignKey(TableB, oncas...) class TableD(models.Model): tablec = models.ForeignKey(TableC, ...) class TableE(models.Model): tabled = models.ForeignKey(TableE, ...) In my views.py i'm using the prefetch related method on TableA: from . models import * data = TableA.objects.all().prefetch_related('tableb_set__tablec_set__tabled_set') I can't seem to access information from TableC, TableD or TableE. for a in data: print(a.id) for b in a.tableb_set.values(): print(b['id]) for c in b.tablec_set.values(): #This is where I get an error message stating the model doesn't have a relatedmanager How can I access model information 2+ tables deep into the prefetch_related relationship? Thanks in advance -
Can you run a raw MySQL query in Django without a model?
I am still learning Django and I'm just now getting into connectors to MySQL. What I'm trying to figure out is how I would go about querying a db/table that I am not creating with a model in Django. Do I have to recreate the table as a model in order to have it talk to Django? If so, would that basically mean just recreating my structure with a model then importing my data to the new table? Sorry if this is a goofy question, I appreciate any help you can give! -
Are Django Sessions Completely Unique?
I am using Django Sessions to store price for Stripe based on a form input (if this is bad please advise). if form.is_valid(): srv = form.cleaned_data['service'] if srv == 'Silver': request.session['price'] = 999999 else: request.session['price'] = 100000 return redirect('pay-now') Now, obviously, the price is going to be variable, I want to know if sessions are completely unique to each individual, and I won't encounter any errors in terms of people being charged the wrong price based on a previous session store etc. Thanks in advance! -
i am trying to send data through postman and it takes one field null. So anyone can help me in that. And also i am beginner to django
this is the error django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (6, MBBS, Orenburg University, 2019, null). My models is: class Educations(models.Model): user = models.ForeignKey(MyUser, on_delete=models.CASCADE, related_name='edu_user') doctor_degree = models.CharField(max_length=25) university = models.CharField(max_length=25) passing_year = models.IntegerField() def str(self): return self.doctor_degree here the user is for doctor and i'am taking its foreign key in education model and its viewset is: class EducationViewSet(viewsets.ViewSet): def list(self,request): eduss=Educations.objects.all() edu_data_list=[] for edu in eduss: edu_data_list.append({ "doctor_degree" : edu.doctor_degree, "university" : edu.university, "passing_year" : edu.passing.year, "doctor_name" : edu.user.full_name, "doctor_mobile_number": edu.user.mobile_number, "doctor_date_of_birth": edu.user.date_of_birth, "doctor_blood_group": edu.user.blood_group, "doctor_email": edu.user.email }) return Response({"eduss":edu_data_list}) def create(self,request): doctor_degree = request.data.get('doctor_degree') university = request.data.get('university') passing_year = request.data.get('passing_year') user = request.user education = Educations() education.doctor = user education.doctor_degree = doctor_degree education.university = university education.passing_year = passing_year education.save() return Response("successfully saved") -
Django / FactoryBoy - Overriding lazy_attributes
I'm working on a Django project for which I've created the following factory: class PurchaseFactory(factory.DjangoModelFactory): class Meta: model = 'core.Purchase' amount = decimal.Decimal(random.randrange(100, 100000) / 100) ( .... ) user = factory.SubFactory(UserFactory) @factory.lazy_attribute def date(self): if not self.date: return timezone.now() else: return self.date For which I'm running the following test: class TestGetBalanceForPeriod(TestCase): def setUp(self) -> None: self.user: User = UserFactory() self.purchase_1: Purchase = PurchaseFactory( user=self.user, date=timezone.datetime(2019, 11, 1), amount=10 ) def test_test_setup(self) -> None: self.assertEqual(self.purchase_1.date, timezone.datetime(2019, 11, 1)) As you can see I've overridden the date field on the PurchaseFactory with an lazy_attribute. However, in this specific test I'm attempting to set the date myself. I imagined factoryboy would override all values with the values provided by the users, but the test fails with the following error: AssertionError: datetime.datetime(2019, 11, 22, 16, 15, 56, 311882, tzinfo=<UTC>) != datetime.datetime(2019, 11, 1, 0, 0) The first date is the results of the timezone.now() call and not the date that I provided as an input. So far I've been able to override all values on the many factories in our project without problems - but I'm unable to solve this problem. Does anyone know what I am doing wrong? -
using AWS Elastic search with VPC endpoint django haystack
I want to use AWS Elastic-search service with my django application which is running on EC2 instance. For that I use the settings - HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch5_backend.Elasticsearch5SearchEngine', 'URL': 'https://vpc-ES-CLUSTER.ap-south-1.es.amazonaws.com:9200/', 'INDEX_NAME': 'haystack', 'INCLUDE_SPELLING':True, }, } I am not even able to set the connection. Here I am getting this error - raise ConnectionError('N/A', str(e), e) elasticsearch.exceptions.ConnectionError: ConnectionError((, 'Connection to vpc-ES-CLUSTER.ap-south-1.es.amazonaws.com timed out. (connect timeout=10)')) caused by: ConnectTimeoutError((, 'Connection to vpc-ES-CLUSTER.ap-south-1.es.amazonaws.com timed out. (connect timeout=10)')) I have updated the access policy to allow the user for edit and list, also in security group add the port 9200 TCP rule. How to connect ec2 with elastic search using VPC. -
Various issues running gunicorn with django app
I'm new to Django. Trying to get my app running under Nginx+gunicorn but running into a few issues. If someone has some insight, I'd appreciate it. I've found a few things to try on google, but gunicorn still seems hosed. 1) I've rsync'd my Django project from my dev box to the Nginx host. If I try launch using the dev server, it doesn't work unless I use Python 3. What have I got messed up? I've googled the ...from exec error below and found I could get it working if prefixed with python3. Seems like a workaround for a larger issue though since this way of starting it isn't mentioned in any of the tutorials I've been following. This bombs: (venv) $ python manage.py runserver 127.0.0.1:8777 File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax This works: (venv) $ python3 manage.py runserver 127.0.0.1:8777 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 22, 2019 - 15:46:59 Django version 2.2.7, using settings 'auth.settings' Starting development server at http://127.0.0.1:8777/ Quit the server with CONTROL-C. [22/Nov/2019 15:47:27] "GET /accounts/login/ HTTP/1.0" 200 1229 ^C(venv) $ 2) Above, I can run the app fine … -
Testing Django Rest Framework: how to test hyperlink relations?
I'm trying to create a true unit test for a customized DjangoRestFramework Hyperlinked related field. But I cannot seem to get around this error: django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "relatedtestmodel-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. And here is the unit test, stripped down to simplify the example: from django.conf.urls import url from django.test import TestCase, override_settings from api_tests.models import APITestModel, RelatedTestModel from api_tests.serializers import APITestModelSerializer def dummy_view(request, pk): pass urlpatterns = [ url(r'^relatedtestmodel/?P<pk>[a-zA-z0-9]/$', dummy_view, name='relatedtestmodel-detail') ] @override_settings(ROOT_URLCONF='tests.test_relations') class HyperlinkedRelatedFieldTestCase(TestCase): def setUp(self): self.parent = APITestModel.objects.create() self.child = RelatedTestModel.objects.create(parent=self.parent) assert self.child.parent.id == self.parent.id def test_to_internal_value_correct_error_message(self): queryset = APITestModel.objects.all() serializer = APITestModelSerializer(queryset, many=True, context={'request': None}) expected = [{'foo': 'bar'}] self.assertEqual(serializer.data, expected) I more or less lifted the test from https://github.com/encode/django-rest-framework/blob/master/tests/test_relations_hyperlink.py, because I figured who knows best how to unit test DRF than the makers of DRF? But as it stands, my test refuses to run. Notice in particular that I override the settings with a custom urlpatterns (which is this same file, hence the urlpatterns at the top). So I don't understand why DRF thinks that url name doesn't exist - … -
Django, use Subqueries instead of filtering on QuerySet converted to list
I have two related models: class Execution(models.Model): name = models.CharField("Test Suite Name", max_length=1024) <...> class TestCase(models.Model): name = models.CharField("Test Case Name", max_length=1024) result = models.CharField("Test Case Result", max_length=32) execution = models.ForeignKey(Execution, on_delete=models.CASCADE) <...> I need to compare two executions, devising a list of test-cases which have result discrepancies. My approach feels pythonic enough and works reasonably fast, but I'm pretty sure this can be improved with Django Subqueries (or may be Exists()?) Here is the code I have: execution1 = Execution.objects.get(id=id1) # Executions retrieval (irrelevant to the question) execution2 = Execution.objects.get(id=id2) execution1_testcases = execution1.testcase_set.all() execution1_testcases_names = [testcase.name for testcase in execution1_testcases] for testcase2 in execution2.testcase_set.order_by('-result', 'name'): if testcase2.name in execution1_testcases_names: # TODO: this most likely can be improved with Subqueries result1 = list(filter(lambda testcase1: testcase1.name == testcase2.name, execution1_testcases))[0] else: result1 = None if result1 != testcase2.result: <...> # discrepancy processing -
GraphQL response error message from DRF serializer
I can make CRUD in GraphQL using Django as a backend. My Mutation is meta class is based on DRF serializer. I had search with term DRF, GraphQL, serializer, ... etc. Most of the will be topic related to make the endpoint, but it does not go to detail of response the error message. And most of the time I found DRF without GraphQL answer class Question(models.Model): question_text = models.CharField(max_length=50) class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ( 'id', 'question_text', ) class QuestionSerializerMutation(SerializerMutation): class Meta: serializer_class = QuestionSerializer model_operation = ['crated', 'update'] lookup_field = 'id' class Mutation(graphene.ObjectType): xxx = QuestionSerializerMutation.Field() Body mutation{ xxx(input: {questionText: "a;lsfjkdsajfdsjf;sjfsajdfkd;lsafjl;asfdsjf;lajflsadjf;alsjf;lasfsj"}){ id questionText } } Expected result: GraphQL return the error message from Serializer because my payload is exceed 50 characters As is: No error message raises { "data": { "xxx": { "id": null, "questionText": null } } } Question: How response with serializer.error in GraphQL? -
API view is empty when Filtering django rest framework view by PK in urls.py
I am trying to filter my APIListView by a PK value specified in the url. The code runs however my API is empty even though i know it has data at the PKs that i am testing. Any Ideas? Models.py class Item(models.Model): Description = models.CharField(max_length=20) Price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.Description Serializers.py class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('pk', 'Description', 'Price') Views.py (API) class SingleItemAPIView(generics.ListAPIView): serializer_class = ItemSerializer def get_queryset(self): item = self.request.query_params.get('pk', None) queryset = Item.objects.filter(pk=item) return queryset Urls.py urlpatterns = [ path('<int:pk>/',SingleItemAPIView.as_view(), name='single_object_view') ] DRF Output GET /api/1/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [] -
Django Categories and Breadcrumbs Issues
Everything works normally on the admin side. However, I could not show the categories and breadcrumbs on front site. I'd appreciate it if you could help me. models.py from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Post(models.Model): title = models.CharField(max_length=120) category = TreeForeignKey('Category',null=True,blank=True) content = models.TextField('Content') slug = models.SlugField() def __str__(self): return self.title class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_together = (('parent', 'slug',)) verbose_name_plural = 'categories' def get_slug_list(self): try: ancestors = self.get_ancestors(include_self=True) except: ancestors = [] else: ancestors = [ i.slug for i in ancestors] slugs = [] for i in range(len(ancestors)): slugs.append('/'.join(ancestors[:i+1])) return slugs def __str__(self): return self.name admin.py from mptt.admin import MPTTModelAdmin admin.site.register(Post,PostAdmin) admin.site.register(Category, DraggableMPTTAdmin) settings.py MPTT_ADMIN_LEVEL_INDENT = 20 #you can replace 20 with some other number urls.py path('category/<path:hierarchy>.+', views.show_category, name='category'), views.py def show_category(request,hierarchy= None): category_slug = hierarchy.split('/') parent = None root = Category.objects.all() for slug in category_slug[:-1]: parent = root.get(parent=parent, slug = slug) try: instance = Category.objects.get(parent=parent,slug=category_slug[-1]) except: instance = get_object_or_404(Post, slug = category_slug[-1]) return render(request, "post/detail.html", {'instance':instance}) else: return render(request, 'post/categories.html', {'instance':instance}) templates/categories.html {% extends 'base.html' %} {% load static %} {% block head_title %} {{ instance.name … -
Django customized user model.... where does user.model(...) come from?
So, I am working my way through the jungle of the django documentation in order to create an online classifieds app. Since users are supposed to be anble to post their own classifieds online, I need to make use of the user authentication system. However, they need to be able to log in by email instead of username, which is why I need to come up with a customized user model. Now, the example walk-through thats contained in the django documentation seems helpful: https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#a-full-example In order to understand django better, I am trying to go through the example line by line, and there is a point that I don't quite get: class MyUserManager(BaseUserManager): def create_user(self, email, date_of_birth, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, ) I don't get where the "self.model(...)" comes from. Is it a method? I cannot find it in BaseUserManager... where is it defined? I don't even quite know how to phrase the question precisely because I'm so puzzled about it... could anybody just enlighten me about what we are defining here … -
How do i do a POST request in django rest framework with this model structure
i am new in django and django rest framework , i am trying to send an object with POST, but i don´t know why why it's failing, this are my models: class Region(models.Model): id_region = models.AutoField(primary_key=True) name_region = models.CharField(max_length=255) def __str__(self): return self.name_region class DataTicker(models.Model): id_data_ticker = models.AutoField(primary_key=True) ytd = models.FloatField() expense_ratio = models.FloatField() price_earnings_ratio = models.FloatField() price_book_ratio = models.FloatField() aum_ticker = models.FloatField() price = models.FloatField() nav = models.FloatField() bid_ask = models.FloatField() premiun_discount = models.FloatField() date= models.DateTimeField(auto_now=False) region_id_fk = models.ForeignKey(Region,on_delete=models.CASCADE) geography_id_fk = models.ForeignKey(Geography,on_delete=models.CASCADE) def __str__(self): return str(self.id_data_ticker) class Ticker(models.Model): id_number = models.AutoField(primary_key=True) ticker_id = models.CharField(max_length=100) index_tracked = models.CharField(max_length=255) fund = models.CharField(max_length=255) focus = models.CharField(max_length=255) inception_date= models.DateTimeField(auto_now=False) asset_id_fk = models.ForeignKey(AssetClass,on_delete=models.CASCADE) data_tickers = models.ManyToManyField(DataTicker) def __str__(self): return self.ticker_id And this are my serializers class RegionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Region fields = ('id_region','name_region','geography_id_fk') class DataTickerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = DataTicker fields = ('id_data_ticker','ytd','expense_ratio','price_earnings_ratio', 'price_book_ratio','aum_ticker','price','nav','bid_ask','premiun_discount','date','region_id_fk','geography_id_fk') region_id_fk = serializers.SerializerMethodField('get_region_id_fk') geography_id_fk = serializers.SerializerMethodField('get_geography_id_fk') def get_region_id_fk(self,obj): return obj.region_id_fk.name_region def get_geography_id_fk(self,obj): return obj.geography_id_fk.name_geography class TickerSerializer(serializers.ModelSerializer): #data_tickers = serializers.PrimaryKeyRelatedField(queryset=DataTicker.objects.all(), many=True) data_tickers = DataTickerSerializer(many=True, read_only=True) class Meta: model = Ticker fields = ('id_number','ticker_id','index_tracked','fund', 'focus','inception_date', 'asset_id_fk','data_tickers') asset_id_fk = serializers.SerializerMethodField('get_asset_id_fk') def get_asset_id_fk(self,obj): return obj.asset_id_fk.name_asset And this is the object that i am trying to send: var obj = { "ticker_id": "TEST", … -
django filter on listed jsonfield to return exact list object
We have a postgres JSONField class Demo_Model(models.Model): urls_results = JSONField(blank=True,null=True,default=dict) from mainapp.models import Demo_Model j1 = [{"name":"John","age":"15"},{"name":"cena","age":"21"}] j2 = [{"name":"Shawn","age":"9"},{"name":"Michale","age":"19"}] Demo_Model(urls_results=j1).save() Demo_Model(urls_results=j2).save() Now we have inserted our JSON data into 2 objects for Demo_Model, When we filter out the results based on keys and values of json data of urls_results field. >>> x = Demo_Model.objects.filter(urls_results__contains=[{"name":"cena"}]) >>> x <QuerySet [<Demo_Model: Demo_Model object (1)>]> >>> for eachx in x: ... print(eachx.urls_results) ... [{'age': '15', 'name': 'John'}, {'age': '21', 'name': 'cena'}] it filters based on key and value and returns the matched object. How do I filter just matched json part from the result list, instead of entire field. FROM THIS [{'age': '15', 'name': 'John'}, {'age': '21', 'name': 'cena'}] TO JUST MATCHED OBJECT PART of DICT {'age': '21', 'name': 'cena'} I know we can just run a for loop across the resultant objects to match and return. for eachx in x: for key,val in eachx.items(): if key == 'name' & val == 'cena': return eachx But it's a problem when we have a large list of urls_results, I'm looking for another way instead of looping around, what is the most effective /fast way to solve this problem? -
Django: I get `duplicate key value violates unique constraint` even if I have provided instance to ModelForm
I have a model as follows: class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) '''Basic Info''' name = models.CharField( max_length=100, verbose_name='name', null=True) alias_name = models.CharField( max_length=100, verbose_name='alias name', blank=True, null=True) last_name = models.CharField( max_length=100, verbose_name='last name', null=True) And a simple view to create or update this basic info as follows: class PersonalInfoCreateUpdateView(View): def post(self, request, *args, **kwargs): logger.info("posting a request.") instance = Person.objects.get(user=self.request.user) form = PersonalInfoForm(request.POST, request.FILES, instance=instance) # I am instantiating the form with a previous record if form.is_valid(): form.save() # Given that I have passed the instance to form, # I expect this to work but it does not. return redirect(reverse(self.post_redirect_url)) context['form'] = form return render(request, self.template_name, context=context) def get(self, request): instance, created = self.child_model.objects.get_or_create( user=self.request.user) form = PersonalInfoForm(instance=instance) context['form'] = form return render(request, self.template_name, context=context) And my form is: class PersonalInfoForm(ModelForm): class Meta: model = Person fields = ['name', 'alias_name', 'last_name'] and here's the error: Environment: Request Method: POST Request URL: http://localhost:8000/basic-info Django Version: 2.2.1 Python Version: 3.6.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_jalali', 'core', 'django_extensions'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/amir/.virtualenvs/owj/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute 84. return self.cursor.execute(sql, params) The above exception (duplicate key value violates unique constraint "core_person_user_id_key" DETAIL: Key … -
Resize image before upload django without saving
I am trying to crop and resize before uploading image, here is spinnet of my code - x,y,w,h = self.x, self.y, self.w, self.h image = Image.open(self.cleaned_data.get('profile_image')) try: for orientation in ExifTags.TAGS.keys() : if ExifTags.TAGS[orientation]=='Orientation' : break exif=dict(image._getexif().items()) if exif[orientation] == 3 : image=image.rotate(180, expand=True) elif exif[orientation] == 6 : image=image.rotate(270, expand=True) elif exif[orientation] == 8 : image=image.rotate(90, expand=True) except: pass cropped_image = image.crop((x, y, w+x, h+y)) resized_image = cropped_image.resize((160, 160), Image.ANTIALIAS) filename = 'image' new_image = InMemoryUploadedFile(resized_image,'ImageField',\ "%s.jpg" % filename , 'image/jpeg', resized_image.__sizeof__(), None) self.cleaned_data['profile_image'] = resized_image return super(UpdateUserProfileForm, self).save() this is not working, resized image is not saved instead original get saved. I have to save it in InMemoryUploadedFile because I am using AWS S3 bucket for media files and it doesn't support absolute path for saving images. Previously in development I am using this code - x,y,w,h = self.x, self.y, self.w, self.h try: image = Image.open(update_form.profile_image) for orientation in ExifTags.TAGS.keys() : if ExifTags.TAGS[orientation]=='Orientation' : break exif=dict(image._getexif().items()) if exif[orientation] == 3 : image=image.rotate(180, expand=True) elif exif[orientation] == 6 : image=image.rotate(270, expand=True) elif exif[orientation] == 8 : image=image.rotate(90, expand=True) except: pass cropped_image = image.crop((x, y, w+x, h+y)) resized_image = cropped_image.resize((160, 160), Image.ANTIALIAS) resized_image.save(update_form.profile_image.path) This was working fine but I need … -
Raising APIException in "update" Method of ModelSerializer does not Respond with Desired Status Code
I have a field that should not be updatable, which I've found out update method on ModelSerializer is the best to do that. What I do, pretty much, is to: def update(self, instance, validated_data): if "content" in validated_data: raise APIException( _("whatever error message is"), status.HTTP_403_FORBIDDEN, # or plain int, 403 ) return super().update(instance, validated_data) Oddly, the response's body is proper, which is: {"detail":"whatever error message is"} However, due to some unknown reason, it does not respond with status code 403, instead it responds with 500. 500 occurs when any exception is thrown during runtime in Django, yet the documentations of DRF clearly states that it especially handles APIException and responds accordingly. I do not know why it responds with 500. Environment Python 3.7.4 Django 2.2.7 Django Rest Framework 3.10.3 -
405 method not allowed while refreshing JWT Token - Django, Angular
I'm using JWT Authentication in my Django/Angular project and weird thing happens when I'm trying to get a new access token when the old one expired. I get a 405 POST METHOD NOT ALLOWED. I've set up corsheaders to allow all the methods and external hosts to access the app. The request looks fine as I'm sending the refresh token to get a new access token. What I've noticed is that it happens only on the pages which are sending POST request to django to access some data before displaying it. When I'm on a page that sends GET request or nothing, obtaining new token works perfectly good. Please take a look at the code and the responses. Error response settings.py CORS_ORIGIN_WHITELIST = ( '127.0.0.1:4200', '127.0.0.1:8082', ) CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] Handling 401 error and getting a new token in angular private handle401Error(request: HttpRequest<any>, next: HttpHandler ) : Observable<any> { if(!this.isRefreshing) { this.isRefreshing = true; this.refreshTokenSubject.next(null); return this.userService.refreshToken().pipe( switchMap((token:any) => { this.isRefreshing = false; this.refreshTokenSubject.next(token.access); return next.handle(this.addToken(request, token.access)); })); } else { return this.refreshTokenSubject.pipe( filter(token => token != null), take(1), switchMap(access … -
Choices in django
My Models: class Book(models.Model): # book types and placed BIOGRAFIA = 1 FANTASTYKA = 2 HISTORYCZNY = 3 HORROR = 4 POEZJA = 5 PRZYGODA = 6 ROMANS = 7 DRAMAT = 8 BRAK = 0 B00K_CHOICES = ( (BIOGRAFIA, 'Biografia'), (FANTASTYKA, 'Fantasy/Sci-Fi'), (HISTORYCZNY, 'Historyczny'), (HORROR, 'Horror'), (POEZJA, 'Poezja'), (PRZYGODA, 'Przygoda'), (ROMANS, 'Romans'), (DRAMAT, 'Dramat'), (BRAK, 'Brak informacji'), ) tytul = models.CharField(max_length=60, unique=True) autor = models.ForeignKey(Author, on_delete=models.CASCADE) opis = models.TextField(null=True, blank=True) gatunek = models.IntegerField(choices=B00K_CHOICES, default=BRAK) cena = models.DecimalField(max_digits=400, decimal_places=2) rok_wydania = models.DateField(null=True, blank=True) liczba_stron = models.PositiveIntegerField(null=True, blank=True) zdjecie = models.ImageField(null=False, blank=True, upload_to='zdjecia_ksiazek') przecena = models.BooleanField() def __str__(self): return self.tytul My View: def Gatunek(request, gatunek_id): ksiazki = Book.objects.filter(gatunek=gatunek_id) return render(request, 'ksiazki.html', {'ksiazki': ksiazki}) I don't think my view is too good, I don't know if it should also be {{gatunek. gatunek}} My template HTML: {% for ksiazki in ksiazki %} <div class="card" style="width: 500px"> <div class="card-body"> <img src="/media/{{ksiazki.zdjecie}}"> <div class="row"> <div class="col-sm-9"> <h2>{{ksiazki}}</h2> </div> <div class="col-sm-3"> <a href="{% url 'Edytuj_ksiazke' ksiazki.id %}"><i class="fas fa-2x fa-edit"></i></a> <a href="{% url 'Usun_ksiazke' ksiazki.id %}"><i class="fas fa-2x fa-trash-alt"></i></a> </div> </div> <p>{{ ksiazki.gatunek }} </p> <p>{{ ksiazki.opis }}</p> </div> </div> {% endfor %} It seems to me that I have a problem in Django when I … -
How to use request.path in Django View get_context_data?
I want to use last part of the url in get_context_data in the view. For example: if I have /foo/bar I want to get /bar in a variable in the view. def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx["url"] = request.path.split('/')[:-1] return ctx -
How could I query a MySQL DB to pull out all entries with an AD User's name in it while using Python/Django?
Long story short, we are running some cleanup processes on our Tableau Server environment. What I need to do is have users login to the Django page with LDAP (that's a battle for another day), then have a query run automatically that will display their workbooks in an html table. I already have the SQL DB being built, I just need to figure out how to display it to my users and how I will get it to return output in some way that flags a workbook for deletion. Any thoughts on this? PS, I am fairly new to Django and models in particular, Python not so much. -
Can I configure Django for Unit tests with restricted view on unmanaged databases?
We are a small team, trying to work with Django with a restricted access to a futurely unmanaged PostgreSQL database (i.e: only views and stored procedures ; no access to any tables) for security reasons. We tried to give (within Postgre) the user external_test the rights to create any tables inside his own schema on external, and to use the following settings (settings.py): ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'external': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgre_db', 'USER': 'external_user', 'PASSWORD': 'password', 'HOST': 'integration.project.net', 'PORT': '5432', 'TEST': { 'NAME': 'test_db', 'USER': 'external_test', 'PASSWORD': 'password', ... Using simple passing unit tests (project/app/tests/test_views.py): ... class InternalTest(TestCase): database = ['default'] def test_something(self): pass class StoredProcedureTest(TestCase): databases = ['external'] def test_one_procedure(self): with connections["external"].cursor() as cursor: cursor.callproc("some_procedure", [42, ]) pass ... If we try the first one with ./manage.py test app.tests.test_views.InternalTest → ok If we try the other one with ./manage.py test app.tests.test_views.StoredProcedureTest → circular dependency issue (ImproperlyConfigured: Circular dependency in TEST[DEPENDENCIES]) probably because it's skipping the configuration of default If we try both tests with ./manage.py test app.tests.test_views: → permission denied Creating test database for alias 'default'... Creating test database for alias 'external'... Got an error creating the test database: permission … -
Django Get Entries Separated by Month
I've got an object called entry. This object has a CharField, a DateField and a ForeignKey to a status. (The status could be "Error" or "Warning") I now want to do a page where the user can see how many entries with the status "Error" and "Warning" got created a certain number of months until today. I already got the logic that the url has a kwarg that shows the number of months. Here is what I have so far in my views.py: class graph_view(View, LoginRequiredMixin): def get(self, request, **kwargs): timeline = get_object_or_404(Timeline, id=kwargs.get('pk')) months = kwargs.get('months') The Result should look something like this: August: 5 Errors, 2 Warnings September: 4 Errors, 6 Warnings October: 0 Errors, 5 Warnings November: 2 Errors, 4 Warnings In the excample above the user selected that he wants to see the entries over the last 4 months. Does anyone have an idea how i can query these entries? Thanks for any help.