Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image not loading on a class based view DJANGO for Twitter Card
I am trying to load the image on Twitter card and i am using 'SITE_PROTOCOL_URL': request._current_scheme_host, in function based views it is working well but in a class based view its not loading. I tried different ways but still doesnt work and i am stuck on it here is my code in view: def category(request,slug,pk): query_pk_and_slug = True katego=Kategori.objects.all() kategorit=Kategori.objects.get(title=slug, fotot_e_kategoris=slug) lajmet=Lajmet.objects.filter(kategorit=kategorit, verified=True).order_by('-data_e_postimit') lajms=Lajmet.objects.filter(kategorit=kategorit, verified=True).order_by('-data_e_postimit')[3:] lajmets=Lajmet.objects.filter(kategorit=kategorit, verified=True).order_by('-data_e_postimit')[7:] sponsor=SponsorPost.objects.all().order_by('-data_e_postimit') paginator = Paginator(lajmets, 15) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request,'main/category-news.html',{ 'SITE_PROTOCOL_URL': request._current_scheme_host, 'lajmet':lajmet, 'kategorit':kategorit, 'katego': katego, 'lajms': lajms, 'page_obj': page_obj, 'sponsor':sponsor }) class LajmetListView(ListView): model = Kategori model = Lajmet template_name = 'main/lajme-home.html' # <app>/<model>_<viewtype>.html context_object_name = 'lajmets' query_pk_and_slug = True def get_context_data(self, **kwargs): context = super(LajmetListView, self).get_context_data(**kwargs) context['lajmet'] = Lajmet.objects.order_by('-data_e_postimit').filter(verified=True) context['katego'] = Kategori.objects.all() context['shikime'] = Lajmet.objects.all().order_by('-shikime') context['SITE_PROTOCOL_URL'] = self.request._current_scheme_host return context And Template : {% if object.slug in request.path %} <title>{{object.titulli}}</title> <meta name="twitter:card" value="summary_large_image"> <meta name="twitter:site" content="@gazetarja_"> <meta name="twitter:creator" content="@SimonGjokaj"> <meta name="twitter:title" content="{{object.titulli}}"> <meta name="twitter:description" property="og:description" content="{{object.detajet|striptags|truncatewords:30}}"> <meta name='twitter:image' content="{{SITE_PROTOCOL_URL}}{{object.fotografit.url}}"> {% elif request.path == '/' %} <title>Portali Gazetarja - LAJMI FUNDIT</title> <meta name="twitter:card" value="summary_large_image"> <meta name="twitter:site" content="@gazetarja_"> <meta name="twitter:creator" content="@SimonGjokaj">' <meta name="twitter:title" content="Portali Gazetarja - LAJMI FUNDIT"> <meta name="twitter:description" content="Gazetarja i'u sjell në kohë reale, sekond pas sekonde informacione … -
How can I put 2 views in one template? Django
To put multiple forms in one view we are using request.POST.get(name argument of form), but When I am doing that with my register and login page than the login page is working, but I cant see the register form. The problem is to check if request is POST and than return the result for each case. def index(request): # login view if request.user.is_authenticated: return render(request, 'authenticated.html') else: if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('index') else: messages.error(request, 'Username or password is incorrect, try again!') return render(request, 'index.html') def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST or None) if form.is_valid(): form.clean_email() form.save() username = form.cleaned_data.get('username') messages.success(request, f'Successfully created account for {username}') return redirect('index') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) Html for login and registration <form method="post" name="login"> {% csrf_token %} <input type="text" name="username" placeholder="username"> <input type="password" name="password" placeholder="password"> <input type="submit" value="Login Yeah!"> </form> <form method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Sign Up"> </form> -
How to access multiple Data from jquery class to another input field to extract using python
kindly check out this image for further proceedings. Here we had used a jquery function to do the multiple CC. and we want to access those data to the second field from there will be stored to DB using python. -
How to redirect to an authenticated view with access token from another app in Django?
I have a Django website with two apps running on it. On app 1 the user receives an auth token and is supposed to be redirected to app 2 with said token. App 2 requires authentication in all views through APIView's permission_class "IsAuthenticated". app2/urls.py: app_name = 'app2' urlpatterns = [ path('',views.waitingroom_view.as_view(), name = 'waitingroom_index'), path('authenticated/',views.authentication_view.as_view(), name ='authentication') ] app2/views.py: class waitingroom_view(APIView): def get(self, request): return redirect('app1/index') My code correctly authenticates the user by giving them authentication tokens (refresh and access tokens) through a requests.post function: app1/views.py: def get_authentication_tokens(request, username, password): #BEWARE: hardcoded URL url = 'http://127.0.0.1:8000/api/token/' postdata = { 'username': username, 'password': password, } r = requests.post(url, data=postdata) tokens_json = r.json() #splits the respective tokens into 2 variables: "refresh" and "access" refresh_token = tokens_json['refresh'] access_token = tokens_json['access'] return access_token, refresh_token response = requests.get('http://0.0.0.0:8000/authenticated', auth=BearerAuth(access_token)) return HttpResponse(response) This returns a .html page that requires an auth token to access. However, the return is on app 1 instead of redirecting to app 2 with auth token. How do I redirect to an authenticated view (app 2) from another app (app 1) (that generated the auth token)? -
django model select_related or prefetch_related child model
Newbie here, I have two models which are below class ReceipeMaster(models.Model): receipe_type = models.CharField(max_length=50, choices=TYPE_OPTIONS, default=TYPE_OPTIONS[0]) item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='receipe') units = models.IntegerField(default=1) status = models.BooleanField(default=True) class ReceipeDetail(models.Model): master = models.ForeignKey(ReceipeMaster, on_delete=models.CASCADE, related_name='items') item_type = models.ForeignKey(Item_type, null=True, on_delete=models.PROTECT) item = models.ForeignKey(Item, on_delete=models.PROTECT) quantity = models.IntegerField() I have a detailed view DetailView class ReceipeDetailView(PermissionRequiredMixin, DetailView): permission_required = 'item_management.view_receipemaster' model = ReceipeMaster template_name = 'receipes/show.html' context_object_name = 'receipe' I would like to prefetch_related or select_related on the ReceipeMaster model and as well as the ReceipeDetail model. Simply prefetch on both models. Regards -
What is the best video storage solution
I have an application which connects to Instagram API and pulls massive amount of data everyday. My next challenge is to pull and save many Instagram users stories to a storage, then let my application users to see/view those stories in my django web app. I need to save nearly 50 GB of short videos (stories) everyday This makes nearly 20 TB of data for a year, so the storage must be at least that big The amount of stories that will be watched per day on my web app will be < 1000 (less than 1 GB) I don't have any experienced developers/engineers around me, so I do my own research about the subject. Azure Blog Storage looks like the solution that fit my needs but also a very expensive one (200-400$ per month). I have experience with Postgres and MySQL databases but not with Cloud services like Google or Azure, so any links, advices and tips are appreciated highly. -
Show a message in Django after a function completes, without having the user wait for it to complete
Say I have this view: import threading def MyView(request): thr = threading.Thread(target=my_func, args=(request,)) thr.start()#Runs a function that the user should not wait for return render(request, "my_site") where def my_func(request): #Some function that takes 10 second and the user should not wait for this sleep(10) messages.success(request, "Your meal is ready!") return render(request, "my_other_site") What I want to do is; I have a function of which the user should not wait for to complete i.e they should be able to continue browsing, and then when the function is done, I want to show them a message either using messages or a pop-up box or something third. Is there a way to do that in Django (since it all runs synchronous I can't think of a way), or what would be the most optimal way ( -
Discard records using serializers of Django rest framework
I need to discard all records that have no associated images. This must be implemented in serializers. If there is a solution in the views, it is also welcome. I have these models class Activity(models.Model): """ Class Activity """ name = models.CharField(max_length = 200, null = False, blank = False) create_at = models.DateTimeField('Create date', auto_now_add = True, editable = False) update_at = models.DateTimeField('Last update', auto_now = True) class Image(models.Model): """ Image of an activity """ activity = models.ForeignKey(Activity, related_name = 'images', on_delete = models.CASCADE) image = models.ImageField(upload_to = 'files/images') And following serializers class ImageModelSerializer(serializers.ModelSerializer): """ Image model serializer """ class Meta: model = Image fields = ('id', 'image') class ActivityModelSerializer(serializers.ModelSerializer): """ Activity model serializer """ images = ImageModelSerializer(read_only = True, many = True) class Meta: model = Activity fields = ('id', 'name', 'images', 'create_at') Here are examples of the response I need to get. Example: Correct [ { "id": 1, "name": "Activity 1", "images": [ {"id": 1, "image": "path to image 1"}, {"id": 2, "image": "path to image 2"} ], "create_at": "2021-04-07T15:58:15.409054Z" }, { "id": 3, "name": "Activity 3", "images": [ {"id": 3, "image": "path to image 1"}, {"id": 4, "image": "path to image 2"} ], "create_at": "2021-04-07T15:58:15.409054Z" } ] … -
Django model query .values() on a JSONfield
I have a JSONfield that contains a lot of data that I need to aggregate over, but i'm having a little trouble doing so. So I have a field in the JSON data that contains the amount of cores for a specific node, and i'd like to grab all these values in the DB and count them afterwards. I've tried the following data = Node.objects.filter(online=True).values( data__golem.inf.cpu.cores).annotate(the_count=Count(data__golem.inf.cpu.cores)) But that didn't work out, which might be because JSONfield doesn't support .values() queries? I'm not sure if that's the case anymore but it was mentioned at an old answer back from 2017. Next thing I tried was to just filter the by online=True and loop over each element in the QuerySet and then get the golem.inf.cpu.cores manually and add that to a dict and add it all together in the end. But that results in a KeyError and that's because of the punctations in the fieldname I would assume? How can I go on about this? print(obj.data['golem.inf.cpu.capabilities']) KeyError: 'golem.inf.cpu.capabilities' views.py @api_view(['GET', ]) def general_stats(request): """ List network stats. """ if request.method == 'GET': #data = Node.objects.filter(online=True) query = Node.objects.filter(online=True) for obj in query: print(obj.data['golem.inf.cpu.capabilities']) serializer = NodeSerializer(data, many=True) return Response(serializer.data) else: return Response(serializer.errors, … -
Django - Limiting selection of many to many field on ModelForm to just values from parent record
Could really use some help. I have a django app that has the following tables: Mission. Package. Target. Flight. A mission has 1 or many packages. 1 or many targets and 1 or many packages. A package has one or many flights. A Flight has a many to many relationship such that there is a multi-select field that allows you to select pre-added targets (added as children of the mission parent) to the flight. The problem is the dropdown shows all targets ever added to the database. I was expecting it would only show targets that belong to the mission parent. How do I limit the target options that appear in the Flight form, to just those of targets that belong to a mission? Mission Model class Mission(models.Model): # Fields campaign = models.ForeignKey( 'Campaign', on_delete=models.CASCADE, null=True) number = models.IntegerField( default=1, help_text='A number representing the mission order within the campaign.', verbose_name="mission number") name = models.CharField( max_length=200, help_text='Enter Mission Name') description = models.TextField( help_text='Enter Mission Description/Situation.', default="Mission description to be added here.") Package Model class Package(models.Model): # Fields mission = models.ForeignKey( 'Mission', on_delete=models.CASCADE, null=True) name = models.CharField( max_length=200, help_text='Enter Package Name', verbose_name="Package Name") description = models.TextField( help_text='Enter Mission Description/Situation.', null=True, blank=True, verbose_name="Description … -
Djoser user creating route return a socket error
I'm using Djoser to create a user from my front-end. When I create a user from the React app with this request const newStudent = () => { fetch(`${process.env.REACT_APP_SERVER_URL}/auth/users/`, { method: 'POST', headers: { "Accept": "application/json", "Content-Type": "application/json", }, body: JSON.stringify({ email: "mss@domain.hr", display_name: "Maa", username: "as", password: "sa", role: 1 }) }) } The request completes, the new user gets created but this nice error pops up in the Django console ---------------------------------------- Exception occurred during processing of request from ('192.168.1.6', 49473) Traceback (most recent call last): File "C:\Python39\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Python39\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Python39\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\Mislav\.virtualenvs\backend-EBmKnWnA\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\Mislav\.virtualenvs\backend-EBmKnWnA\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Python39\lib\socket.py", line 704, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine ---------------------------------------- The interesting thing is that other requests work fine after the socket error Doing the exact same request from postman doesn't cause the error [08/Apr/2021 13:15:46] "POST /auth/users/ HTTP/1.1" 201 104 My Djoser setup DJOSER = { 'USER_ID': 'id', 'LOGIN_FIELD' : 'username', 'LOGOUT_ON_PASSWORD_CHANGE': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': … -
Invalid block tag on line 2: 'else', expected 'endblock'. Did you forget to register or load this tag?
I followed one django tutorial on youtube. I am currently category page where I want to have urls like this: "../search/<category_name>" I have no problem loading the page until I want to search the category. I am using the name in the category database which is 'django' so that I can avoid error. The URLs FYI, I'm using vscode and run the code in django html language. I have read some discussion regarding to this issue. I have followed one advice to rearrange so that it can read the code easily but when I save the code is going back to the state shown in the picture below. Therefore, I encounter an error due to invalid block tag. Django html code back to its state when I save picture Invalid block tag Output -
Django annotate and apply different aggregation functions on the same field
I'm using django annotate and I want to apply multiple aggregations on the same field: queryset = queryset.apply_filters( user=user, start_date=start_date, end_date=end_date ).values('product').annotate( avg_a=Avg('field_a'), total_a=Sum('field_a'), ) But I'm getting the following FieldError: django.core.exceptions.FieldError: Cannot compute Sum('field_a'): 'field_a' is an aggregate I'm quite sure that SQL queries like this one: SELECT AVG(field_a), SUM(field_a) FROM random_table GROUP BY product Are totally valid. To recap: How I could apply multiple aggregation functions on the same field using annotate? -
Make HTML custom field sortable in django-admin
I have a very simple model that just consists of a name and serial number. I can use that serial number to ask for a status on an API and I want to display the result as icon/HTML: class ProductAdminForm(admin.ModelAdmin): class Meta: model = Product fields = ["get_status", "name",] def get_status(self, obj): status = get_status_from_API(obj)["status"] style = """style="height: 10px; width: 10px; border-radius: 50%; COLOR display: inline-block;" """ if status == 2: new_style = style.replace("COLOR", "background-color: green;") elif status == 2: new_style = style.replace("COLOR", "background-color: red;") else: new_style = style.replace("COLOR", "background-color: grey;") return mark_safe(f"""<span class="dot" {new_style}></span>""") How can I make the get_status column sortable? -
New ckeditor's plugin is not showing
I am trying to add a Plugin in django-ckeditor in my BlogApp. How i am trying to do :- I have downloaded a plugin from ckeditor site named hkemoji and I have pasted it in the main plugins file of ckeditor but when i try to check in browser then it is not showing in Browser. I have seen many tutorial but nothing worked for me. Any help would be appreciated. Thank You in Advance. -
How to get data from model to model when user click button in django
So in my website, i have this page with products, and another page titled " MyList ", so 2 templates. The page with the products has a model which stores the products ( name, price , link). So what I want to do is the following: I want to have a button for every product, and when the user clicks it, that product should be added to his list page. Like on a shop, when you add a product to your cart. But I really don't understand how to do this, and how my view should look like :/ in this image u can see the webpage with the productshere is the model of the products -
Django not recognizing blocks and endblocks in HTML
this block isn't recognizing my HTML code, which is weird. Is there anyway to fix this? <!DOCTYPE html> {% extends 'base.html %} {% block content %} <!DOCTYPE html> <div style="border: 2px solid #000;"> <h1> This is the body </h1> <p> Here is where you put stuff </p> </div> {% endblock content %} -
Problem with TypeError: a bytes-like object is required, not 'str'
recently I started with Django, and now I'm working on a website and I have an error. Note: I use Manjaro Linux. I have found a template online (calorietracker is the name)that I want to use some parts for my website but I cannot run this template. This is what I get when I try to run it... (calorietracker) [mahir@mahir-pc mysite]$ ./manage.py runserver Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ma1bolg3s/.local/share/virtualenvs/calorietracker-UDGAzgdx/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/ma1bolg3s/.local/share/virtualenvs/calorietracker-UDGAzgdx/lib/python3.7/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/home/ma1bolg3s/.local/share/virtualenvs/calorietracker-UDGAzgdx/lib/python3.7/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/ma1bolg3s/.local/share/virtualenvs/calorietracker-UDGAzgdx/lib/python3.7/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/home/ma1bolg3s/.local/share/virtualenvs/calorietracker-UDGAzgdx/lib/python3.7/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/ma1bolg3s/calorietracker/mysite/mysite/settings.py", line 72, in <module> "default": django_cache_url.parse(os.getenv("MEMCACHED_URL")) File "/home/ma1bolg3s/.local/share/virtualenvs/calorietracker-UDGAzgdx/lib/python3.7/site-packages/django_cache_url.py", line 60, in parse if '?' in path and query == '': TypeError: a bytes-like object is … -
DRF - created_by and last_updated_by fields - how to make it work?
How to make created_by and last_updated_by fields work in Django REST Framework? Created by should be populated when the object is created and last_updated_by should be updated any time the object is updated. The usual way is to use CurrentUserDefault but that is not working on PATCH methods if the last_updated_by is not included in the payload. last_updated_by = serializers.HiddenField(default=serializers.CurrentUserDefault()) Do you know how to do that? Maybe the best way would be to modify the serializer data inside the ViewSet but I can't figure out how. -
Dynamically determine Django template tags file to be loaded inside {% load %} using a variable
I have a set of applications in a Django project all of which have similar templates. In each template for each application, I load the template tags file I have defined for that application: {% load <appname>tags %} But since appname is different for every application, it causes the templates (which are identical otherwise) to differ. I can determine appname programmatically inside a template, so all I need is a way to do something like this: {% load appname|add:'tags' %} Is such a thing possible? The idea above doesn't work because the result of the expression is parsed directly, rather than being interpreted the way other tags are. The end goal is to have the templates which are the same across all the applications to be shared via soft links, to reduce code duplication. -
I am getting cannot serialize error in django 3.1
I have created a new user model as shown below: In this, I am creating a new user model and an admin from abstract user and BaseUserManager. I have also added some extra fields like gender and phone number. from django.contrib.auth.base_user import BaseUserManager from django.db.models import Manager from importlib._common import _ from django.db import models from django.contrib.auth.models import AbstractUser from phone_field import PhoneField # Create your models here. class CustomUserManager(BaseUserManager): """Define a model manager for User model with no username field.""" def _create_user(self, email, password=None, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('Users must have email address.') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Super user must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractUser): genders = ( ('m', _('Male')), ('f', _('Female')), ('o', _('Other')), ) username = None email = models.EmailField(_('email address'), unique=True) is_passenger = models.BooleanField(default=True) is_driver = … -
Cerbot error when completing challenges while running Django dockerized application with NGINX (and UWSGI)
When building and running my docker project with docker compose I get an error on the cerbot. The following errors were reported by the server: Domain: example.com Type: connection Detail: Fetching http://example.com/.well-known/acme-challenge/5bGuPxC5Bd-jqT6BOBS91XJg0cNjxc: Connection refused To fix these errors, please make sure that your domain name was entered correctly and the DNS A/AAAA record(s) for that domain contain(s) the right IP address. Additionally, please check that your computer has a publicly routable IP address and that no firewalls are preventing the server from communicating with the client. If you're using the webroot plugin, you should also verify that you are serving files from the webroot path you provided. My docker compose file part of the proxy is: proxy: build: context: ./proxy volumes: - static_data:/vol/static - ./proxy/default.conf:/etc/nginx/conf.d/default.conf ports: - "80:80" depends_on: - web And my docker file of the proxy is: FROM nginxinc/nginx-unprivileged:1-alpine COPY ./default.conf /etc/nginx/conf.d/default.conf COPY ./uwsgi_params /etc/nginx/uwsgi_params USER root RUN mkdir -p /vol/static RUN chmod 755 /vol/static RUN apk add --no-cache python3 python3-dev py3-pip build-base libressl-dev musl-dev libffi-dev gcc cargo sudo RUN pip3 install pip --upgrade RUN pip3 install certbot-nginx RUN mkdir /etc/letsencrypt RUN certbot --nginx -d example.com --email info@example.com -n --agree-tos --expand USER nginx My understanding is that the … -
post_save signal in django
I want to save the user IP address and the reference link in UserLog whenever the user performs any changes in the model. Currently, I am using post_save signal for this purpose. But the problem is, that it does not pass the request argument that's why I am unable to use request.META.get. Can anyone guide me to this or is there any other best practice to perform this. @receiver(post_save, sender=Session) def session_added_success(sender, instance, created, **kwargs): user = request.user action = "Logout" action_from_page = request.META.get('HTTP_REFERER') campus = request.user.campus remarks = f"{user} created a new session" login_ip = request.META.get('REMOTE_ADDR') if created: log = UserLog.objects.create( user=user, action=action, action_from_page=action_from_page, campus=campus, remarks=remarks, ip_address=login_ip) if created == False: print("Record Updated") -
Is there a way to set @csrf_exempt decorator to a view class?
I am trying to allow sending POST request without CSRF token, but getting an issue #view.py from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework import viewsets from .serializer import AuthorSerializer, MessageSerializer from .models import Author, Message @csrf_exempt class MessageViewSet(viewsets.ModelViewSet): queryset = Message.objects.order_by('-send_time') serializer_class = MessageSerializer def listMessages(self, page): per_page = 5 queryset = Message.objects.all()[page * per_page: page * per_page + per_page] return JsonResponse(queryset, safe=False) class AuthorViewSet(viewsets.ModelViewSet): queryset = Author.objects.all() serializer_class = AuthorSerializer AttributeError: 'function' object has no attribute 'get_extra_actions' Is there a way of getting this working? -
Will Django run on Windows Server 2019 or 2016?
I am trying to launch my app which i have created using flutter and django.I have started a server, the server provider is asking which OS i want in my server ,he is giving the option of Windows server 2016 and 2019. Which one should i choose? How will Django work in a Windows Server?