Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implementing Djoser and JWT in Django for user authentication
I am implementing user authentication in my first Django app. I decided to follow a tutorial from here. I just finished the implementation, and it happens that when I add the following route path('api/app', include('app.urls')),to the url.py, I get the following error, which crashes t he platform: .... File "/Users/frankydoul/opt/anaconda3/lib/python3.8/site-packages/django/urls/resolvers.py", line 123, in _check_pattern_startswith_slash if regex_pattern.startswith(('/', '^/', '^\\/')) and not regex_pattern.endswith('/'): RecursionError: maximum recursion depth exceeded while calling a Python object Removing it let the platform running. Is anybody familiar with the error please ? -
zappa deployment : [ERROR] CommandError: Unknown command: 'create_pg_db'
I followed the tutorial on https://romandc.com/zappa-django-guide/walk_database/ and pip installed the package, added the value to installed apps, configured the aws aurora postgres then when I do zappa manage project_name create_pg_db I get [ERROR] CommandError: Unknown command: 'create_pg_db' Traceback (most recent call last): File "/var/task/handler.py", line 609, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 243, in lambda_handler return handler.handler(event, context) File "/var/task/handler.py", line 408, in handler management.call_command(*event['manage'].split(' ')) File "/var/task/django/core/management/init.py", line 105, in call_command raise CommandError("Unknown command: %r" % command_name)[END] did I miss anything, what can I do to fix this? -
Django/Daphne, got NotImplementedError calling asyncio.create_subprocess_exec( under WINDOWS
I am using Django 3.2 with Daphne 3.0.2, Python 3.8.9 under Windows 10. Trying to call proc = await asyncio.create_subprocess_exec( python_exe, bridge_script, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, ) Gives me following error: Exception Type: NotImplementedError Exception Location: c:\python\python38\lib\asyncio\base_events.py, line 491, in _make_subprocess_transport When serving Django/ASGI with daphne. Under Linux everything runs fine. Serving under Windows with Python runserver also everything fine, Just daphne & windows gives me the error. Thanks for any help. -
Python and markdown I can't print inside html
I'm using Django and this is my python code import markdown def link(request): output = markdown.markdownFromFile('entries/CSS.md') print(output) this is my html code ` Encyclopedia <h1>All Pages</h1> {{ link }} below is inside CSS.md I want it to print inside my html page inside {{ link }} `CSS CSS is a language that can be used to add style to an HTML page.` > [![I'm having this message][1]][1] -
ngrok: DJango and nodejs: how to add multiple ports
How can i add multiple ports I have nodejs and django application webapp: image: "python-node-buster" ports: - "8001:8000" command: - python manage.py runserver --noreload 0.0.0.0:8000 networks: - django_network node: image: "python-node-buster" ports: - "3000:3000" stdin_open: true networks: - node_network ngrok: image: wernight/ngrok:latest ports: - 4040:4040 environment: NGROK_PROTOCOL: http NGROK_PORT: node:3000 NGROK_AUTH: "" depends_on: - node - webapp networks: - node_network - django_network networks: django_network: driver: bridge node_network: driver: bridge Assuming i get the url for node at http://localhost:4040/inspect/http http://xxxx.ngrok.io and in my nodejs application, i want to access http://xxxx.ngrok.io:8001 for apis How to configure this -
Backend python online game (Гонки для двоих)
Всем привет Стоит задача сделать бекенд для игри гонки на двоих. Клиент будет написан на unity Подскажите что можно использовать для такой задачи. Всем спасибо. -
How to change content with ajax in django
I have a django template as follows <div class="container"> <section class="main"> <h1>Check the chart below</h1> <form> {% csrf_token %} <div class="switch"> <input id="chk" type="checkbox" class="switch-input" /> <label for="chk" class="switch-label">Switch</label> </div> </form> <div class="main_graph"> {% if main_graph %} {{ main_graph.0|safe }} {% else %} <p>No graph was provided.</p> {% endif %} </div> </section> </div> <script type="text/javascript"> $(document).on('click', '#chk', function (e) { $.ajax({ type: 'POST', url: '/home', data: { chk: $('#chk').prop('checked'), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function (data) { $('.main_graph').load(document.URL + ' .main_graph'); } }); }) </script> This is my views def home(request): const_list = pd.read_csv('./const.csv').Const.unique() part_list = pd.read_csv('./part_list.csv').abbr.unique() all_list = pd.read_csv('./all_list.csv').All.unique() chked=request.POST.get('chk', '') if chked == 'true': print(chked) my_graph = main_graph(all_list, len(const_list)) else: print('this is a test') my_graph = main_graph(part_list, len(const_list)) context={'main_graph':my_graph, 'const': const_list} return render(request, 'home.html', context) The main_graph function takes a list and an int value as parameters for creating a bar graph with plotly. The list will be for populating the y-axis and the int value is a range for the x-axis. The graph is created properly. Now I want to change the graph on the click of a button. For this purpose, I created a toggle switch which when clicked will send activate an ajax function. When I … -
How to run a python file in command promt when a button is clicked is on a webpage
I am trying to make a local webpage which later on will be deployed, in which when a button on the html webpage is clicked, it opens up a commend prompt window and run the program. I have tried to implement it this using django framework. I have added the python file to the project library for it to be accessible, I have implemented it in the following way in views.py file, def beast(request): out = run(sys.executable, ['beast.py'], shell=True) return render(request,'page2.html') No input is to be given to the python file. It compiles and runs, but when the button is clicked t gives out a TypeError - bufsize must be an integer Please let me know what can be done for it to work -
Forward & Back Buttons that can Increase or Decrease Current Date in a Django View Repeatedly
I have a view that displays a teacher's daily schedule based on what day it is. If it's Monday then all that teacher's Monday students and lesson times are displayed along with radio buttons for attendance to be recorded. By default the view starts on the current day. I want to install back and forward buttons in templates/teacher.html that will decrease or increase the date by one day per click. Tried passing 'back' or 'forward' as string path converters. For example, in views.py there'd be an if today = 'back' I would use datetime.timedelta(days=-1) to decrement the date by 1. However, that strategy seems to only be meant for making a one time change. In this strategy the first time the user clicks the Back Button the URL reads: localhost...:teacher/id/back Which works. But if the user clicks back again the URL reads: localhost...:teacher/id/backback And then I get an error. I want the user to be able to change the date back or forward as many times as desired. I've tried storing the date into a session variable, but Django Templates don't seem to provide a way to update a session variable from HTML. Or, do they? Anyway, I'm open to … -
Django form inside a page which is a form too
Help please, I have my RaodNetwork model which hold the Project model as Foreign Key. I Would like : 1 - One we are inside a project, select automatically the foreign key of this project without no ned to select it manually 2 - to create a road network instance and display (add) it inside a project. Here is my project page (pk=1) with my roadnetwork instance views.py def create_network(request, pk): """A roadnetwork depends on a project. It must be created un side the project""" project = Project.objects.get(id=pk) form = RoadNetworkForm(initial={'project':project}) if request.method =='POST': form=RoadNetworkForm(request.POST, instance=project) if form.is_valid(): form.save() return redirect('home') context = {'form':form} return render(request, 'roadnetwork.html', context) class RoadNetwork(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) simple = models.BooleanField(default=False) locked = models.BooleanField(default=False) #representation = path nb_nodes = models.IntegerField() nb_edges = models.IntegerField() name = models.CharField('Network Name', max_length=200, blank=False) comment = models.TextField() tags = models.TextField() def __str__(self): return "{}".format(self.name) class Project(models.Model): owner = models.ManyToManyField(User) # define as FK and add a user as ManyToManyField public = models.BooleanField(default=False) name = models.CharField('Project Name', max_length=200, null=False) comment = models.TextField() def __str__(self): return "{}".format(self.name) urlpatterns=[ path('project/<str:pk>/', project_pagination, name = 'project'), path('network/<str:pk>/', create_network, name = 'create_network'), ] -
Is there any method to get rid of this error. (1062, "Duplicate entry '2' for key 'customer_customerprofile.user_id'")?
I have to create a field called location from the lat and on like in this program. The location is printing out correctly, but there is a duplicate entry error while saving. I need to update the user_id to id when the post function works. Since it is saved twice, the duplicate entry error is showing. def post(self, request, format=None): serializer = CustomerSerializer(data=request.data) if serializer.is_valid(): serializer.save() lat = serializer.data.get('latitude',None) lon=serializer.data.get('longitude',None) lat_1=float(lat) lon_1=float(lon) location=Point((lat_1,lon_1),srid=4326) print(location) id=serializer.data.get('user') print(id) v=CustomerProfile(location=location,user_id=id) v.save() return Response({"message":"Customer Profile Updated Successfully","data":serializer.data}, status=200) return Response({"message":"Customer registration failed!!","data":serializer.data}, status=400) -
Django: prefetch related with sort by runs multiple queries
I am using prefetch_related. When i want to sort the prefetch results, then it generates again sql, class UserActivity(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name= 'user_logging_details', on_delete=models.CASCADE ) ip_addess = models.CharField(max_length=40) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) users = User.objects.prefetch_related('user_logging_details').all() for user in users: users_activity = user.user_logging_details.all() # this does not generate any sql ## VS ## users_activity = user.user_logging_details.all().sort_by('ip_addess') # this generates many sqls and defeats the purpose of prefetch related How can sort the prefetch results. What is the correct way to do this. -
Get GET url parameters in class-base views for Django 3.2
I found a similar question, but it was for Django 1.5, and I don't think it worked for me. class SearchedPostListView(ListView): model = Post template_name = 'blog/search.html' # <app>/<model>_<viewtype>.html paginate_by = 2 context_object_name = 'posts' def get_context_data(self, *args, **kwargs): context = super(SearchedPostListView, self).get_context_data(*args, **kwargs) query = self.kwargs.get('q') context['posts'] = Post.objects.filter(Q(title__icontains=query) | Q(author__username__icontains=query) | Q(content__icontains=query)) context['categories'] = Categories.objects.all return context This is my code. I am trying to search through all the posts on my website, and I'm showing any posts that have the query in the title. So, if I type in the URL localhost:8000/search?q=foo, then it has to show me the posts that contain the word foo in its title. But I'm not able to access the GET parameters. How do I access the GET parameters in Django 3.2? -
Django JSONDecodeError
I am working on a code that receives reading from a temperature sensor using ES8266 and the Arduino code is working fine sending the reading in JSON format. received data on the Django server looks like this {'sensorType': 'Temperature', 'reading': '87.00'} when I open the URL that loads the view I get this error "JSONDecodeError at /sensor Expecting value: line 1 column 1 (char 0)". this is the function that receives the data in views @csrf_exempt def index(request): print("\n") data = json.loads(request.body) type = data.get("sensorType", None) reading = data.get("reading", None) print(data) print(type) print(reading) sensor = Sensor() sensor.SensorType = type sensor.Reading = reading sensor.save() return HttpResponse("Hello") -
how to extract function name from a code string pythonic way?
I have a code string as follows code = '\n function factorial( n ){\n\n let a=1;\n\t\tfor(let c=1; c<=n; c++){\n\ta=a*c;\n\t\t}\n\n\treturn a;\n }\n\n\n ' The name of the function is after function keyword and before the first '('. I know how to solve this problem but i was wondering whether there is a short pythonic way to extract function name from the given code string. I appreciate any insights. Thanks! -
Editing a Post - Django and Javascript Question
I am new to Django and Javascript. I would like to create an edit section on a site, where people can edit a post that already exists. Similar to Facebook or Twitter. When I click 'edit' on my post, in the console I am getting: network.js:28 POST http://127.0.0.1:8000/edit_post/ 404 (Not Found) I've tried many things but cannot get it to work. Any help is appreciated. I think the issue might have to do with the use of 'post' and 'text.' 'text' is in my model, used to signify the text of the actual post. views.py: @login_required @csrf_exempt def edit_post(request): if request.method == "POST": post_id = request.POST.get('id') new_post = request.POST.get('text') try: post = Post.objects.get(id=post_id) if post.user == request.user: post.text = new_post.strip() post.save() return JsonResponse({}, status=201) except: return JsonResponse({}, status=404) return JsonResponse({}, status=400) models.py class User(AbstractUser): pass class Post(models.Model): text = models.TextField(max_length=500, blank=True, null=True) username = models.ForeignKey('User', on_delete=models.CASCADE, related_name='author', null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField( User, blank=True, related_name="liked_user") def __str__(self): return self.user.username Javascript file: edit = document.querySelectorAll(".edit"); text_area = document.querySelectorAll(".textarea"); edit.forEach((element) => { element.addEventListener("click", () => { edit_handeler(element); }); }); text_area.forEach((element) => { element.addEventListener("keyup", (e) => { if (e.keyCode == 13 && e.shiftKey) return; if (e.keyCode === 13) edit_handeler(element); }); … -
Using Two Different Models In Views to Return a Newly Created List, Not Already Called Querylist, With a For Loop
I am trying to create the following view: class FeedAPI(ObjectMultipleModelAPIView): #lookup_url_kwarg = 'id' def get_querylist(self, *args, **kwargs): id = self.kwargs['id'] props = Profile.objects.filter(id=id) followers = Profile.filter(followers.includes(props)) querylist = [ {'queryset': Profile.objects.filter(followers), 'serializer_class': ProfileSerializer}, {'queryset': Post.objects.all(), 'serializer_class': PostSerializer}, ] feedPosts= [] for x in followers: feedPosts = Posts.objects.filter(Source_id=Post.sourceID) return Response(props, feedPosts, status=status.HTTP_200_OK) But I get the error type object 'Profile' has no attribute 'filter' which according to stack overflow, comes because I am not returning a querylist in my def get_query list. So, I would like to know how I can just return the Post IDs that have the same sourceIDs associated with the followers of a profile. My models are Source, Profile, and Post. Profile and Post have sourceID ForeignKeys. Profile model* class Profile(models.Model): user = AutoOneToOneField(User, default=True, on_delete=models.CASCADE) sourceID = models.ForeignKey('Source', on_delete=models.CASCADE, related_name='+', blank=True, null=True) followers = models.ForeignKey( 'Source', on_delete=models.CASCADE, related_name='+', default='', blank=True, null=True) following = models.ForeignKey('Source', on_delete=models.CASCADE, related_name='+', default='', blank=True, null=True)``` ***Post model*** class Post(models.Model): sourceID = models.ForeignKey('Source', blank=True, on_delete=models.CASCADE, related_name='+', null=True) image = models.ImageField( "Post Picture", upload_to='post_pics', blank=True, null=True) title = models.CharField(max_length=50)``` Source model class Source(models.Model): profile = models.ForeignKey('Profile', on_delete=models.CASCADE, null=True, blank=True, related_name='+') def __str__(self): return str(self.id) -
AttributeError Exception Value: 'IntegerField' object has no attribute 'max_length'
I did not put any max_length restrictions on the IntegerField hence I am not sure what is the issue. The code below is in models.py. Please tell me what else do i need to provide to give a better understanding to this issue. Django version: Django==3.2 models.py from django.db import models class Rawdata(models.Model): id = models.IntegerField(db_column='id', primary_key = True) name = models.TextField(blank=True, null=True) node = models.TextField(blank=True, null=True) metal_stack = models.TextField(blank=True, null=True) thickness = models.DecimalField(max_digits=4, decimal_places=2,blank=True, null=True) mstk_id = models.IntegerField(db_column='MStk_id',blank=True, null=True) # Field name made lowercase. restrict = models.TextField(db_column='restrict', blank=True, null=True) # Field name made lowercase. class Meta: db_table = 'rawdata' class Technology(models.Model): id = models.IntegerField(db_column='id', primary_key = True) name = models.CharField(unique=True, max_length=45, blank=True, null=True) node = models.CharField(max_length=45, blank=True, null=True) def __str__(self): return self.name class Meta: db_table = 'technology' unique_together = (('name','node'),) class Metalstack(models.Model): id = models.IntegerField(db_column='id', primary_key = True) techname = models.ForeignKey('Technology', to_field = 'name', on_delete = models.CASCADE, db_column ="techname",blank=True, null=True) stackname = models.CharField(max_length=45, blank=True, null=True, db_column ="stackname") mstk_id = models.IntegerField(blank=True, null=True, db_column ="mstk_id") restrict = models.CharField(max_length=45, blank=True, null=True) def __str__(self): return self.stackname class Meta: db_table = 'metalstack' unique_together = (('techname', 'stackname', 'mstk_id'),) class Thickness(models.Model): id = models.IntegerField(db_column='id', primary_key = True) stack_id = models.ForeignKey(Metalstack, to_field = 'id', on_delete = models.CASCADE, … -
CORS not working in Django but settings seem correct
I am trying to make a POST call to Django from a React Native Web front end on different subdomains. I thought I had configured CORS correctly, but that does not seem to be the case. Here's what my Django settings.py looks like: CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = ['*'] CORS_ALLOWED_ORIGINS = ['https://api.example.com', 'https://example.com', 'https://www.example.com' ] CSRF_TRUSTED_ORIGINS = [ 'https://api.example.com', 'https://example.com', 'https://www.example.com' ] ALLOWED_HOSTS = ["0.0.0.0", "api.example.com", "example.com"] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', ] INSTALLED_APPS = [ ... 'corsheaders', ... ] What exactly am I doing wrong here? The error I'm getting is this: Access to XMLHttpRequest at 'https://api.example.com/api/v1/pagescreate/' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. And this is my Django view: class PageCreateView(generics.CreateAPIView): queryset = Page.objects.all() serializer_class = PageSerializer What could be causing this? Am I missing some setting in React? I'm using axios to make the calls, with the only header being "Content-Type": "application/json" -
How to return serializer to bulk create
I have a model which saves some files to db. When I upload nested zip file (zip files inside main zip) I need to create an object for every file inside and return created objects in serializer. models.py class CampaignManagerCreativeAsset(models.Model): asset_file = models.FileField( validators=[validate_file_extension], storage=AssetsMediaStorage() ) mimetype = models.CharField(max_length=50, null=True) helpers.py def _check_for_nested_zip(zip_file): all_zip = list() for file in zip_file.namelist(): if file.lower().endswith('.zip'): all_zip.append(True) else: all_zip.append(False) return all_zip def process_zip_file(file_object): with ZipFile(file_object, 'r') as zip_file: all_zip = _check_for_nested_zip(zip_file) if all(all_zip): files_to_create = list() files_content = {name: zip_file.read(name) for name in zip_file.namelist()} for filename, content in files_content.items(): file = SimpleUploadedFile.from_dict( { 'content': content, 'filename': filename, 'content-type': 'application/zip', } ) files_to_create.append(file) return files_to_create return file_object views.py class CreativeAssetViewSet(viewsets.ModelViewSet): serializer_class = serializers.CreativeAssetSerializer filter_fields = '__all__' def get_queryset(self): return models.CampaignManagerCreativeAsset.objects.all() serializers.py class CreativeAssetSerializer(serializers.ModelSerializer): class Meta: model = models.CampaignManagerCreativeAsset fields = ( 'id', 'external_creative_asset_id', 'asset_file', 'settings', 'mimetype', ) read_only_fields = ('id', 'external_creative_asset_id', 'mimetype') def create(self, validated_data): asset_file = validated_data.get('asset_file') settings = validated_data.get('settings') mimetype = helpers.get_mimetypes_type(asset_file.name) instances = list() if mimetype == 'application/zip': files_to_create = helpers.process_zip_file(asset_file) if not isinstance(files_to_create, list): instances.append(models.CampaignManagerCreativeAsset(**validated_data)) else: for file in files_to_create: instances.append( models.CampaignManagerCreativeAsset( asset_file=file, settings=settings ) ) return models.CampaignManagerCreativeAsset.objects.bulk_create(instances) But I am getting error Got AttributeError when attempting to get a value … -
How to put implement chart.js into an existing page django
I am making this website that has this function that shows total hours worked for the employee. I want to make so that when it shows the total hours worked, it will also show the hours worked for each day in that month. I managed to do the chart for that but the chart will show on another page so how do I show the chart and the total hours worked on the same page? code: def checkTotalHours(response): empName = employeeName.objects.all() if response.method == "POST": if 'checkName' in response.POST: n = response.POST.get("check") emp = employeeName.objects.get(employee=n) time = emp.total_Hours_Worked messages.info(response, time + ' hours') f = Name.objects.filter(name=emp) allDate = [] cIn = [] today = datetime.today() datem = today.month for date in f: allDate.append(date.date) totalTime = (datetime.combine(date.date, date.timeOut)- datetime.combine(date.date, date.timeIn)).seconds/3600 cIn.append(totalTime) hours = int(totalTime) minutes = (totalTime*60) % 60 seconds = (totalTime*3600) % 60 time = "%d:%02d:%02d" % (hours, minutes, seconds) #cIn.append(time) global cInUpdated global allDateUpdated cInUpdated = [] allDateUpdated = [] for item in range(len(allDate)): if allDate[item].month == datem: cInUpdated.append(cIn[item]) allDateUpdated.append(allDate[item]) print("Here:: ", allDate[item].month," ", cIn[item] ) else: continue for item in range(len(cInUpdated)): print("Work: ", allDateUpdated[item], " ",cInUpdated[item]) return redirect('/totalHours') else: form = CreateNewList() return render(response, "main/checkTotalHours.html", {"empName":empName}) HTML: {% … -
Django, how to update my following list using fetch and PUT in JavaScript?
I have a method in views.py that adds user to the following list, I'm trying to make it work whenever I click on the button "follow" that I have added in JavaScript How do I make my Follow button in JavaScript go to my views.py method onclick ? views.py method. def follow(request, profile_to_follow): try: user_to_follow = User.objects.get(username=profile_to_follow) user_to_following = Profile.objects.get(user=request.user.id) except User.DoesNotExist: return JsonResponse({"error": "Profile not found."}, status=404) if request.method == "PUT": user_to_following.following.add(user_to_follow) return HttpResponse(status=204) urls.py # API Routes path("posts", views.compose_post, name="compose_post"), path("posts/all_posts", views.show_posts, name="show_posts"), path("posts/<int:post_id>", views.post, name="post"), path("profile/<str:profile>", views.display_profile, name="profile"), path("<str:profile_posts>/posts", views.display_profile_posts, name="profile_posts"), path("follow/<str:user_to_follow>", views.follow, name="follow"), JavaScript function load_user_info(user_clicked_on){ document.querySelector('#page-view').style.display = 'none'; document.querySelector('#posts-view').style.display = 'none'; document.querySelector('#show-posts').style.display = 'none'; document.querySelector('#load-profile').style.display = 'block'; fetch(`/profile/${user_clicked_on}`) .then(response => response.json()) .then(profile => { const profile_element = document.createElement('div'); const followers = document.createElement('div'); const following = document.createElement('div'); const follow_button = document.createElement('button'); follow_button.innerHTML += "Follow"; followers.innerHTML = 'Followers: ' + profile.followers; following.innerHTML = 'Following: ' + profile.following; profile_element.appendChild(followers); profile_element.appendChild(following); profile_element.appendChild(follow_button); profile_element.classList.add('profile_element'); follow_button.addEventListener("click", () => { follow_user(user_clicked_on) }); document.querySelector('#user-profile').appendChild(profile_element); }); document.querySelector('#user-profile').innerHTML = `<h3>${user_clicked_on.charAt(0).toUpperCase() + user_clicked_on.slice(1)} Profile</h3>`; } function follow_user(user_to_follow){ // to make this function work with the one in views.py fetch(`/profile/${user_to_follow}`, { method: 'PUT', }) } -
List and Retrieve actions generating additional CRUD actions (from ModelViewSet's get_permissions()?)
When I do a simple GET to my model's list or detail view, it actually appears to be running a whole bunch of additional and unasked-for actions under ModelViewSet's get_permissions(). So when I add print(self.action) under get_permissions() I get the following: Accessing model's list view (i.e. /authors/): list create create None Accessing model's detail view (i.e. /authors/1): retrieve retrieve update partial_update update destroy None None Why on earth is this happening? Shouldn't it simply print "list" for my list view and "retrieve" for my detail view? views.py class AuthorViewSet(viewsets.ModelViewSet): queryset = Author.objects.all() lookup_field = "pk" serializer_class = AuthorSerializer def get_permissions(self): print(self.action) # Print self.action code here if self.action == "create": permission_classes = [IsAuthenticated] elif self.action == "list" or self.action == "retrieve": permission_classes = [AllowAny] elif ( self.action == "update" or self.action == "partial_update" or self.action == "destroy" ): permission_classes = [IsAdminUser] # I have to include this final else statement or I get this error: # "UnboundLocalError: local variable 'permission_classes' referenced before assignment" # Probably because there is a self.action == "None" attempt? else: permission_classes = [AllowAny] return [permission() for permission in permission_classes] models.py class Author(models.Model): first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255) serializers.py class AuthorSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="library:author-detail") class … -
Django None parameter function issue
When I input none value or other values that do not match with the patientName and patientNRIC in the database(sqlite), print(patient_data) shows Response 200, then there will be error in converting the patient_data into json bcs the patient_data actually contains no data, and is not None. How should I do so that I can make sure that the function can take it None values at the same time is able to validate/make sure patient_data contains information then return true or return json otherwise return false. Below is the fun with django url. Thank you for your help. def by_nric_name(patientsNRIC=(None,''), patientsName=(None,'')): params = {'patientName': patientsName, 'patientNRIC': patientsNRIC} django_url = "http://85c867e79dc5.ngrok.io/bynricandname/" patient_data = requests.get(django_url, params=params) print(patient_data) patient_data = patient_data.json() return patient_data -
How to fix Django server 503 error when upload a file?
I tried to upload a file by using django-rest-framework. This is my code what I tried. videofile = request.FILES['videoData'] fs = FileSystemStorage() filename = fs.save(videofile.name, videofile) user = request.user File.objects.create( user = user, title = request.data['videotitle'], url = filename, categorys = request.data['categories'], preveimage = request.data['vidoePrevimg'], filetype = request.data['videoType'], filesize = request.data['videoSize'] ) status_code = status.HTTP_200_OK response = { 'success': 'true', 'status code': status_code, 'message': 'Video uploaded successfully', } It works fine in local and when I deploy it to heroku, most APIs works fine, except file upload. The server returns 503 error. Please help me. Sorry for my English. Thank you in advance