Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
loggly-python-handler with django dosent send the logs to loggly
i have django app (Django-Rest-Framework) and i want to add integration with Loggly via HTTP. i used the library loggly-python-handler but the logs are not sent to Loggly. i followed the docs: https://www.loggly.com/docs/python-http/ i installed loggly-python-handler i added to django setting.py file the following: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, 'json': { 'format': '{ "loggerName":"%(name)s", "timestamp":"%(asctime)s", "fileName":"%(filename)s", "logRecordCreationTime":"%(created)f", "functionName":"%(funcName)s", "levelNo":"%(levelno)s", "lineNo":"%(lineno)d", "time":"%(msecs)d", "levelName":"%(levelname)s", "message":"%(message)s"}', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': 'DEBUG', 'formatter': 'verbose', }, 'loggly': { 'class': 'loggly.handlers.HTTPSHandler', 'level': 'INFO', 'formatter': 'json', 'url': 'https://logs-01.loggly.com/inputs/TOKEN/tag/python', }, }, 'loggers': { 'django': { 'handlers': ['console', ], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, 'APPNAME': { 'handlers': ['console', 'loggly'], 'level': 'INFO', }, }, } i changed the TOKEN to my token in my app, in views.py, i called the logger: import logging logger = logging.getLogger(name) logger.info('this is INFO message.') i use Fiddler to see all HTTP requests, but i didn't see any request sent to loggly url. when i call it directly with curl it works. curl -H "content-type:text/plain" -d '{ "message" : "hello" }' http://logs-01.loggly.com/inputs/61fd261c-062f-44b1-b866-f03f5d50f720/tag/http/ -
Django signal based on the datetime field value
I'm struggling with the following. I'm trying to create a custom signal that will trigger when the current time will be equal to the value of my model's notify_on DateTimeField. Something like this: class Notification(models.Model): ... notify_on = models.DateTimeField() def send_email(*args, **kwargs): # send email signals.when_its_time.connect(send_email, sender=User) After I've read through all docs and I found no information on how to implement such a signal. Any ideas? -
How to add to a view of a Django installed app?
An external app provides functionality for uploading a certain type of data via my application using template/view/form. This works great. In the view for upload, it performs a check: if request.method == GET: <handle GET> elif request.method == POST: form = UploadForm(request.POST, request.FILES) <handle POST> In the 'handle POST' part of the view, I want to add something that says if a checkbox I have added to the upload template is checked, I want to upload the data in a custom way using my own model etc. If the checkbox isn't checked, just use the current upload code as is. To do this I figured I'd need to edit the upload view from the external app, as well as maybe adding my model to the models.py of the external app, but I know that's not how you're supposed to work. I thought about adding my own app with this functionality in it (model etc.) and I imagine that'll be fine, but I'd still need to add this conditional to the original view, which means editing the external app code again. How should I do this? -
Active Django app do not recognize global $PATH
I have deployed Django project (coded in Windows) on Ubuntu 18.04 server with gunicorn and nginx. There is a view which call in command line external package executable, located in /home/user/blast/bin/. PATH to package is defined in .profile export PATH="$PATH:/home/user/ncbi-blast-2.8.1+/bin" Package PATH is seen in echo $PATH also in my django project virtualenv. /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/ka4an/ncbi-blast-2.8.1+/bin I am able to run package executable in some_script.py in main shell and in django virtualenv like this: subprocess.run("package_executable", shell=True, stdout=log_file, stderr=log_file) and it returns expected output. However, when It is run in active Django app through views.py it returns that package_executable is not found. I found that inside active Django app i have different echo $PATH output, without PATH to my package: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin Active Django app is run by the same root user (who - returns same user). I can run my package inside active Django app by providing full path to package executable, but i`m interested in why Django do not recognize $PATH in .profile. -
Django - Extend the User model with different user kind
I want to extend the user model in Django (2.2) and combine it a Host and a Guest entities that have also specific fields. In the official documentation, it is recommended to create a "Profile" class with a OneToOne field that reference the User primary key. I can see 3 ways of doing it: Solution 1: Profile, Host and Guest model: class Profile(models.Model): k_user = models.OneToOneField(User, on_delete=models.CASCADE) language = models.CharField(max_length=2) class Host(models.Model): k_user = models.OneToOneField(User, on_delete=models.CASCADE) description = models.CharField(max_length=500) class Guest(models.Model): k_user = models.OneToOneField(User, on_delete=models.CASCADE) have_car = models.BooleanField(null=False) Solution 2: Host and Guest model (with Profile fields duplicated) class Host(models.Model): k_user = models.OneToOneField(User, on_delete=models.CASCADE) language = models.CharField(max_length=2) description = models.CharField(max_length=500) class Guest(models.Model): k_user = models.OneToOneField(User, on_delete=models.CASCADE) language = models.CharField(max_length=2) have_car = models.BooleanField(null=False) Solution 3: Profile model (containing Guest and Host fields) class Profile(models.Model): k_user = models.OneToOneField(User, on_delete=models.CASCADE) language = models.CharField(max_length=2) is_host = models.BooleanField(null=False) have_car = models.BooleanField(null=False) description = models.CharField(max_length=500) All those solutions are working. My question is: "Which one is the smartest, all things considered" (less database access, less code to write, easier to maintain, less limitations, etc..) -
I am getting UnboundLocalError
This is my error code: UnboundLocalError at /profile/ local variable 'u_form' referenced before assignment if u_form.is_valid() and p_form.is_valid(): -
how to bind multiple audio file as one file in python?
In my system i have to list all the wav files from one folder and then i have to bind that files as one file. I have the code to bind two files but i have 8 or more sound file i have to bind those file. Anybody can you help me? this code is bind two files: print(glob.glob('upload/updated_audios/*.wav')) file_data = glob.glob('upload/convertedAudio/*.wav') outfile = "upload/output_files/output.wav" data = [] for infile in file_data: w = wave.open(infile, 'rb') data.append([w.getparams(), w.readframes(w.getnframes())]) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) output.writeframes(data[0][1]) output.writeframes(data[1][1]) output.close() -
How I can test if user have permission for view
I created permission for my view, and its work but I dont know how I can test if patch request will work with user without permission. permission.py class IsObjectCreator(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return request.user == obj.user views.py class TaskDetailAPIView(APIView): permission_classes = [IsObjectCreator] def get_object(self, id): try: return Task.objects.get(id=id) except Task.DoesNotExist: raise Http404 def get(self, request, id): task = self.get_object(id) serializer = TaskSerializer(task) return Response(serializer.data) def patch(self, request, id): task = self.get_object(id) serializer = StatusSerializer(task, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) In normal Django view I can check if response contain form, but I dont know how in API I can test if response contain patch method. -
Bug regards Django adds extension/folder name to image stored on AmazonS3
I have a major bug in production, my image file extension keeps adding another folder on AmazonS3. An example is posted below. I just defined a regular image field in my model. But somehow it keeps adding new folder and name extension to the image file. I have no clue why this loop occurs. image = models.ImageField(upload_to="posts/", null=True, blank=True, max_length=255) It's give: media/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/posts/Nordi.jpg -
How to upload few images for one post on django using formset
I am a newbie in django and have some problems during uploading post with multiple images. Post is created, but images are not. I am trying to use formset, but images were not uploaded, errors were not occured. Some source code is below. Please help. Thank you. MODELS PostImage: class PostImage(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, verbose_name="Название публикации") VIEWS @login_required def post(request): ImageFormSet = modelformset_factory(PostImage, form=ImageForm, extra=3) if request.method == 'POST': postForm = PostForm(request.POST) formset = ImageFormSet(request.POST, request.FILES, queryset=PostImage.objects.none()) if postForm.is_valid() and formset.is_valid(): post_form = postForm.save(commit=False) post_form.user = request.user post_form.words = len(post_form.body.split()) post_form.reading_time = int(ceil(post_form.words/120)) post_form.save() # for form in formset.cleaned_data: # if form: # image = form["image"] # photo = PostImage(post=post_form, image=image, user=request.user) # photo.save() images = formset.save(commit=False) for image in images: image.post = post_form image.image = image['image'] image.user = request.user image.save() formset.save() formset.save_m2m() return redirect('blog:home') else: print(postForm.errors, formset.errors) else: postForm = PostForm() formset = ImageFormSet(queryset=PostImage.objects.none()) return render(request, 'blog/create_post.html', {'postForm': postForm, 'formset': formset}) HTML <form action="" method="post" class="form-horizontal" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="form-group"> <div class="col-sm-9"> <!-- Form fields - post.reading_time --> <input type="file" placeholder="Картинка" class="form-control" name="image" value="{{ form.image.value|default:"" }}"> </div> </div> {% endfor %} ... -
Do some post-processing after form submit, and render a new page with the newly processed data
Django newbie here, I created a simple form following this tutorial, and my form correctly saves the data in my Postgres connected local database. Then I used a signal to trigger on post_save so I can run my custom code. I learned by this question. Now, after the user enters data in the form and it gets saved, which triggers the custom code which does some post-processing, I want to show the user a new page with the newly processed data. But the trigger function I have used does not let me pass arguments to the custom code function. Before this, I was able to show the user the new page with some sample data and render a page with the new data. But, now I want to do it only when a user enters some data. Is this the right approach ? My templates all work fine, and the custom code fills the variables like rocode.vehicleroute with string values. Here is my code : views.py from django.shortcuts import render from django.http import HttpResponse from .forms import auditform, ClientAuditForm from django.db.models.signals import post_save from .models import auditModel def clientauditingfun(request): if request.method == 'POST': forminput = ClientAuditForm(request.POST) if forminput.is_valid(): Preference = … -
invalid config error in google api authentication
Traceback (most recent call last): File "quickstart.py", line 4, in gauth.LocalWebserverAuth() File "/home/wakefit3lenovo/.local/lib/python2.7/site-packages/pydrive/auth.py", line 113, in _decorated self.GetFlow() File "/home/wakefit3lenovo/.local/lib/python2.7/site-packages/pydrive/auth.py", line 443, in GetFlow self.LoadClientConfig() File "/home/wakefit3lenovo/.local/lib/python2.7/site-packages/pydrive/auth.py", line 366, in LoadClientConfig self.LoadClientConfigFile() File "/home/wakefit3lenovo/.local/lib/python2.7/site-packages/pydrive/auth.py", line 388, in LoadClientConfigFile raise InvalidConfigError('Invalid client secrets file %s' % error) pydrive.settings.InvalidConfigError: Invalid client secrets file Missing property "redirect_uris" in a client type of "web". -
Django Visitor Uploaded directory with uuid and sending the id to custom Script
I am creating a Django application that will convert the image to text. The script working fine before I add upload_to= in my model. Have a look at my model.py from django.db import models import os import uuid from django.conf import settings def img_path(_, file_name): return os.path.join(settings.MEDIA_ROOT, str(uuid.uuid4()), file_name) class ImageForExtractText(models.Model): image = models.FileField(upload_to=img_path) When a visitor uploads an image, it creates a new directory and put the image there. even if the same visitor uploads another image, it creates another new directory and put that image there---- this is working nice, no issue with this. Problem with my OCR script, the script can't find the image directory, coz, it always creates a new directory name with uuid. Have a look at img2text.py below import os import pytesseract from PIL import Image def extract_text_from_img(): basepath = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) basepath = basepath[:-5] + '/media/' img_path_list = os.listdir(basepath) for path in img_path_list: path = basepath + path img = Image.open(path) text = pytesseract.image_to_string(img) yield text This script can't find the directory name. It should always recognize the unique visitor uploaded image directory. Have a look at my view.py below from django.shortcuts import render, redirect from .img2text import extract_text_from_img from .forms import UploadImage def … -
django.contrib.auth.models.User.DoesNotExist: User matching query does not exist
I have error like in title when I'm trying to run test, I dont know whats going on but my testUser doesn't work properly, It's funny because i have identical test user in another project and there everything is ok. test_api.py class TaskDetailViewAPI(APITestCase): def setUp(self): self.client = APIClient() self.user = User.objects.create_user(username='test', password='test123') self.user.save() @classmethod def setUpTestData(cls): user = User.objects.get(id=1) Task.objects.create(name='TestTask', user=user, status='NEW', date=date(2019, 4, 9), description='This is test') def test_access_to_view_logged(self): task= Task.objects.get(id=1) login = self.client.login(username='test', password='test123') self.assertTrue(login) And this is test from another project where everything works fine class CreateCommentAPI(APITestCase): def setUp(self): self.client = APIClient() self.user = User.objects.create_user(username='test', password='test123') self.user.save() @classmethod def setUpTestData(cls): Category.objects.create(name='PC', slug='pc') Product.objects.create( category=Category.objects.get(id=1), name='Laptop', slug='laptop', description='here is description', photo=SimpleUploadedFile("file.jpeg", b"file_content", content_type="image/jpeg"), price=1999, available='available' ) def test_access_to_view_logged(self): product = Product.objects.get(id=1) login = self.client.login(username='test', password='test123') response = self.client.get(reverse('add_comments', kwargs={'id': product.id})) self.assertTrue(login) self.assertEqual(response.status_code, 200, f'expected Response code 200, instead get {response.status_code}') -
Heroku app giving 503 service unavailable error on postman on hitting the django api
I tried to deploy django app on heroku and on running the app through postman received the error as: 503 Service Unavailable. Logs: 2019-03-24T09:48:32.793173+00:00 app[web.1]: [2019-03-24 09:48:32 +0000] [4] [INFO] Starting gunicorn 19.9.0 2019-03-24T09:48:32.793191+00:00 app[web.1]: [2019-03-24 09:48:32 +0000] [4] [INFO] Listening at: http://0.0.0.0:25659 (4) 2019-03-24T09:48:32.793192+00:00 app[web.1]: [2019-03-24 09:48:32 +0000] [4] [INFO] Using worker: sync 2019-03-24T09:48:32.793194+00:00 app[web.1]: [2019-03-24 09:48:32 +0000] [10] [INFO] Booting worker with pid: 10 2019-03-24T09:48:32.868969+00:00 app[web.1]: [2019-03-24 09:48:32 +0000] [11] [INFO] Booting worker with pid: 11 2019-03-24T09:48:33.226325+00:00 app[web.1]: /app/.heroku/python/lib/python3.6/site-packages/psycopg2/init.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: http://initd.org/psycopg/docs/install.html#binary-install-from-pypi. 2019-03-24T09:48:33.226366+00:00 app[web.1]: """) 2019-03-24T09:48:33.314368+00:00 app[web.1]: /app/.heroku/python/lib/python3.6/site-packages/psycopg2/init.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: http://initd.org/psycopg/docs/install.html#binary-install-from-pypi. 2019-03-24T09:48:33.314372+00:00 app[web.1]: """) 2019-03-24T09:48:34.434383+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=POST path="/admin/categoryform" host=fashion-vocabulary.herokuapp.com request_id=c7c71191-ab20-47be-ad56-565854dc6008 fwd="103.87.57.16" dyno=web.1 connect=0ms service=485ms status=503 bytes=0 protocol=https 2019-03-24T09:48:34.431881+00:00 app[web.1]: Forbidden (Referer checking failed - no Referer.): /admin/categoryform 2019-03-24T09:48:34.432837+00:00 app[web.1]: 10.10.113.175 - - [24/Mar/2019:09:48:34 +0000] "POST /admin/categoryform HTTP/1.1" 403 3388 "-" "PostmanRuntime/7.1.1" -
django_cities_light no data being imported
I'm trying to work with django_cities_light and have followed the docs to a T and also referenced some other SO questions but no data is being imported. When I open a python shell and do from cities_light.models import City c1 = City.objects.get(id=100) c1 returns cities_light.models.City.DoesNotExist I've ran ./manage.py migrate ./manage.py cities_light But there is still no data. Does anyone have an idea of how I can fix this? -
django-widget-tweaks error while rendering in Django 2.1
While trying to use OSMField from django-osm-field and rending it with with django-widget-tweaks I am getting this error: File "/usr/local/lib/python3.7/site-packages/django/forms/boundfield.py", line 93, in as_widget renderer=self.form.renderer, TypeError: render() got an unexpected keyword argument 'renderer' However, downgrading from Django 2.1.x to 2.0.x it seems to be resolved -
Django user signup using custom user model not workin
I have a Django custom user model 'es_user' which inherit the Django's default user model. when a user signup it works fine but that user will be part of 'Users' and nothing will add upto es_user. so each time a user sign up I've to go to admin panel and add a signed in 'User' to 'es_user'. So to solve that I added these 2 to lines to views.py es_user_instance = es_user.objects.create(user= req_user) es_user_instance.save() which gives me this error ValueError at /signup/ Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7f9c787b9be0>>": "es_user.user" must be a "User" instance. models.py class es_user(models.Model): user = models.OneToOneField(User,related_name='es_user', on_delete=models.CASCADE) views.py def signup(request): signup_form_instance = SignUpForm() if request.method == "POST": signup_form_instance = SignUpForm(request.POST) if signup_form_instance.is_valid(): signup_form_instance2 = signup_form_instance.save(commit = False) req_user = request.user signup_form_instance2.password = make_password(signup_form_instance.cleaned_data['password']) signup_form_instance2.save() es_user_instance = es_user.objects.create(user= req_user) es_user_instance.save() return index(request)#successful signup redirect or return else: print("SIGN UP FORM INVALID") return render(request,'signup.html',{'signup_form':signup_form_instance}) forms.py class SignUpForm(forms.ModelForm): class Meta: model = User fields = ('username', 'email', 'password') can somebody tell me where is the problem NOTE: I've used this custom user model because I will be adding many more fields to 'es_user' later on. -
Is there a way to create a Task Manager Django App?
I wish to create a Task Manager Django app that can allow a user to sign in and new users to sign up. I've already done that part. A signed-in user can create a 'Team' and can add other users to his team. Now I want a message to be sent to the added users, saying like : 'Hey, you have been added to the Team of xyz User'. How to intercommunicate ? Is there something like an FB friend request possible here ? A signed-in user can create and assign a 'Task' to a single 'Team' but he may or may not assign it to the entire team, i.e. he can choose some members of a team and reject others, but all this must be from a single team. How to manage this ? Another issue is that once the user has signed in, he can only view the teams that he has created and also those teams to which he has been added. He must not view 'all' the created teams. I'm an infant to Django and I need to submit this project. Please help. Thanks a lot ! I've done the sign-in and sign up part. models.py … -
How to fix pdf.js rendering error of my website in Google Chrome
I am trying to make a pdf viewer in html template using pdf.js in Django framework. I had used a code that I got from a Youtube channel Traversy Media on how to create a custom PDF Viewer With JavaScript. It is working in Mozilla Firefox but not in Google chrome. These are the errors that I got from the console log: 1. Uncaught TypeError: Cannot read property 'xhr' of undefined at NetworkManager_getXhr [as getRequestXhr] (network.js:239) at PDFNetworkStreamFullRequestReader_onHeadersReceived [as _onHeadersReceived] (network.js:353) at NetworkManager_onStateChange [as onStateChange] (network.js:168) at NetworkManager_request [as request] (network.js:137) at NetworkManager_requestFull [as requestFull] (network.js:88) at new PDFNetworkStreamFullRequestReader (network.js:328) at PDFNetworkStream_getFullReader [as getFullReader] (network.js:292) at WorkerTransport.<anonymous> (api.js:1753) at _callee$ (message_handler.js:25) at tryCatch (runtime.js:62) 2. network.js:137 Access to XMLHttpRequest at 'file:///C:/Users/admin/Downloads/New%20folder/pdf_viewer-master/andro.pdf' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.NetworkManager_request @ network.js:137 3. network.js:419 Uncaught TypeError: Cannot read property 'reject' of undefined at PDFNetworkStreamFullRequestReader_onError [as _onError] (network.js:419) at XMLHttpRequest.NetworkManager_request.xhr.onerror (network.js:126) at NetworkManager_request [as request] (network.js:137) at NetworkManager_requestFull [as requestFull] (network.js:88) at new PDFNetworkStreamFullRequestReader (network.js:328) at PDFNetworkStream_getFullReader [as getFullReader] (network.js:292) at WorkerTransport.<anonymous> (api.js:1753) at _callee$ (message_handler.js:25) at tryCatch (runtime.js:62) at Generator.invoke [as _invoke] (runtime.js:288) 4. main.js:62 Uncaught … -
Django - Annotating each Event with Sum of participants that overlap with the start DateTime of that Event
I have an Event model with a start DateTime and end DateTime, as well as the number of participants. For each Event object, I want to get an annotated Sum of ALL the participants in any event that overlaps with the start DateTime. This is so I can make sure there aren't too many participants at any given time. class Event(models.Model): start = models.DateTime() end = models.DateTime() participants = models.IntegerField() I've been reading about Window functions, and maybe that would work here, but I can't get it right. I tried this, but it doesn't work because it's looking to group together events with the SAME start DateTime, not overlapping periods of start and end DateTimes against the original event start DateTime. starts = Event.objects.annotate( participants_sum=Window( expression=Sum('participants'), partition_by=[F('start'),], order_by=ExtractDay('start').asc(), ), ).values('participants', 'participants_sum', 'start') Any recommendations would be appreciated! -
Django: Why do I have to import signals in my AppConfig (it seems to work without)
I currently create a recurring cron job called every six hours via python manage.py dynamic_pricing_adjustment. As expected my console prints DO STUFF. My AppConfig. from django.apps import AppConfig class PricingConfig(AppConfig): name = 'myproject.pricing' It says in the Django documentation I should add it to the ready function. It seems to work without. Can you tell me what that part is for or why I should anyway add it? def ready(self): from . import signals # noqa Here the rest of my code: dynamic_pricing_adjustment.py from django.core.management.base import BaseCommand from myproject.pricing.signals import dynamic_pricing class Command(BaseCommand): help = "Adjust prices for dynamic pricing" def handle(self, *args, **options): dynamic_pricing.send(self) signals.py from django.dispatch import Signal, receiver dynamic_pricing = Signal() @receiver(signal=dynamic_pricing) def adjust_prices(sender, **kwargs): print("DO STUFF") -
Custom validation in ModelSerializer not working
I have a model of Printer: class Printer(models.Model): name = models.CharField(...) api_key = models.CharField(...) check_type = models.CharField(...) point_id = models.IntegerField() I created several printer objects. For building API I am using Django REST framework. I get 'POST' request that looks like this: { "id": 123456, "price": 780, "point_id": 1 } I need to check if there is Printer object with that point_id. So I made custom validator in Printer serializer: class PrinterSerializer(serializers.ModelSerializer): class Meta: model = Printer fields = ('name', 'api_key', 'check_type', 'point_id') def validate_poit(self, value): a = [] for i in Printer.objects.all(): a.append(i.point_id) if value not in a: raise serializers.ValidationError("Value not in range") return value And my view looks like this: @api_view(['POST']) def create_checks(request): printerserializer = PrinterSerializer(data = request.data['point_id'] if printerserializer.is_valid(): #do some stuff So as I think it could work: I get 'point_id', check if there is Printer object with that id and do some stuff if it is, but it never works -
How to edit user permission in Django Rest Framework
I am following the tutorial of django Rest Framework. I want to add user-based permission so that only authenticated user can view each user's detail information. Objective : Anyone can view the UserList, but only owner can view its UserDetail. models.py class Meeting(models.Model): created = models.DateTimeField(auto_now_add=True) sinceWhen = models.DateTimeField(null=True) tilWhen = models.DateTimeField(null=True) owner = models.ForeignKey('auth.User', related_name='meetings', on_delete=models.CASCADE) #highlighted = models.TextField() def save(self, *args, **kwargs): super(Meeting, self).save(*args, **kwargs) class Meta: ordering = ('created',) views.py from django.contrib.auth.models import User # User is not created inside models.py class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserListSerializer class UserDetail(generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) # I added IsOwnerOrReadOnly to make it work, but this is the part where it causes error! serializers.py class UserSerializer(serializers.ModelSerializer): meetings = serializers.PrimaryKeyRelatedField(many=True, queryset=Meeting.objects.all()) #owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = User fields = ('id', 'username', 'meetings',) class UserListSerializer(serializers.ModelSerializer): #meetings = serializers.PrimaryKeyRelatedField(many=True, queryset=Meeting.objects.all()) class Meta: model = User fields = ('username',) permissions.py from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): # Any permissions are only allowed to the owner of the meeting return obj.owner == request.user I overrode IsOwnerOrReadOnly so that only user can view the details of his/her user detail. And add … -
Credit card validation form error at delete
I'm not sure where the error is coming from, if the models, forms or views, most likely the form. I got the editing the form working, also adding a new credit card works, but when I try to delete a credit card object I get this error: The error I'm getting: Traceback: File "/Users/Arturo/anaconda3/envs/SoftEngVEnv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Users/Arturo/anaconda3/envs/SoftEngVEnv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/Users/Arturo/anaconda3/envs/SoftEngVEnv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/Arturo/anaconda3/envs/SoftEngVEnv/lib/python3.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/Users/Arturo/Documents/Arturo/Knowledge_center/Computer_Science/Projects/GitHub/Software Engineering 1/softwareEngineering_Group2/bookStore/users/views.py" in creditCardChange 185. if user_CreditCardForm.is_valid(): File "/Users/Arturo/anaconda3/envs/SoftEngVEnv/lib/python3.7/site-packages/django/forms/forms.py" in is_valid 185. return self.is_bound and not self.errors File "/Users/Arturo/anaconda3/envs/SoftEngVEnv/lib/python3.7/site-packages/django/forms/forms.py" in errors 180. self.full_clean() File "/Users/Arturo/anaconda3/envs/SoftEngVEnv/lib/python3.7/site-packages/django/forms/forms.py" in full_clean 382. self._clean_form() File "/Users/Arturo/anaconda3/envs/SoftEngVEnv/lib/python3.7/site-packages/django/forms/forms.py" in _clean_form 409. cleaned_data = self.clean() File "/Users/Arturo/Documents/Arturo/Knowledge_center/Computer_Science/Projects/GitHub/Software Engineering 1/softwareEngineering_Group2/bookStore/users/forms.py" in clean 121. number = self.cleaned_data['number'] Exception Type: KeyError at /settings/billing/creditcard/6/ Exception Value: 'number' And this is my forms.py class CreditCardForm(ModelForm): def __init__(self, *args, **kwargs): super(CreditCardForm, self).__init__(*args, **kwargs) self.fields['name'].widget.attrs['placeholder'] = 'My Discover' self.fields['number'] = forms.CharField(widget=forms.TextInput( attrs={'id': 'creditcard-number'})) self.fields['number'].widget.attrs[ 'placeholder'] = '123456789' self.fields['expdate_month'] = ChoiceField(choices=MONTHS) self.fields['expdate_year'] = ChoiceField(choices=YEARS) self.fields['securitycode'].widget.attrs[ 'placeholder'] = '123' class Meta: model = CreditCard fields = [ 'name', 'number', 'expdate_month', 'expdate_year', 'securitycode' ] def clean(self): # errors …