Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python error: Requested setting INSTALLED_APPS, but settings are not configured
I am new to Python. We have an application using Python + nginx + uwsgi and able to start 'uwsgi' as service. However, it errors with the following message on uwsgi.log Error *** Operational MODE: preforking *** Traceback (most recent call last): File "./Mybot/wsgi.py", line 16, in <module> from websocket.views import sio File "./websocket/views.py", line 12, in <module> from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job File "/home/sathish/Mybot/venv/lib/python3.7/site-packages/django_apscheduler/jobstores.py", line 15, in <module> from django_apscheduler.models import DjangoJob File "/home/sathish/Mybot/venv/lib/python3.7/site-packages/django_apscheduler/models.py", line 46, in <module> class DjangoJob(models.Model): File "/home/sathish/Mybot/venv/lib/python3.7/site-packages/django/db/models/base.py", line 87, in __new__ app_config = apps.get_containing_app_config(module) File "/home/sathish/Mybot/venv/lib/python3.7/site-packages/django/apps/registry.py", line 249, in get_containing_app_config self.check_apps_ready() File "/home/sathish/Mybot/venv/lib/python3.7/site-packages/django/apps/registry.py", line 131, in check_apps_ready settings.INSTALLED_APPS File "/home/sathish/Mybot/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 57, in __getattr__ self._setup(name) File "/home/sathish/Mybot/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 42, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I tried the following 1) Added 'export DJANGO_SETTINGS_MODULE=Mybot.settings' 2) I am able to run the project using 'python manage.py runserver' and am able to access the page from browser INSTALLED_APPS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_apscheduler', 'jobs', 'websocket', ] I googled but I am unable to spot the issue. To my understanding … -
Django registration with confirmation email, error: save() got an unexpected keyword argument 'commit'
I'm trying to create confirm email system, bu I got the same error as in title, anyone know how to solve it? class StudentSignUpView(CreateView): model = User form_class = StudentSignUpForm template_name = 'registration/signup_form.html' def form_valid(self, form, **kwargs): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(self.request) mail_subject = 'Activate your account.' message = render_to_string('core/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') -
I am getting This Error While Starting Django Server
ForkingPickler(file, protocol).dump(obj) _pickle.PicklingError: Can't pickle : attribute lookup colors on main failed (venv) D:\ingenero\cpchemserver>Traceback (most recent call last): File "", line 1, in File "C:\Program Files\Python36\lib\multiprocessing\spawn.py", line 99, in spawn_main new_handle = reduction.steal_handle(parent_pid, pipe_handle) File "C:\Program Files\Python36\lib\multiprocessing\reduction.py", line 82, in steal_handle _winapi.PROCESS_DUP_HANDLE, False, source_pid) OSError: [WinError 87] The parameter is incorrect -
get_absolute_url creates blank link
get_absolute_url doesn't create url. Clicking in title of the post must lead to detail of the post. While I manually create url in address bar as blog/2020/1/3/check-text, it works. What could be the possible problem? Is it something to do with python version? models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default = timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() # the default manager published = PublishedManager() # our custom manager class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args = [ self.publish.year, self.publish.month, self.publish.day, self.slug, ]) views.py from django.shortcuts import render, get_object_or_404 from django.core.paginator import Paginator, PageNotAnInteger,\ EmptyPage from django.views.generic import ListView from .models import Post from .forms import EmailPostForm from django.core.mail import send_mail class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 3 template_name = 'blog/post/list.html' def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, … -
Deploy Django App to Azure with Windows Server VM
I have a VM Windows Server 2012 R2 and I would like to deploy a Django application to Azure with it. I connect to this VM remotely and installed IIS. Can someone write here what packages or features has to be installed on the VM remotely (with steps) and how this will be connected to Azure? -
Not getting messages in the form in django?
I am having registration form and users model in the users model I had kept the unique=true for email field after submitting the form with the duplicate email the error is getting in the in the full page like integrity error But I want to get the message in the form itself My models.py class users(models.Model): email=models.CharField(max_length=50,unique=True) password=models.CharField(max_length=50,default='0000000') room = models.ForeignKey(rooms,on_delete=models.CASCADE) goal = models.ManyToManyField(goals) style = models.ManyToManyField(designs) furn = models.ForeignKey(furniture,on_delete=models.CASCADE) My views.py def user_register(request): if request.method == 'POST': username=request.POST["username"] email = request.POST['email'] password = request.POST['password'] room = request.POST['room'] g=goal=request.POST['goal'] g = g.split(',') s=style=request.POST['style'] s=s.split(',') furn=request.POST['furn'] user = users(password=password,email=email) user.room=rooms.objects.get(pk=room) goal = goals.objects.filter(pk__in=g) style = designs.objects.filter(pk__in=s) user.furn = furniture.objects.get(pk=furn) user.save() user.goal.add(*goal) user.style.add(*style) return render(request,'register.html') My form.html <form action="{% url 'car:user_register' %}" method="POST" > {% csrf_token %} <div class="form-group"> <label for="username">Username</label> <input type="text" name="username" class="form-control" required> </div> <div class="form-group"> <input type="hidden" name="room" id="name" value=" "> </div> <div class="form-group" > <input type="hidden" name="goal" id="goal" value=" "> </div> <div class="form-group"> <input type="hidden" name="style" id="style" value=" "> </div> <div class="form-group" > <input type="hidden" name="furn" id="furn" value=" "> </div> <div class="form-group"> <label for="email">Email</label> <input type="text" name="email" class="form-control" required> </div> <div class="form-group"> <label for="password2">Password</label> <input type="password" name="password" class="form-control" required> </div> <div class="button"><input type="submit" value="Register" style="background-color:#000080;" class="btn btn-secondary … -
Django "order_by " excluding the first items
I have this model, and I need to reset or Purchased.bought_today every day automatically at 00:00. models.py class Purchased(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) collection = models.ForeignKey(Collection, on_delete=models.DO_NOTHING) last_purchased = models.DateTimeField(default=datetime.now) purchased_today = models.IntegerField(default=0) I thought of resetting it whenever I login, with a signal. but not found. models.py from django.contrib.auth.signals import user_logged_in from django.dispatch import receiver class Purchased(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) collection = models.ForeignKey(Collection, on_delete=models.DO_NOTHING) last_purchased = models.DateTimeField(default=datetime.now) purchased_today = models.IntegerField(default=0) @receiver(user_logged_in) def purchased_today_login(request, **kwargs): today = datetime.now().strftime("%Y-%m-%d") if purchased.last_purchased.date().strftime("%Y-%m-%d") != today: purchased_today = 0 subscription.save() user_logged_in.connect(purchased_today_login) If it worked it would be very good. How can I do that? -
React Chrome Extension: API response data can be viewed via React Chrome extension, is this alright?
Hi I am new to React development, and I am currently developing a Django-React application implementing DRF. I have installed a React Chrome extension to check some stuff but upon exploring I noticed that my API responses can be spied on via this Chrome extension. I am now starting to think if I've integrated React well on my Django app. Is it normal and safe to have these response data available via the extension? Here're some screenshots: Here is a NEWS section on the homepage which is loaded via React And someone can spy on the API data via React Chrome app -
graphene-django: Query all the models fields and not the requested fields
I have two models: class Type(models.Model): name = models.CharField(max_length=255) def __str__(self): return f'{self.name}' class Pet(models.Model): name = models.CharField(max_length=255) color = models.CharField(max_length=255) type = models.ForeignKey(Type, related_name="pets", on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return f'{self.type.name} {self.name}' The schema: class Type(DjangoObjectType): class Meta: model = TypeModel @classmethod def get_node(cls, info, id): return TypeModel.objects.get(id=id) class TypeConnector(graphene.Connection): count = graphene.Int() class Meta: node = Type def resolve_count(root, info): return len(root.edges) class Pet(DjangoObjectType): class Meta: model = PetModel interfaces = (relay.Node,) @classmethod def get_node(cls, info, id): return PetModel.objects.get(id=id) class PetConnector(graphene.Connection): count = graphene.Int() class Meta: node = Pet def resolve_count(root, info): return len(root.edges) class Schema(ObjectType): pets = graphene.ConnectionField(PetConnector) types = graphene.ConnectionField(TypeConnector) def resolve_pets(self, info, **kwargs): # TODO: Query for requested fields only return PetModel.objects.all() def resolve_types(self, info, **kwargs): # TODO: Query for requested fields only return TypeModel.objects.all() One of the goals of GraphQL is the performance. To make it the GraphQL must request to the database only the requested fields via GraphQL request (e.g: GraphiQL) If I request the following query: { pets { edges { node { color type { name } } } } } graphene-django library generate the follow SQL: 2020-01-03 03:16:18.184 UTC [136] LOG: statement: SELECT "pets_pet"."id", "pets_pet"."name", "pets_pet"."color", "pets_pet"."type_id" FROM "pets_pet" 2020-01-03 … -
NGINX - uWSGI or reverse proxy with python [duplicate]
This question already has an answer here: What's the advantage of putting nginx in front of uWSGI? 1 answer I know that you use NGINX as an application server when using PHP, for Node.js you use the http server from nodejs itself and use NGINX as a reverse-proxy. But what is recommended as application server for python frameworks like Flask or Django? NGINX does support python via uWSGI (https://www.nginx.com/blog/maximizing-python-performance-with-nginx-parti-web-serving-and-caching/) but is it actually faster than using the built-in web server? Or is there a better setup? -
How do I put env_file in Dockerrun.aws.json file?
I have env_file option in my docker-compose.yml file. However, when I use container-transform, every option is translated into dockerrun, but env_file variable. What is the efficient way to pass django environment variables to the docker deployed in elastic beanstalk? -
Django collectstatic not working on production with S3, but same settings work locally
I've been moving around some settings to make more defined local and production environments, and I must have messed something up. Below are the majority of relevant settings. If I move the production.py settings (which just contains AWS-related settings at the moment) to base.py, I can update S3 from my local machine just fine. Similarly, if I keep those AWS settings in base.py and push to production, S3 updates appropriately. In addition, if I print something from production.py, it does print. However, if I make production.py my "local" settings on manage.py, or when I push to Heroku with the settings as seen below, S3 is not updating. What about my settings is incorrect? (Well, I'm sure a few things, but specifically causing S3 not to update?) Here's some relevant code: __init__.py (in the directory with base, local, and production) from cobev.settings.base import * base.py INSTALLED_APPS = [ ... 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', ... 'storages', ] ... STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "global_static"), os.path.join(BASE_DIR, "media", ) ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' local.py # local_settings.py from .base import * ... STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') production.py from .base import * # AWS Settings AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = … -
Stripe, Django Rest Framework - AttributeError: 'tuple' object has no attribute 'get'
I constantly get an error whenever I make a POST request to /api/tickets/: Internal Server Error: /payment-stripe/ Traceback (most recent call last): File "/ENV/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/ENV/lib/python3.8/site-packages/django/utils/deprecation.py", line 96, in __call__ response = self.process_response(request, response) File "/ENV/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'tuple' object has no attribute 'get' [03/Jan/2020 03:17:09] "POST /payment-stripe/ HTTP/1.1" 500 58576 Here is my stripe payment handling view that I think is causing the problem, but I can't find out why: @require_http_methods(["POST"]) @csrf_exempt def stripe_payment_handling(request): """ The following code is copied from Stripe Docs. Everything inside the IF statements is how the ticket gets handled. """ payload = request.body # Checks for the signature of stripe. sig_header = request.headers['Stripe-Signature'] event = None try: # Tests if it can create a connection with Stripe. event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: # invalid payload: If it doesn't pass it gives back a 400 return "Invalid payload", 400 except stripe.error.SignatureVerificationError as e: # invalid signature: If the Stripe Signature is not there it wont accept it. return "Invalid signature", 400 # Create the a dictionary with the data event_dict = event.to_dict() print(event_dict) if … -
git bash freezes when I run "python manage.py runserver"
I'm trying to learn django and have already created my project using startproject. Now I want to run the server but it won't work in git bash. It works if I use powershell or cmd but it just freezes in git bash. It says "Watching for file changes with StatReloader" but does nothing. Please help I want to use git bash to run my commands. Thanks -
Selenium Error InvalidElementStateException "invalid element state: Element must be user-editable in order to clear it"
I have an input HTML element like this in Django <input id="id" type="number" maxlength="50"> When I want to find and clear it elm_input = self.wait.until(EC.presence_of_element_located((By.ID, elm_id))) elm_input.clear() elm_input.send_keys(value) It's got error InvalidElementStateException InvalidElementStateException invalid element state: Element must be user-editable in order to clear it" We cannot send key clear because selenium know CLEAR or DELETE Keys is an Charactics Keys not an Number Keys, It's don't send Keys to element input. So how can I we fix it, I had try ActionChains but It's not working with as well -
sql How to cap the number of record when doing group by
Suppose you have a 'like' rating records. user document timestamp You can see the count of ratings per each user select user, count(user) from rating group by user what if you want the count but capped at some number like 100 select user, min(100, count(user)) from rating group by user How can you do something like above in sql, and preferably django queryset? -
Django - return list of children from values() function?
I'm building a Django app and trying to return a list of objects inside of my values() dict. My sample models look like this - class State(models.Model): StateID = models.AutoField(primary_key = True) StateName = models.CharField(max_length = 30, default='State Name') StateAbbreviation = models.CharField(max_length = 4, default='SN') Population = models.IntegerField(default = 0) NationID = models.ForeignKey(Nation, on_delete=models.CASCADE) class City(models.Model): CityID = models.AutoField(primary_key = True) CityName = models.CharField(max_length = 30, default='City Name') Population = models.IntegerField(default = 0) StateID = models.ForeignKey(State, on_delete=models.CASCADE) What I would like to return is something along the lines of : [{ 'StateName': 'California' , 'NationID__NationName': 'United States' , 'Population': 90000000 , 'CityList': [{'CityName': 'Los Angeles', 'Population': 4000000},{'CityName': 'San Francisco', 'Population': 2000000}, ...more cities] }, { 'StateName': 'Texas' , 'NationID__NationName': 'United States' , 'Population': 50000000 , 'CityList': [{'CityName': 'Austin', 'Population': 1000000},{'CityName': 'Dallas', 'Population': 2000000}, ...more cities] }, ...more states ] Now, I would love to use the query below, but it of course doesn't work as I can't figure out how to return a list into a values() return object. Is this possible? StateList = State.objects.values('StateName', 'NationID__NationName', 'Population').annotate( CityList = City.objects.values('CityName', 'Population') ) I know I could do something like the query below, but the state info (state name, nation name, … -
Building a simple solution for object level permissions
Consider the following models: class Administrator(AbstractBaseUser, PermissionsMixin): etc class Issuer(models.Model): lists = models.ManyToManyField(List, etc) class List(models.Model): issuer = models.ForeignKey(Issuer, etc) class Member(models.Model): lists = models.ManyToManyField(List, etc) issuer = models.ForeignKey(Issuer, etc) In this app: each List belongs to an Issuer each Member belongs to an Issuer each List has one or more Members, Members can be on one or more lists each Issuer can have one or more Administrators, Administrators can have one or more Issuers Administrators are a custom user model using contrib.auth Question 1 I would like Administrators to only be allowed to create/view/edit Lists and Members that they share the same Issuer with. How can I do this? I assume the easiest method would be to query the user session when rendering each of the views? Question 2 I would like Administrators to be able to switch between Issuers they have access to, so that when they create/view lists or members the Issuer is automatically saved. Imagine a select field in the nav bar "Issuer 1, Issuer 2, Issuer 3, etc". What's the simplest way to achieve this? Passing the issuer.pk through the URL to render each view and using the permissions to Q1, or is there a … -
Django/knox backend login failing even when given proper username and password
I'm building user authentication in Django using the built-in user model and knox token authentication. Through postman, I'm able to create a new user which properly returns the username and a unique token for that user. However, when I attempt to hit my login path with correct username and password information, it returns a 400 Bad Request along with my validation error message "Incorrect Credentials." Any idea why this might be happening? Below is my login serializer, api, and url paths. # Login Serializer in serializers.py from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth import authenticate class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError('Incorrect Credentials') # Login API in api.py from rest_framework import generics from rest_framework.response import Response from knox.models import AuthToken from .serializers import LoginSerializer class LoginAPI(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) from django.urls import path, include from .api import RegisterAPI, LoginAPI, UserAPI from knox import views as knox_views urlpatterns = { path('auth', include('knox.urls')), path('auth/register', RegisterAPI.as_view()), path('auth/login', LoginAPI.as_view()), path('auth/user', UserAPI.as_view()), path('auth/logout', knox_views.LogoutView.as_view(), name='knox_logout'), } I … -
Make base_field of ArrayField unique for a table in Django
Goal The following should raise a ValidationError >>> m1 = MyModel(names=['name1']) >>> m2 = MyModel(names=['name1', 'name2']) >>> m1.save() >>> m2.save() django.core.exceptions.ValidationError: ... In plain English, if an element in a model's ArrayField matches an element in the database table a ValidationError should be raised Failed Solutions ArrayField docs don't mention the unique keyword so I tried doing this a couple ways (these are minimal code examples). Adding unique=True to the base_field didn't seem to the anything at all after running makemigrations and migrate # models.py ... class MyModel(models.Model) title = ArrayField( models.CharField(max_length=255, unique=True), ) ... # shell_plus from Django-extensions >>> m1 = MyModel(names=['name1']) >>> m2 = MyModel(names=['name1']) >>> m1.save() >>> m2.save() # no errors raised I tried adding unique=True to only the ArrayField. Django raises an error if an array is exactly the same. # models.py ... class MyModel(models.Model) title = ArrayField( models.CharField(max_length=255), unique=True, ) # shell_plus from Django-extensions >>> m1 = MyModel(names=['name1']) >>> m2 = MyModel(names=['name1']) >>> m1.save() >>> m2.save() django.core.exceptions.ValidationError: ... >>> m3 = MyModel(names=['name1', 'name2']) >>> m3.save() # no error raised The above makes sense when I think it about. I then tried to add unique=True to both the base_field and to the ArrayField but the behavior … -
TemplateSyntaxError when overriding admin templates
I need to override the index.html template from Django Admin. Following the documentation, I created a index.html file inside my templates/admin directory and paste the original content from here https://github.com/django/django/blob/master/django/contrib/admin/templates/admin/index.html I got this error: TemplateSyntaxError at /admin/ Invalid block tag on line 31: 'translate', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 3.0.1 Python Version: 3.6.8 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /home/croves/code/cita-django/cita/templates/admin/index.html, error at line 31 Invalid block tag on line 31: 'translate', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? 21 : </caption> 22 : {% for model in app.models %} 23 : <tr class="model-{{ model.object_name|lower }}"> 24 : {% if model.admin_url %} 25 : <th scope="row"><a href="{{ model.admin_url }}">{{ model.name }}</a></th> 26 : {% else %} 27 : <th scope="row">{{ model.name }}</th> 28 : {% endif %} 29 : 30 : {% if model.add_url %} 31 : <td><a href="{{ model.add_url }}" class="addlink"> {% translate 'Add' %} </a></td> 32 : {% else %} 33 : <td>&nbsp;</td> 34 : {% endif %} … -
Run python script from django app, display window on Raspberry Pi
I want to run an app from Django and have window open on the Raspberry Pi screen. On the Pi I have a Django project running on the web server. The Pi is running Raspbian I have a small game app called game.py on the Rpi. I want to be able to run the game.py from a tablet via a browser. I guess in other words can I launch a python app from a tablet using Django and have the app displayed on the RPi screen? If possible would this be handled through Django views.py file? -
Set the return type of the Django response as a list of objects
How to format the DRF response as a list of objects ? Here are my models: class User(models.Model): id = models.IntegerField(primary_key=True) email = models.EmailField() class Cars(models.Model): name = models.CharField() year = models.IntegerField() Serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email') class CarSerializer(serializers.ModelSerializer): class Meta: model = Cars fields = ('name', 'year') ViewSets: class UserViewSet(viewsets.ModelViewSet): queryset = Users.objects.all() serializer_class = UserSerializer permission_classes = default_permission_classes def get_serializer_class(self): if self.action == 'car': return CarSerializer return UserSerializer @action(detail=True) def cars(self, request, *args, **kwargs): all_cars = self.get_object().get_all_cars() serializer=CarSerializer(all_cars, many=True, context={'request': request}) return JsonResponse(serializer.data, safe=False) Here on calling cars endpoint in User rest API, I get a list of cars in the following format: [ { "name": "civic", "year": "2004", }, { "name": "city", "email": "2005", } ] Which is the expected response from this endpoint. The issue is the serializer class (return type of the response). I want it the class to be a list of Car objects but it's an object. Please let me know how to achieve this. -
ImportError: Failed to import test modul
here is my project structure : # Create your tests here. from django.contrib.auth.models import User from django.test import TestCase from g_attend.website.models import Profile class TestIndex(TestCase): def setUp(self): new_user = User.objects.create_user(username='user', password='pass') Profile.objects.create(user=new_user, type="Admin", full_name="Ahmed Wagdy") def test_visit_unauthorised(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'home.html') I've used python manage.py startapp to create both apps website and panel Now when I added tests to website.tests.py as follows : # Create your tests here. from django.contrib.auth.models import User from django.test import TestCase from g_attend.website.models import Profile class TestIndex(TestCase): def setUp(self): new_user = User.objects.create_user(username='user', password='pass') Profile.objects.create(user=new_user, type="Admin", full_name="Ahmed Wagdy") def test_visit_unauthorised(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'home.html') but I try to run tests I get this error: ImportError: Failed to import test module: website.tests -
How to get parameters from script src in django?
How to retrieve parameters from script src, in django? This script located outside of my django app. (not in my templates, other website) Here is an example of script: <script src="http://127.0.0.1:8000/" par1='value'></script> I need to get parameter par1 in my view. How I can do that using django view and request?