Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying to save the form data to database
How to access form data and save it into database. I tried In this way, But i'm getting None value -
How to get user object by email filtering in Django
I am trying to get a specific user in Django via email filtering using default user model. I am doing the following in my views.py but it is not working: from django.contrib.auth.models import User ... email = "abc@gmail.com" user = User.objects.get(email = email)' but its getting be following error Internal Server Error: /editor/share Traceback (most recent call last): File "D:\stocksapp\winenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\stocksapp\winenv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\stocksapp\winenv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\stocksapp\main\views.py", line 138, in shareCode obj = Code.objects.get(id=id,user = user) File "D:\stocksapp\winenv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\stocksapp\winenv\lib\site-packages\django\db\models\query.py", line 390, in get clone = self.filter(*args, **kwargs) File "D:\stocksapp\winenv\lib\site-packages\django\db\models\query.py", line 844, in filter return self._filter_or_exclude(False, *args, **kwargs) File "D:\stocksapp\winenv\lib\site-packages\django\db\models\query.py", line 862, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "D:\stocksapp\winenv\lib\site-packages\django\db\models\sql\query.py", line 1263, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "D:\stocksapp\winenv\lib\site-packages\django\db\models\sql\query.py", line 1287, in _add_q split_subq=split_subq, File "D:\stocksapp\winenv\lib\site-packages\django\db\models\sql\query.py", line 1225, in build_filter condition = self.build_lookup(lookups, col, value) File "D:\stocksapp\winenv\lib\site-packages\django\db\models\sql\query.py", line 1096, in build_lookup lookup = lookup_class(lhs, rhs) File "D:\stocksapp\winenv\lib\site-packages\django\db\models\lookups.py", line 20, in __init__ self.rhs = self.get_prep_lookup() File "D:\stocksapp\winenv\lib\site-packages\django\db\models\lookups.py", line 70, in get_prep_lookup return self.lhs.output_field.get_prep_value(self.rhs) File "D:\stocksapp\winenv\lib\site-packages\django\db\models\fields\__init__.py", line 965, in get_prep_value return … -
How to pass django request using pool in multiprocessing
from django.http import JsonResponse import pymongo import json from bson.json_util import dumps myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["game"] mycol = mydb["test_collection"] def fetch_data(request): mycol = mydb["Eugenie_Table"] qry = {'country': country} query = mycol.find(qry).limit(10) data = json.loads(dumps(query)) return data def handle_cache(request): from multiprocessing.pool import ThreadPool pool = ThreadPool(processes=4) async_result = pool.apply_async(fetch_data, args=(request)) return_val = async_result.get() return JsonResponse(return_val, safe=False) Here i am using django with pymongo for fetching data from mongodb database. Here i am passing request argument to fetch_data() function. But i am getting below error. TypeError at / fetch_data() missing 1 required positional argument: 'request' Please have a look. -
NoReverseMatch at register - Django
I'm trying to add an email confirmation feature to my django project. I already created a view and a url, but i'm getting this error now: Reverse for 'activate' with keyword arguments '{'uidb64': 'MzA', 'token': '55y-fec02444935d88a056dc'}' not found. 1 pattern(s) tried: ['activate/<uidb64:\\[0\\-9A\\-Za\\-z_\\\\\\-\\]\\+\\)>/<token:\\[0\\-9A\\-Za\\-z\\]\\{1,13\\}\\-\\[0\\-9A\\-Za\\-z\\]\\{1,20\\}\\)/\\$>\\)/$'] I think the error should be in the url, here it is: path('activate/<uidb64:[0-9A-Za-z_\-]+)>/<token:[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$>)/', views.activate, name='activate'), Am i declaring it in a wrong way? Thanks in advance -
how to handle webhook validation requests with MSgraph?
I'm trying to register my web app in Microsoft azure ,to get notification about users one-drive change . to do so I need to register my app for getting notification. I've been following these instructions:Create subscription and here Handling webhook validation requests but I need some help with the validation of the webhook. When a new subscription is created, OneDrive will POST a request to the registered URL(my web app or maybe I'll use azure function) in the following format: POST https://contoso.azurewebsites.net/your/webhook/service?validationtoken={randomString} Content-Length: 0 For the subscription to be created successfully, my service must respond to this request by returning the value of the validationtoken query string parameter as a plain-text response. HTTP/1.1 200 OK Content-Type: text/plain {randomString} I'm using django , how do I make response in python like they asked? this is how I send the first post request def create_subscription(token): payload = { "changeType": "updated", "notificationUrl": notification_url, "resource": "/me/drive/root", "expirationDateTime": "2030-01-01T11:23:00.000Z", "clientState": "client-specific string" } headers = { "Authorization": token['access_token'], "Host": "graph.microsoft.com", "Content-Type": "application/json" } response = requests.post("https://graph.microsoft.com/v1.0/subscriptions".format(graph_url), data=json.dumps(payload), headers=headers) this is how I make the response for the POST request of Microsoft def validate_subscription(request): if request.method == 'POST': url = request.get_full_path() parsed = urlparse.urlparse(url) validation_string = … -
django rest: testing file upload but request.data is empty
I try to test file upload with django rest framework, but the request.data is empty test: def test_update_story_cover(self): auth_token, story_id = self.create_story() image_path = os.path.join(os.path.dirname(__file__), 'book.jpg') url = reverse('story_modify', kwargs={'pk': story_id}) with open(image_path) as cover: response = self.client.patch( url, data={'cover': cover, 'title': 'test title'}, content_type='multipart/form-data', HTTP_AUTHORIZATION=auth_token) self.assertEqual(response.status_code, status.HTTP_200_OK) view: class StoryModifyView(RetrieveUpdateDestroyAPIView): ... def update(self, request, *args, **kwargs): print(request.data) print(request.FILES) ... the output is <QueryDict: {}> {} <MultiValueDict: {}> -
Django - reverse not found
I'm trying to add an Email confirmation feature to my Django project, where a user has to confirm it's email using the link provided by the site. I already added the view, the url and a template, but i keep getting the error: Reverse for 'activate' not found. 'activate' is not a valid view function or pattern name. 1 {% autoescape off %} 2 Hi {{ user.username }}, 3 Please click on the link to confirm your registration, 4 http://{{ domain }}**{% url 'activate' uidb64=uid token=token %}** 5 {% endautoescape %} I don't know where this error is coming from, i think i defined my view properly and added it to my urls.py, i'm following this tutorial. Here is my view: def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) # return redirect('home') return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!') The url: from .views import activate path("activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$", views.activate, name='activate') And acc_active_email.html {% autoescape off %} Hi {{ user.username }}, Please click on the link to … -
How to fix "cannot unpack non-iterable NoneType object" error in django admin whilst using customer user model
I am trying to use a custom user model and I am working with the AbstractBaseUser class.However, when I try to create a new user from the admin end, I get this error - "cannot unpack non-iterable NoneType object" I am able to view users from the admin end, but when I try to add new user. I get this error my custom user model class User(AbstractBaseUser): """docstring for Users""" status = ( ('1', 'Verified'), ('0', 'Unverified'), ) username = models.CharField(max_length=200,unique=True) email = models.EmailField(max_length=200,unique=True) name = models.CharField(max_length=1024) password = models.CharField(max_length=1024) phone = models.CharField(max_length=1024) country = models.CharField(max_length=50) state = models.CharField(max_length=1024) city = models.CharField(max_length=1024) address = models.CharField(max_length=1024) age = models.CharField(max_length=1024, null=True) verified = models.CharField(max_length=1, default=0) verification_code = models.CharField(max_length=1024, null=True) is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) pass_code = models.CharField(max_length=1024) avatar = models.ImageField(upload_to=upload_user_image,default=None, max_length=1024) bio = models.TextField(max_length=1024,default=None) registration_date = models.DateTimeField() slug = models.SlugField(max_length=255,unique=True) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'username','phone','country','state','city','address','age','registration_date'] def save(self, *args, **kwargs): self.slug = slugify(self.name) super(User, self).save(*args, **kwargs) def __str__(self): return self.name def get_full_name(self): return self.name def get_short_name(self): return self.name def has_perm(self, perm, obj=None): #"Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): #"Does the user have permissions to view … -
I am not able to escape html in django tinyMCE
I am learning django currently and I faced this issue while trying to escape my HTML which was read from my database. I tried to use |safe in my template but it is not working. Below is the code I am tried in my template {% load static %} <!-- Prism CSS --> <link href="{% static "tinymce/css/prism.css" %}" rel="stylesheet"> </head> <body> {% for tut in tutorials %} <p>{{tut.tutorial_title}}</p> <p>{{tut.tutorial_published}}</p> <p>{{tut.tutorial_content|escape|safeseq}}</p> <br><br> {% endfor %} <!-- Prism JS --> <script src="{% static "tinymce/js/prism.js" %}"></script> </body> My extected output is plain text without html tags -
django delete objects if date check-out equal date computer
can any body suggest me any idea about How to delete an object when the exit time arrives Example There is a customer of the day of entry and the day of departure What is the code to delete the object on the date of the date of synchronization with the date of the date of the computer -
Django save() always create a new object
I have this model in my app which is meant to auto-generate it's primary Key based on a method added in the save(). However, for each object, I will be expected to make updates of certain fields. Right now, anytime I make an update on the admin side (testing use cases) it instead creates a new record of the PK instead of updating the existing one. Any thoughts on how to remedy this? class DeploymentTask(models.Model): deployment_id = models.CharField( 'Deployment Task ID', primary_key=True, max_length=25, editable=False) title = models.CharField(max_length=100) current_status = FSMField('Current Status', default=STATES[0], choices=STATES) site_id = models.ForeignKey( Site, related_name='+', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) refuel_record = models.ManyToManyField(RefuelRecord) def __str__(self): """String for representing the Model object.""" return self.deployment_id class Meta: db_table = 'rm_deployment_task' verbose_name_plural = 'Deployment Tasks' def get_absolute_url(self): return reverse('deployment_id-view', args=[str(self.deployment_id)]) def save(self): today = datetime.datetime.now() ticket_count = DeploymentTask.objects.filter( created_at__year=today.year, created_at__month=today.month).count() + 1 new_task_id = 'DPT-' + str(str(datetime.date.today().year)) + str( datetime.date.today().month).zfill(2) + str( datetime.date.today().day).zfill(2) + '-' + str(ticket_count).zfill(6) self.deployment_id = new_task_id super(DeploymentTask, self).save( update_fields=['refuel_record','updated_at']) -
Django rest framework custom Response middleware
I use Django Rest Framework with rest_auth (/login, /logout/, /register...) I have a Middleware, normally triggered by user_logged_in or user_logged_out signals. In my Middleware, I want to use Response object from Rest framework. My middleware.py from django.contrib.sessions.models import Session from django.contrib.auth import logout from django.contrib.auth.models import AnonymousUser from rest_framework.response import Response from rest_framework import status class OneSessionPerUserMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated: if request.user.session_key != Session.objects.filter(session_key__in = request.user.session_key): logout(request) return Response(request) return self.get_response(request) I suppose that I pass my condition, but I get this error : The response content must be rendered before it can be accessed How to use correctly the API Response object in a middleware ? And I don't understand really what is : self.get_response = get_response ? -
Django Rest Framework JSONAPI and sideloaded/included resources
I am using the Django Rest Framwork JSON API for my Ember back end. The (data) response I am getting back includes the "relationship" key but I need to sideload resources for a particular model, and hence want to include the "included" key as shown on the Ember docs https://guides.emberjs.com/release/models/relationships I have a Product model with a FK relationship to a Tax model. Here is my tax serializer: from rest_framework_json_api import serializers from .models import Tax class TaxSerializer(serializers.ModelSerializer): class Meta: model = Tax fields = ('id', 'name', 'amount') Here is my product serializer: from rest_framework_json_api import serializers from .models import Product from tax.serializers import TaxSerializer included_serializers = { 'tax': TaxSerializer } class Meta: model = Product fields = ('id', 'name', 'image', 'price','tax') class JSONAPIMeta: included_resources = ['tax'] For this I've followed the example from https://www.mattlayman.com/blog/2017/sideload-json-api-django/ However, my response still includes the "relationships" key, and not the "included" key eg "data" : [ { "type":"products", "id": "1", "attributes": {...omitted for brevity ... }, "relationships": { "tax": { "data": { "type":"tax", "id":"1" } } } }, {...etc....} ] -
How to set product attributes to basket line in Oscar
I'm new to Django-oscar and working on Basket now I can add products as lines to the basket easily but what if I want to choose a specific Product attribute to add to basket for example product A has attributes {'size': ['M', 'S'], 'color': ['red', 'blue']} what should i do if i want to add product A with size M and color blue to the basket? -
how to save multiple Django forms with foreign keys?
I know this question has been asked before and I applied the suggested solutions but still my code is not working. I am trying to save 3 forms which one of models has foreign keys of the other two. I try commit=false at first and then save but I still get the IntegrityError. I share the code to explain better the question. I will really appreciate it if someone can help me with this issue. Here is my models.py: class Species(models.Model): name = models.CharField(max_length=255, verbose_name="Name",) obs_type = models.CharField(max_length=255, choices = species_choices,default='none' ) def __str__(self): return self.name class POI(models.Model): geometry = models.PointField(srid=4326) def __str__(self): return "Point(%s)"%(self.geometry) class Observation(models.Model): species = models.ForeignKey(Species, on_delete=models.CASCADE, verbose_name="Species",) poi = models.ForeignKey(POI, on_delete=models.CASCADE, verbose_name="POI",) description = models.CharField(max_length=255, default='SOME STRING',) date = models.DateField(verbose_name="Date") photo = models.ImageField(upload_to='media', default='no image') Here is my forms.py: class ObservationForm(ModelForm): class Meta: model = Observation fields = ['description','date', 'photo'] widgets = {'date': forms.DateTimeInput(attrs={'class': 'datetime-input'})} class SpeciesForm(ModelForm): class Meta: model = Species fields = ['name','obs_type'] class POIForm(ModelForm): class Meta: model = POI fields = ['geometry'] geometry = PointField( widget=OSMWidget( attrs={'map_width': 600, 'map_height': 400, 'template_name': 'name.html', 'default_lat': 57, 'default_lon': 12})) and the views.py: def observe(request): context = { 'observation_form': ObservationForm(), 'species_form': SpeciesForm(), 'poi_form': POIForm() } if … -
Model method doesnt work in template calling
I am having a model in my admin file : class ExampleClass(PHAdmin): # class variables and stuff def refresh_page(self): self.message_user("Page refreshed") return HttpResponseRedirect(/..) And in my custom template html file : # other code {% if messages %} <ul class="messages"> {% for message in messages %} <li>{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} <li> <a href="{{ ExampleClass.refresh_page }}" >Refresh</a> </li> My problem is that this link-button is supposed to call the model function and then refresh the page , which is not . When I inspect the element from my browser I see that the href field is empty so the function is not called. Also , in PyCharm where I am working I get the error : Cannot resolve file ' Inspection info: This inspection checks unresolved file reference in this HTML So I guess the template is unable to find this method but I can't find out why . Any help ? -
How can i create custom users with only forms?
I am a beginner in Django an am using version 2.2 .I created a user form to sign a user in the site but it cant add other field information to the database I have tried adding other fields in the fields list add adding fields but nothing works` forms.py from django import forms from django.contrib.auth import ( authenticate, get_user_model ) User = get_user_model() class UserRegisterForm(forms.ModelForm): username = forms.CharField(label='PUsername') email = forms.EmailField(label='Email address') email2 = forms.EmailField(label='Confirm Email') password = forms.CharField(widget=forms.PasswordInput,label='Password') password2 = forms.CharField(widget=forms.PasswordInput,label='ConfirmPassword') age = forms.CharField(label='your age') info = forms.CharField(label='info about you') class Meta: model = User fields = [ 'username', 'email', 'email2', 'password', 'password2', 'age' 'info' ] def clean(self, *args, **kwargs): username = self.cleaned_data.get('email') email = self.cleaned_data.get('email') email2 = self.cleaned_data.get('email2') password = self.cleaned_data.get('password') password2 = self.cleaned_data.get('password2') if email != email2: raise forms.ValidationError("Emails must match") email_qs = User.objects.filter(email=email) if password != password2: raise forms.ValidationError("Passwords must match") email_qs = User.objects.filter(email=email) if email_qs.exists(): raise forms.ValidationError( "This email has already been registered") username_ex = User.objects.filter(username=username) if username_ex.exists(): raise forms.ValidationError("This username is taken") return super(UserRegisterForm, self).clean(*args, **kwargs) views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate,get_user_model,login,logout from .forms import CreateUserForms import random import string def register_view(request): if request.method=='POST': frm=CreateUserForm(request.POST) if frm.is_valid(): username, email, … -
Conditions in IF Statements requires values to be specified explicitly
I have created a template that displays items from a loop, Within the loop there is a condition, but the condition does not work unless specified explicitly. {% extends 'blog/base.html' %} {% block content %} <h3>{{ user.username }}</h3> {% for project in projects %} {% if user.username == 'testuser' %} <h5>{{ project.title }}</h5> <p>{{ project.description }}</p> <p>{{ project.objectives }}</p> <pre>{{ project.score }}</pre> <pre>{{ project.student_id }}</pre> {% endif %} {% endfor %} {% endblock content %} The above code works perfectly and returns the records assigned to the user named testuser. But if I write the code as below, it skips all records {% extends 'blog/base.html' %} {% block content %} <h3>{{ user.username }}</h3> {% for project in projects %} {% if user.username == project.student_id %} <h5>{{ project.title }}</h5> <p>{{ project.description }}</p> <p>{{ project.objectives }}</p> <pre>{{ project.score }}</pre> <pre>{{ project.student_id }}</pre> {% endif %} {% endfor %} {% endblock content %} -
Django2 + Ajax: Ajax returning HTML page instead of the desired response
i am making an AJAX POST request to django and i want to populate a <select> field in my django admin page with the response, but i get a full html page in return. i have set some print() in my django view to see the progress of the request, but none of them gets triggered. AJAX returns success, DJANGO post returns status 200. i am completely confused. here's my Ajax Call : (function($) { $(function() { var selectField = $('#id_parent'), verified = $('#id_child'); function toggleVerified(value) { if (value) { // verified.empty(); verified.show(); console.log(value); } else { verified.hide(); }; }; function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; }; var csrftoken = getCookie('csrftoken'); // show/hide on load based on pervious value of selectField toggleVerified(selectField.val()); // show/hide on change selectField.change(function() { toggleVerified($(this).val()); $.ajaxSetup({ beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }); $.ajax({ type: 'POST', url: '/catalogue/get_children/', // dataType: "json", contentType: "application/json; charset=utf-8", data : {"id": $(this).val()}, … -
If there a problem solving with ValueError: source code string cannot contain null bytes
After when i carried over my file with code in other folder and late tried to runserver with manage.py i will get error: ValueError: source code string cannot contain null bytes -
Django 2.2 can't connect to ElastiCache Redis on AWS ElasticBeanstalk
I have Django 2.2 app running on AWS that is working correctly with Memcached on AWS ElastiCache but for some reason, it will not connect to a Redis server on AWS ElastiCache. I have added the permissions to my security groups but no luck and the http request just hangs until it will timeout. Even though a similar behavior is usually related with security groups, I feel that I may be missing some Redis specific packages in my .requirements or Yum packages in .ebextensions as everything is working correctly locally, and with Memcached server on AWS as well. Perhaps, do I have to somehow start/enable the Redis server to start accepting connections? Here is what I have. settings.py CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://myendpoint.cache.amazonaws.com:6379', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } .ebextensions packages: yum: python36-devel: [] mysql-devel: [] libmemcached-devel: [] gcc: [] gcc-c++: [] libffi-devel: [] option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "api.settings" requirements.txt blessed==1.15.0 botocore==1.12.137 cached-property==1.5.1 cement==2.8.2 certifi==2019.3.9 chardet==3.0.4 colorama==0.3.9 django-redis==4.10.0 Django==2.2.1 djangorestframework==3.9.2 docutils==0.14 future==0.16.0 future==0.16.0 idna==2.7 jmespath==0.9.4 jsonschema==2.6.0 mysqlclient==1.4.2.post1 pathspec==0.5.9 python-dateutil==2.8.0 python-memcached==1.59 pytz==2019.1 PyYAML==3.13 redis==3.2.1 requests==2.20.1 semantic-version==2.5.0 six==1.11.0 sqlparse==0.3.0 termcolor==1.1.0 texttable==0.9.1 urllib3==1.24.2 wcwidth==0.1.7 websocket-client==0.56.0 -
Create instance of Notification and save to DB each time message is received Django Channels
In my Django Channels 2.1.2 chat application, I have a Notification model that gives users notifications of unread messages (using JQuery). class Notification(models.Model): notification_user = models.ForeignKey(User, on_delete=models.CASCADE) notification_chat = models.ForeignKey(ChatMessage, on_delete=models.CASCADE) notification_read = models.BooleanField(default=False) I need to save an instance of the Notification model each time a message is received through the websocket (taking in chat and user as args). That instance will then be used to populate the notification center with unread notifications. When a user clicks on the red icon, the notification_read method will be triggered in consumers.py async def websocket_receive(self, event): # when a message is recieved from the websocket print("receive", event) message_type = json.loads(event.get('text','{}')).get('type') print(message_type) if message_type == "notification_read": # Update the notification read status flag in Notification model. notification_id = '????' notification = Notification.objects.get(id=notification_id) notification.notification_read = True notification.save() #commit to DB print("notification read") return This currently doesn't work because I don't have notification_id because notifications aren't being saved to the DB. I am unsure of how to write a method to do this each time a message is received over the websocket. My code is below. consumers.py class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): print('connected', event) other_user = self.scope['url_route']['kwargs']['username'] me = self.scope['user'] #print(other_user, me) thread_obj = … -
User is not iterable
Getting a user is not iterable error on my piece of api code. it happens whenever i attempt to call the userdetail class from rest_framework import viewsets, permissions from django.contrib.auth.models import User from .serializers import UserSerializer from django.contrib.auth import authenticate from django.db.models import QuerySet from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from rest_framework_simplejwt.authentication import JWTTokenUserAuthentication class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = UserSerializer class UserDetail(viewsets.ModelViewSet): serializer_class = UserSerializer def get_queryset(self) -> QuerySet: ser = authenticate(username="test", password="test") print(ser) return ser im using the default django user model from django.db import models from django.contrib.auth import get_user_model User = get_user_model() -
Django=1.8,suddently ran an exception says: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\Radhey\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 338, in execute_from_command_line utility.execute() File "C:\Users\Radhey\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 312, in execute django.setup() File "C:\Users\Radhey\Anaconda3\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Radhey\Anaconda3\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\Radhey\Anaconda3\lib\site-packages\django\apps\config.py", line 86, in create module = import_module(entry) File "C:\Users\Radhey\Anaconda3\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Radhey\Desktop\myproject\src\tweetme\hashtags\__init__.py", line 11, in <module> from tweets.api.serializers import TweetModelSerializer File "C:\Users\Radhey\Desktop\myproject\src\tweetme\tweets\api\serializers.py", line 5, in <module> from accounts.api.serializers import UserDisplaySerializer File "C:\Users\Radhey\Desktop\myproject\src\tweetme\accounts\api\serializers.py", line 8, in <module> User = get_user_model() File "C:\Users\Radhey\Anaconda3\lib\site-packages\django\contrib\auth\__init__.py", line 150, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL) File "C:\Users\Radhey\Anaconda3\lib\site-packages\django\apps\registry.py", line 199, in get_model self.check_models_ready() File "C:\Users\Radhey\Anaconda3\lib\site-packages\django\apps\registry.py", line 131, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. -
How to run development server?
I'm setting up a development server in Pycharm. I have tried to change the interpreter. raise ImproperlyConfigured("The %s setting must be a list or a tuple. " % setting) Its supposed to show "Hello World" in the browser.