Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i get queryset based on mapping table in django rest framework?
models.py class MasterCategory(models.Model): name = models.CharField(max_length=200, blank=True, null=True) code = models.CharField(max_length=20, blank=True, null=True) icon = models.TextField(blank=True, null=True) image = models.TextField(blank=True, null=True) is_active = models.BooleanField(default=True, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Meta: db_table = 'master_category' class MasterLessonType(models.Model): lesson_type = models.CharField(max_length=20, blank=True, null=True) lesson_code = models.CharField(max_length=20, blank=True, null=True) is_active = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Meta: db_table = 'master_lesson_type' class Lesson(models.Model): lesson_type = models.ForeignKey(MasterLessonType, on_delete=models.CASCADE, blank=True, null=True) content = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Meta: db_table = "lesson" ** --- category can be mapped to multiple lesson -----** class CategoryLessonMapping(models.Model): category = models.ForeignKey(MasterCategory, on_delete=models.CASCADE, blank=True, null=True) lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, blank=True, null=True) class Meta: db_table = 'category_lesson_mapping' ** ---- user can be mapped sto multiple lesson --- ** class UserLessonMapping(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, blank=True, null=True) class Meta: db_table = 'user_lesson_mapping' I want to get the logged in user, user mapped to lesson, lesson mapped to category and lesson mapped to lesson type data like this { user:{ 'id':1, 'first_name': 'alan' 'last_name': 'walker' }, 'lesson': [ { "id": 1, "lesson_type": { "id": 1, "lesson_type": "Video", … -
Making a request that triggers a function that searches a json object. The object will be updated every minute, could this lead to issues?
I am making a bus prediction web application for a college project. The application will use GTFS-R data, which is essentially a transit delay API that is updated regularly. In my application, I plan to use a cron job and python script to make regular get requests and write the response to a JSON file, essentially creating a feed of transit updates. I have set up a get request, where the user inputs trip data that will be searched against the feed to determine if there are transit delays associated with their specific trip. My question is - if the user sends a request at the same time as the JSON file is being updated, could this lead to issues? One solution I was thinking of is having an intermediary JSON file, which when fully loaded will replace the file used in the search function. I am not sure if this is a good solution or if it is even needed. I am also not sure of the semantics needed to search for solutions to similar problems so pointers in the right direction would be useful. -
How to make a shortcut of day display e.g Thursday 14/07/2022 => Thu 14/07/2022 in Django html template
I have booking start date as follow <p>{{ booking.start_time|date:"j/F/Y" }}</p> on Django html template which it displays the date as 14/July/2022 on the DOM, how I can make it display like this Thu 14/07/2022 -
How to return 400 status code from custom middleware in django?
I am trying to write a custom middleware which does some operation on the request to check its validity and if the request is invalid then return the bad request 400 status code without even going ahead. from django.http import HttpResponseBadRequest class VersionCheckMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): meta = request.META client = meta.get('HTTP_X_APP_CLIENT', None) if client == 'ios': app_version = ( int(meta['HTTP_X_IOS_APP_VERSION']) if meta.get('HTTP_X_IOS_APP_VERSION') else int(meta.get('HTTP_X_APP_VERSION', 0)) ) if app_version < 30: return HttpResponseBadRequest elif client == 'android': app_version = int(meta['HTTP_X_APP_VERSION']) if app_version < 188: return HttpResponseBadRequest elif client == 'web': app_version = int( meta['HTTP_X_APP_PLATFORM_VERSION'] if meta.get("HTTP_X_APP_PLATFORM_VERSION") else meta['HTTP_X_APP_VERSION'] ) if app_version < 188: return HttpResponseBadRequest response = self.get_response(request) return response -
how to add value from user input field in django imoirt-export library?
I have model named Product and Calculator that is connected to each item in Product model. What I am trying to achieve is to allow user to insert number of units and based on this number calculate total price in Excel file that will be exported when user clicks Calculate button. Questions: How can I add value inserted by a user in my input field to my cost_calculator.xlsx file and based on that value calculate total price? How can I add unit_hours property from CostCalculator model to my exported file? I successfully added it to admin page and it shows me correct result but when I add to to fields in my resource model then I get KeyError. What is the best approach to calculate total_price and display it in Excel in my case? The formula is following: number_of_units * rate * margin = total_price. Should I put it in form_valid in ProductDetailView or in ExportData view or maybe I shouldn't seperate Export button to seperate view but add it to form_valid. Is it possible to merge Send and Calculate buttons into one so if user clicks 1 button it will send user's value, calculate and export unit_hours and total_price … -
How do I change the default value of a field on a bound form that gets rendered in Django?
In a Django project we have forms that have already been submitted where for some reason the person before me set the default value of a field to be one blank space (' ') and this is affecting some other functionality where we need to copy data (not relevant to go into detail for this question I don't think) Anyway, here is a snippet from models.py where I changed the default value to '': #inside class Meta base64_encoded_activation_key = models.CharField (max_length = 1000, default = '', blank = True, verbose_name = 'Activation Key') Inside views.py def edit_activation(request, id=None): ...... activation = get_object_or_404(ActivationRecord, pk=id) ....... ....... ....... else: # GET request form = ActivationRecordForm(instance=activation) Now, this works fine if I create and submit a new form, but when I go back to an old form then the value is still ' ' (which I guess is expected as the form has been submitted) but I don't know how to fix this to the new default value. -
django the request argument must be an instance of django.http.HttpRequest
I'm importing a service function from django views function and getting this error 'The `request` argument must be an instance of `django.http.HttpRequest`, not `collections.OrderedDict`.' I have used the same implementation in other modules too and those are working fine. from custom_label.services.custom_label_svc import update_label @api_view(["POST"]) @authorize def update_label(request) -> JsonResponse: try: payload = ValidateUpdateLabel(data=request.data) if payload.is_valid(): # call service methods data = update_label(payload.validated_data) << here ... In custom_label > services > custom_label_svc.py file: from basic_files.database_connections import connect_to_postges cursor = connect_to_postges() def update_label(params: dict) -> dict: app_id = params.get('appid') label_name = params.get('label_name') updated_label_icon = params.get('updated_label_icon') sql = "UPDATE label SET icon = %s WHERE appId = %s AND name = %s" % (updated_label_icon, app_id, label_name) cursor.execute(sql) return cursor.rowcount What am I missing here? -
how to filter number of posts per page in Django python
This is views.py file paginator = Paginator( product_list, 5 ) show_on_page = request.GET.get('show_on_page', 5) product_item_list = paginator.get_page(show_on_page) and this is my templates file <div class="show-on-page"> <label class="product-sort-label" for="show-on-page">Tonen op pagina:</label> <select name="show-on-page" id="show-on-page"> <option value="5" selected>5</option> <option value="10">10</option> <option value="20">20</option> </select> I want to add random navigation like when you select 5 from dropdown 5 posts should be displayed per page if 10 it selects 10 posts. Can anyone help me with this? -
How to get queryset i need?
i have 2 models class Task(models.Model): user = models.ForeignKey( to='users.User', on_delete=models.CASCADE, related_name='tasks', ) category = models.ForeignKey( to='TaskCategory', on_delete=models.CASCADE, related_name='tasks', blank=True, null=True, ) difficult = models.DecimalField( max_digits=10, decimal_places=2, validators=(MinValueValidator(Decimal('0.01')),), ) class TaskCategory(models.Model): user = models.ForeignKey( to='users.User', on_delete=models.CASCADE, related_name='task_categories', ) name = models.CharField( max_length=255, ) i want to get this query(get top 3 category of most difficults sum and next one to sum of anothers): [ { "category__name": "Food", "category_sum": "12477.00" }, { "category__name": "Shopping", "category_sum": "3214.00" }, { "category__name": "Movie", "category_sum": "2590.00" }, { "category__name": "Anothers", "category_sum": "2000.00" } ] i make this queryset, but i dont know how make queryset i want: Task.objects.values('category__name').annotate( category_sum=Coalesce( Sum('difficult'), 0, output_field=DecimalField() ) ).filter( category__isnull=False ).order_by('-category_sum') [ { "category__name": "Food", "category_sum": "12477.00" }, { "category__name": "Shopping", "category_sum": "3214.00" }, { "category__name": "Movie", "category_sum": "2590.00" }, { "category__name": "Sport", "category_sum": "1000.00" } { "category__name": "Home", "category_sum": "1000.00" } ] -
Check overlapping reservation
I am developing a Reservation System in Django. I have a booking model, and in views the logic to make new booking and also to edit bookings. The logic in creating new bookings works perfectly but I am having problems when editing it. Basically, what I need to achieve is: If I edit my reservation but I don't change any data, I want the form to be saved If I edit my reservation and I change some data, I want the form to be saved ONLY if it doesn't overlap with any other reservation. I post some code: models.py class Booking(models.Model): aircraft = models.ForeignKey(Aircraft, on_delete=models.CASCADE) student = models.ForeignKey( Student, on_delete=models.CASCADE, blank=True, null=True) instructor = models.ForeignKey( Instructor, on_delete=models.CASCADE, blank=True, null=True) renter = models.ForeignKey( Renter, on_delete=models.CASCADE, blank=True, null=True) booking_date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() uid = models.CharField(max_length=200, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) The uid field I created is a sort of logic to have a kind of Unique ID of the reservation in order to check if anything changed when I edit the booking. views.py if request.method == "POST": aircraft = request.POST.get('aircraft') student = request.POST.get('student') instructor = request.POST.get('instructor') renter = request.POST.get('renter') date = request.POST.get('date') start_time = … -
How to add/update objects using serializers in the Django Rest Framework?
I am using Django Rest Framework so that my other Django project can change records in this project's database, and am using serializers to do so. I am using the .save() method, which will add to the database only if none of the existing records share the same primary key as the ones being saved. I would like to "update" these existing records, either by updating them straight or deleting them then creating them again. This is my views.py: from rest_framework.response import Response from rest_framework.decorators import api_view from .serializers import parcelSerialiser @api_view(['POST']) def addItem(request): serializer = parcelSerialiser(data=request.data, many = True) print(request.data) print(serializer.is_valid()) print(serializer.errors) if serializer.is_valid(): serializer.save() return Response(serializer.data) and my serializers.py: from rest_framework import serializers from mainMenu.checkIn.models import Parcels class parcelSerialiser(serializers.ModelSerializer): class Meta: model = Parcels fields = '__all__' -
Code in Django is not working. The form in html does not open the output when clicking on submit
I am working on a simple project where I want to read a pdf using a form in html and then display the contents of the pdf on another page in form of a dictionary key value format. This is the code I have so far. The problem is that when I click on the submit button not even the else condition is executing and nothing happens. index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Pdf Reader</title> </head> <body> <form enctype='multipart/form-data' action='/analyze' method='POST'> <div class="input-group"> <input type="file" name="inp" class="form-control" id="inputGroupFile04" aria-describedby="inputGroupFileAddon04" aria-label="Upload"> <button class="btn btn-outline-secondary" type="button" id="inputGroupFileAddon04">Submit</button> </div> </form> </body> </html> views.py from django.http import HttpResponse from django.shortcuts import render import PyPDF2 from io import StringIO def index(request): return render(request,'index.html') def analyze(request): if request.method == "GET": #txt = request.FILES['inp'].read() # get the uploaded file pdfFileObj = open(request.FILES['inp'].read(), 'rb') # pdfFileObj = open((request.GET.get('inp.pdf')),'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) pageObj = pdfReader.getPage(0) content = pageObj.extractText() buf = StringIO(content) l = buf.readlines() while '\n' in l: l.remove('\n') i = 0 while i < len(l): for j in range(len(l[i])): if l[i][j:j + 2] == '\n': l[i] = l[i][:-1] j += 1 i += 1 d = {} i = 0 while i < (len(l)): if ":" … -
DJango can't execute an empty query
Im not so familiar with sql command, my sql command comes from csv file and it's all good. Im using multi database in django but I got an error : django.db.utils.ProgrammingError: can't execute an empty query. I also tried this solution but not working can't execute an empty query . Please help me on this.Thank You! Here's my csv file: Name sql James SELECT value AS id from test WHERE name ='James' AND age ='10' AND grade ='80' Ice SELECT value AS id from test WHERE name ='Ice' AND age ='14' AND grade ='85' Mike SELECT value AS id from test WHERE name ='Mike' AND age ='11' AND grade ='88' and more and more query here........ def filter(request): field = {"James","Mike"} number={3265826,61894965} df = pd.read_csv('/pathtofile/grade.csv') for name in field: data = df[df['Name'] == name] sql = data['sql'].values[0] query = sql + ' AND Number =' + "'"+ number +"'" sqldata = test.objects.using("database2").raw(query) cursor = connection.cursor() cursor.execute(sqldata) row = cursor.fetchall() -
PyJWT cant find module with import jwt
after the installation of the PyJWT 2.4.0 i can't import the module jwt it shows me "Import could not be resolved import jwt import datetime from django.conf import settings def generate_access_token(user): payload = { 'user_id':user.id, 'exp':datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat' : datetime.datetime.utcnow() } return jwt.encode(payload,settings.SECRET_KEY,algorithm='HS256').decode('utf-8') -
passing session in forms.py in django
I'm working on django project, in which I'm using model as form to generate an image upload page. The problem is there's a foreign key referring to user's profile table which fetches a list of users in a drop down menu. I figured i need to use the session value from logged in user but so far I haven't been able to pass the session through forms. Of course, I've tried couple of solutions found on similar questions but those options didn't work for me here's the code: forms : class ImageForm(forms.ModelForm): class Meta: model = ImageMedia fields = ['id', 'Image', 'ImageTitle', 'ImageContext', 'Uploader'] labels = {'Image' : 'Select Image', 'Image Context' : 'Image Context'} Models : class ImageMedia(models.Model): id = models.AutoField(primary_key = True) Image = models.ImageField(verbose_name="Image Name", upload_to = "ImageSet") UploadDate = models.DateTimeField(verbose_name="Date and time uploaded", auto_now_add=True) Uploader = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=False) ImageTitle = models.CharField(verbose_name="Image Title", null=False, max_length=100) ImageContext = models.CharField(verbose_name="Image Context", max_length=500, null=True) def __str__(self): return self.ImageTitle upload template <body> <div class="container"> <center><div class="card" style="width: 28rem;"> <div class="py-5 text-center bg-secondary text-white"> <div class="card-header"> <h1 class="mb-3">Upload Image</h1> </div> <form name="UploadForm" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% comment %} {{form.Image}} {{form.ImageTitle}} {{form.Uploader.as_hidden}} {{form.ImageContext}} {% endcomment %} {{form.as_p}} <input type="submit" id="submit" … -
Best way to convert Django ORM query to GraphQL
So I have this webapp, that the frontend side allows the user to build dashboards which in-turn create a GraphQL query. This query is sent the the Backend (Django) and all the backend does is route this request to some external DB that handles the GraphQL and returns a response. The issue: I have a complex logic in the backend, that knows how to create a Django ORM query (Q) per each request, which I would like to combine with the GraphQL query. Basically im trying to convert a Django Q (django.db.models.query_utils.Q) into a GraphQL filter section. Is there a way to do it? Maybe with a different generic lang than GraphQL? or Do I have to resort to write something myself -
Submitting Bulk Forms In Django
I have 5 different forms in forms.py; the forms are all based off of 1 model. The 5 forms are all displayed on the same html page, so as to allow the user to create or register 5 objects into the DB with 1 single button click. In the future, I might need to submit 50 forms in a single click. If I were to do this based on the existing code, I would probably need 50 forms in forms.py and repeat the registration logic in views.py for 50 times. Is there a more efficient way to do this? views.py def register(request): form1 = DetailsForm1() form2 = DetailsForm2() form3 = DetailsForm3() form4 = DetailsForm4() form5 = DetailsForm5() if request.method == "POST": form1 = DetailsForm1(request.POST) if form1.is_valid(): form1.save() form2 = DetailsForm2(request.POST) if form2.is_valid(): form2.save() form3 = DetailsForm3(request.POST) if form3.is_valid(): form3.save() form4 = DetailsForm3(request.POST) if form3.is_valid(): form3.save() form5 = DetailsForm5(request.POST) if form5.is_valid(): form5.save() return render(request, "app/registration_completed.html") context = { "form1": form1, "form2": form2, "form3": form3, "form4": form4, "form5": form5 } return render(request, "app/register.html", context) forms.py class DetailsForm1(forms.ModelForm): class Meta: model = Property fields = ( 'owner', 'address', 'postcode', ) class DetailsForm2(forms.ModelForm): class Meta: model = Property fields = ( 'owner', 'address', 'postcode', … -
Web API that itself sends data to client on availability
I am currently working with Django but I am stuck as I don't know if I am pursuing the right model given the nature of my application. Problem Statement: I have to make a REST API for a client such that whenever I get a trigger for a new entry/entries in my Database I have to send those to the client which is supposed to listen to a URL and has asked for data only once and now is open to receive data whenever available to him. It is not sending a GET request now and then. There will be different endpoints of the APIs. One is where I provide him all the new data available to me and in other where it asks for specific data (ex: '/myAPI/givemethis') I can easily implement the second requirement as it is a simple request-response case. I am not sure how to send him data that too on availability without him making a repeated request as client. It appears a Publisher-Subscriber model is better suited for my use case but I don't know how to implement it on Django. I bumped into several concepts like StreamingServices and MQTT but I am not sure … -
Django statics returns 404 error in cPanel Passenger
I used cPanel and deployed a Django application on my server using passenger_wsgi.py. The problem is when I'm trying to access static files (like admin CSS file: static/admin/css/base.css) I'm facing with 404 error. I've already done collectstatic and added PassengerPathInfoFix method to passenger_wsgi.py file but the output log is Not Found: /home/mysite/public_html/static/admin/css/base.css even though the outputted path exists and I can edit it using vim. My settings.py: STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = "/static/" MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Any help would be appreciated. -
Django rest framework URL pattern of CRUD operation in single GenericAPIView class
I have been creating a class view with GenericAPIView in the Django rest framework. and define their URLs but on Django swagger, every URL shows all methods. #views.py class AmenitiesView(ListModelMixin, RetrieveModelMixin, CreateModelMixin, DestroyModelMixin, UpdateModelMixin, GenericAPIView): serializer_class = AmenitiesSerializer queryset = Amenities.objects.all() def get(self, request, *args, **kwargs): many, queryset = True, self.filter_queryset(self.get_queryset()) if 'pk' in kwargs and kwargs['pk']: many, queryset = False, self.get_object() serializer = self.get_serializer(queryset, many=many) return Response({"data": serializer.data, "message": "Successfully Get Amenities", "isSuccess": True, "status": 200}, status=200) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) #urls.py urlpatterns = [ path('amenities/get/', AmenitiesView.as_view()), path('amenities/get/<int:pk>/', AmenitiesView.as_view()), path('amenities/create/', AmenitiesView.as_view()), path('amenities/edit/<int:pk>/', AmenitiesView.as_view()), path('amenities/delete/<int:pk>/', AmenitiesView.as_view()), ] how to define URL with the method, like if 'amenities/get/' is URL so on swagger will show only get method and if URL is 'amenities/create/' so only post method shown on this url. -
subprocess.call() doesn't throw and error when file is not found
I'm trying to run a python script from a Django web service and I'm using the subprocess.call() method and I've put it in a try except block because I need to get the error when something is wrong. I discovered that when the path to the script is not valid is not raising an error it's only displaying it on the console, but I need it to be thrown so I can catch it in the except block. Here is my code. try: row = exec_SQL(f"SELECT [ID], [ProjectPath], [MainFileName] FROM [dbo].[WebserviceInfo] WHERE ProjectName='{project}'") command = f'python {row[1]}\{row[2]} {model} {scenario}' subprocess.call(command, shell=True) except Exception as e: error_message = str(e) This is the path to the file + some arguments that I need. f'python {row[1]}\{row[2]} {model} {scenario} Thanks in advance for your help. -
App runs locally but crashes when deployed to Heroku
My Python Flask app runs locally but when I deploy it to Heroku it successfully builds but crashes when opening the app. I'm relatively comfortable with Python but new to web dev and Heroku etc. Here's my Procfile web: gunicorn app:app From my limited understanding my Procfile is correct(?) as it's telling Heroku to run my app.py file which is what I run when running the app locally. Logs 2022-07-14T09:08:18.969324+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/werkzeug/serving.py", line 740, in __init__ 2022-07-14T09:08:18.969325+00:00 app[web.1]: HTTPServer.__init__(self, server_address, handler) 2022-07-14T09:08:18.969325+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/socketserver.py", line 452, in __init__ 2022-07-14T09:08:18.969325+00:00 app[web.1]: self.server_bind() 2022-07-14T09:08:18.969325+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/http/server.py", line 136, in server_bind 2022-07-14T09:08:18.969325+00:00 app[web.1]: socketserver.TCPServer.server_bind(self) 2022-07-14T09:08:18.969326+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/socketserver.py", line 466, in server_bind 2022-07-14T09:08:18.969326+00:00 app[web.1]: self.socket.bind(self.server_address) 2022-07-14T09:08:18.969326+00:00 app[web.1]: OSError: [Errno 98] Address already in use 2022-07-14T09:08:18.969552+00:00 app[web.1]: [2022-07-14 09:08:18 +0000] [10] [INFO] Worker exiting (pid: 10) 2022-07-14T09:08:33.000000+00:00 app[api]: Build succeeded 2022-07-14T09:08:49.139858+00:00 app[web.1]: [2022-07-14 09:08:49 +0000] [4] [INFO] Shutting down: Master 2022-07-14T09:08:49.139897+00:00 app[web.1]: [2022-07-14 09:08:49 +0000] [4] [INFO] Reason: Worker failed to boot. 2022-07-14T09:08:49.288295+00:00 heroku[web.1]: Process exited with status 3 2022-07-14T09:08:49.375710+00:00 heroku[web.1]: State changed from up to crashed 2022-07-14T09:08:49.378964+00:00 heroku[web.1]: State changed from crashed to starting 2022-07-14T09:08:59.395728+00:00 heroku[web.1]: Starting process with command `gunicorn app:app` 2022-07-14T09:09:00.585739+00:00 app[web.1]: [2022-07-14 09:09:00 +0000] [4] [INFO] Starting … -
Django Rest Framework Custom Permission not taking effect
I have a permissions.py file that holds a custom permission called CanViewUserRecord. I have assigned this to a viewset called UserRecordView. The permission isn't working though, whenever I call the endpoint attached to the viewset all of the data from the database is returned. Here is the custom permission code: from accounts.models import Staff class CanViewUserRecord(permissions.BasePermission): edit_methods = ("PUT", "PATCH") def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: if obj.account_type == "staff": # If user is the manager of staff if obj.staff.manager == request.user.id: return True # If the user is the owner if obj == request.user: return True # Allow admins to access if request.user.account_type == "admin": return True return False elif obj.account_type == "manager": # If the user is the owner if obj == request.user: return True # Allow Admins to access if request.user.account_type == "admin": return True return False elif obj.account_type == "admin": # If the user is the owner if obj == request.user: return True # Allow Admins to access if request.user.account_type == "admin": return True return False else: return False elif request.method in self.edit_methods: if obj.account_type == "staff": if ( request.user.account_type == "manager" or request.user.account_type == "admin" ): return True else: return False elif … -
Blog API with DRF getting Anonymous User Error
I am creating a BlogAPI with LoginAPI(using dj-rest-auth). I have created a model for my Post- models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): content = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) Then I have made 2 serializers User and Post - serializers.py from rest_framework import serializers from django.contrib.auth.models import User from .models import Post class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'id', 'email'] class PostSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Post fields = ['user', 'content'] My view looks like this- views.py from rest_framework import viewsets, permissions from .serializers import UserSerializer, PostSerializer, CommentSerializer from . import models from rest_framework.response import Response from rest_framework.decorators import action, api_view, permission_classes class UserViewSet(viewsets.ModelViewSet): queryset = models.User.objects.all() serializer_class = UserSerializer class PostViewSet(viewsets.ModelViewSet): queryset = models.Post.objects.all() serializer_class = PostSerializer permission_classes = [permissions.AllowAny] def create(self, request): serializer = PostSerializer( data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) print(request.data) print(request.user) serializer.save(user=request.user) return Response(serializer.data) I have kept the permissions_class as AllowAny because then I was not able to test the API. urls.py(inside app) router = routers.DefaultRouter() router.register(r'^users', views.UserViewSet) router.register(r'^posts', views.PostViewSet) urlpatterns = [ path('', include(router.urls)), re_path(r'^posts/(?P<pk>\d+)/comments/$', view=views.PostViewSet.as_view({'get': 'comments', 'post': 'comments'})), re_path(r'^posts/(?P<pk>\d+)/comments/(?P<comment>\d+)/$', view=views.PostViewSet.as_view({'delete': 'remove_comment'})) ] After running it on locahost on http://127.0.0.1:8000/posts/ I am able to do … -
Check if the data in json file exit in django models
I want to check if the data in json file exit in django models table For example: In models.py table called activity in that table different fields are there Such as activity_name , activity_status I want to check the activity names in json file exit or not If exit print true or if not false Plese help me