Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to implement Session AND Token Authentication together in DRF?
I'm kind of new with DRF and I am building a website. I've successfully implemented a basic authentication using forms and the code below: def login_request(request): if request.method == 'POST': form = AuthenticationForm(request=request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('/user-area/') form = AuthenticationForm() return render(request = request, template_name = "myapp/login.html", context={"form":form}) After logged in, the user is redirected to a page that shows some data about him. My question is: Is it possible to show the user Authentication Token on this page (on browser, with my HTML template)? So the user would be able to just copy the Token and use it in his device to request some data (on another page), without needing of provide his login/password credentials? I'm looking for the both Authentication Method... to allow the user login providing the credentials on his browser AND use only the token on his external device. There is a similar question, but without answers here: DRF both Token and Session Authentication -
How to use Django ORM with cloud NDB?
I am trying to create an django project in which database is handled by cloud NDB. I checked out the cloud ndb documentation here and it only specifies the middleware that I need to include in my settings.py file. I want to use django ORM facility but I don't know how to do that with cloud NDB. I don't even know if I can use it so any answers are welcome. Thank you for help. -
Django REST Framework got Server Error 500
I followed the turial at django-rest-framework quickstart I have two URLs namely /users/ and /groups/ The group works perfectly: but the user url gets a error like this: server error 500 I set DEBUG to True then add some host to ALLOWED_HOST in settings.py: DEBUG = False ALLOWED_HOSTS = [ '127.0.0.1', 'localhost' ] INSTALLED_APPS = [ 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] my urls.py: from django.contrib import admin from django.urls import include, path from rest_framework import routers from django_rest.django_rest_app import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] this is my serializers.py: from django.contrib.auth.models import User, Group from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url','username','email','group'] class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ['url','name'] and this is my views.py: from django.shortcuts import render from django.contrib.auth.models import User, Group from rest_framework import viewsets from rest_framework import permissions from django_rest.django_rest_app.serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer permission_classes = … -
How to show django debug tool bar to just Admin?
I am working on a project, so I want to show djnago debug toolbar just to admins. So I added the django debug tool bar, and I want it not to show to all the users with this piece of code. if request.user.is_admin and request.GET.get('debug') == 'true': return True DEBUG_TOOLBAR_CONFIG = { 'SHOW_TOOLBAR_CALLBACK': 'webapp.settings.show_toolbar' } but it does not seem to have an impact. Let me know if I am doing it right. or is there any other way possible to accomplish the same goal. -
Django clean() method not raising exception when form.is_valid() is called
I want to return a custom message based on the error when a user submits a form but I don't know how to catch the exception. I have extended the clean() method to raise some ValidationError's: class EmailChangeForm(forms.Form): email1 = forms.EmailField(label='New Email') email2 = forms.EmailField(label='Confirm Email') password = forms.CharField(label='Password', widget=forms.PasswordInput) def clean(self): cleaned_data = super().clean() new_email1 = cleaned_data.get('email1', None) new_email2 = cleaned_data.get('email2', None) print(new_email1, new_email2) try: user = User.objects.get(email=new_email1) except: user = None if user is not None: raise forms.ValidationError('Email is already in use.', code='inUse') elif new_email1 != new_email2: raise forms.ValidationError('New emails don\'t match.', code='noMatch') return cleaned_data But when i call form.is_valid() it only returns a boolean. I know it's being called because using print will output something to the console. Is it possible to get the custom messages via .is_valid()? -
Alternatives to Django post_save
a question on Django signals, e.g. post_save: My understanding is that object updates caused by a post_save signal fire an additional call on that object's post_save. Taking it a step further, syncing two models via 2 post_save signals calls post_save on one model's object, which then calls post_save on the other model's object, then post_save back on the original, at the least. Is there a way to disable the recursion here? Also, in general, is this actually a pattern that is scalable and endorsed by the Django community? Recently came across this article suggesting overriding model save function, but it seems like that approach isn't viewed positively across Django users either. Is there another way? -
Blank Page for View in Django
I'm trying to create a view for a model in an app in Django. I'm still learning the ropes on this. I've created a model and put a view and url together. When I go to the localhost/app I'm getting a blank page so I can see the view exists but none of my objects are populating. I've checked that the objects exist using localhost/admin from django.shortcuts import render from .models import Menu from django.http import HttpResponse def take_order(request): menus = Menu.objects.all() return render(request, 'menu_items/menu_items_list.html', {'menus': menus}) from .models import Menu from django.conf.urls import url from . import views app_name = "menu_items" urlpatterns = [ url(r'^$', views.take_order), ] from django.db import models class Menu(models.Model): entree = models.CharField(max_length=255) description = models.TextField() def __str__(self): return self.entree return self.description -
How do I connect python-socketio with Django
I need to send notification to app(desktop-app) in real-time bases. I tried django-socketio but does not working with python3.6 then I go through the documentation of python-socketio i dont understand how do i integrate it with django.Please help me in this -
how to filter array based on another array in queryset
Here is my output: [ { "blog_value": [ { "requirement": [ { "name": { "profile": "Jr.Developers", } } ], "candidate": [ { "name": { "f_name":"asd" }, } ] } ], } ] I am trying to filter "profile": "Jr.Developers" but I am not able to filter in queryset -
Django AllAuth and Django Crispy Forms
I am trying to override the default django-allauth templates and use django-crispy-forms from improved rendering but having no luck getting the forms to actually submit, meaning I press submit and nothing happens. Here is my settings.py: INSTALLED_APPS = [ 'about.apps.AboutConfig', 'content.apps.ContentConfig', 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', ] ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # All Auth settings AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ) SITE_ID = 1 ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' Here is my custom template: {% extends "about/base.html" %} {% load crispy_forms_tags %} {% block content %} {% block navbar %}{% endblock %} <div class="site-section mb-5"> <div class="container"> <div class="form-register"> <form method="POST" class="signup" id="signup_form" action="{% url 'account_signup' %}"> {% csrf_token %} <legend>Signup</legend> <div class="form-group"> {{ form | crispy }} </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Sign Up"> </div> </form> </div> </div> </div> {% endblock %} I know the template is in the correct location and correctly … -
Requirement is installed but when I try to run the program it says it doesn't
Like the title says, I install crispy forms and it's installed, but when I try to migrate, it says crispy forms it's not installed (env) C:\Users\Dias\Desktop\Soccer_site\aposta_segura>pip3 install django-crispy-forms Requirement already satisfied: django-crispy-forms in c:\users\dias\desktop\soccer_site\aposta_segura\env\lib\site-packages (1.9.0) (env) C:\Users\Dias\Desktop\Soccer_site\aposta_segura>python3 manage.py migrate Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Dias\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\__init__.py", lin e 401, in execute_from_command_line utility.execute() File "C:\Users\Dias\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\__init__.py", lin e 377, in execute django.setup() File "C:\Users\Dias\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Dias\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\apps\registry.py", line 91, in po pulate app_config = AppConfig.create(entry) File "C:\Users\Dias\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\apps\config.py", line 90, in crea te module = import_module(entry) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.752.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'crispy_forms' (env) C:\Users\Dias\Desktop\Soccer_site\aposta_segura> If I install using the requirements.txt, the same thing happens, it says all the requirements are installed but crispy forms is not, i tried using "--user" but it doesn't work, don't know if it's a windows thing -
Send sms using twilio inside of a view
I have a django webapp which takes in entries of a phone number. I need to send an sms message to the newest entry of a phone number in the database, every time a new record is added, I want that number to receive a text message. How can I incorporate something like twilio into the insert_todo_item view here, so that every a new phone number is added, it gets a message? views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpRequest from django.core.exceptions import ValidationError from .models import Todo from .forms import Post # Create your views here. def list_todo_items(request): context = { 'todo_list' : Todo.objects.all(), 'count': Todo.objects.count() } return render(request, 'index.html', context) # use twilio to send message to the inputted number! # probably don't need to access the database at all :) # want to send to todo.objects.??? def insert_todo_item(request: HttpRequest): todo = Todo(content=request.POST['content']) try: todo.full_clean() except ValidationError: return redirect('/main/list/') todo.save() return redirect('/main/list/') def delete_todo_item(request,todo_id): todo_to_delete = Todo.objects.get(id=todo_id) todo_to_delete.delete() return redirect('/main/list/') models.py class Todo(models.Model): phone_regex = RegexValidator( regex= r'^\+?1?\d{9,15}$', message= ("Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."), code='invalid_regex', ) content = models.CharField(max_length=17, validators=[phone_regex], blank=False) -
when execute "from pyzbar import pyzbar" i got a WindowsError, Hope someone more knowledgeable can help. Thanks a lot
here's my code: from pyzbar import pyzbar I get the following error: Traceback (most recent call last): File "D:/Users/Administrator/Desktop/qrx-tool/test.py", line 1, in <module> from pyzbar import pyzbar File "D:\Python27\lib\site-packages\pyzbar\pyzbar.py", line 7, in <module> from .wrapper import ( File "D:\Python27\lib\site-packages\pyzbar\wrapper.py", line 143, in <module> c_uint_p, # minor File "D:\Python27\lib\site-packages\pyzbar\wrapper.py", line 136, in zbar_function return prototype((fname, load_libzbar())) File "D:\Python27\lib\site-packages\pyzbar\wrapper.py", line 115, in load_libzbar libzbar, dependencies = zbar_library.load() File "D:\Python27\lib\site-packages\pyzbar\zbar_library.py", line 60, in load dependencies, libzbar = load_objects(Path(__file__).parent) File "D:\Python27\lib\site-packages\pyzbar\zbar_library.py", line 54, in load_objects libzbar = cdll.LoadLibrary(str(directory.joinpath(fname))) File "D:\Python27\lib\ctypes\__init__.py", line 443, in LoadLibrary return self._dlltype(name) File "D:\Python27\lib\ctypes\__init__.py", line 365, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 193] %1 不是有效的 Win32 -
how can I get data from a table that is liked to a table that is liked to another one it self?
I have three tables,result, course and study, they are like follows class Study(models.Model): id_study = models.IntegerField(primary_key=True) study_name = models.CharField(max_length=45) description = models.CharField(max_length=45, blank=True, null=True) language = models.CharField(max_length=45) number_of_years = models.CharField(max_length=45) class Course(models.Model): id_course = models.AutoField(primary_key=True) course_name = models.CharField(max_length=45, blank=True, null=True) description = models.CharField(max_length=45, blank=True, null=True) credits = models.CharField(max_length=45, blank=True, null=True) teacher_id_teacher = models.ForeignKey('Teacher', models.DO_NOTHING, db_column='teacher_id_teacher') study_id_study = models.ForeignKey('Study', models.DO_NOTHING, db_column='study_id_study') class Result(models.Model): id_result = models.AutoField(primary_key=True) grade = models.IntegerField(blank=True, null=True) exam_id_exam = models.ForeignKey(Exam, models.DO_NOTHING, db_column='exam_id_exam') date = models.DateField(blank=True, null=True) student_id_student = models.ForeignKey('Student', models.DO_NOTHING, db_column='student_id_student') passed = models.CharField(max_length=45, blank=True, null=True) I want to get a result object depending on the study_id I give Result depends on Course, and course depends on Study Thanks in advance -
Django Rest Framework custom serializer's ValidationError not working
I am trying to set up a custom login serializer in Django and want a custom response but the default one always show: { "username":[ "This field is required." ], "password":[ "This field is required." ] } I tried to set up my serializer like so: class MyLoginSerializer(serializers.Serializer): username = serializers.CharField(required=True, allow_blank=True) email = serializers.EmailField(required=False, allow_blank=True) password = serializers.CharField(style={'input_type': 'password'}) def authenticate(self, **kwargs): return authenticate(self.context['request'], **kwargs) def _validate_email(self, email, password): user = None if email and password: user = self.authenticate(email=email, password=password) else: msg = _('Must include "email" and "password".') raise serializers.ValidationError(msg) return user def _validate_username(self, username, password): print("in username") user = None if username and password: print("in username 2") try: user = self.authenticate(username=username, password=password) except Exception: raise serializers.ValidationError("Wrong") else: print("in username 3") msg = _('Must include "username" and "password".') raise serializers.ValidationError(msg) return user def _validate_username_email(self, username, email, password): user = None if email and password: user = self.authenticate(email=email, password=password) elif username and password: user = self.authenticate(username=username, password=password) else: msg = _( 'Must include either "username" or "email" and "password".' ) raise serializers.ValidationError(msg) return user def validate(self, attrs): username = attrs.get('username') email = attrs.get('email') password = attrs.get('password') user = None if 'allauth' in settings.INSTALLED_APPS: from allauth.account import app_settings # Authentication through … -
Django ORM Query Multiple Models Reverse Relationship
I have the main model and five sub-models out of five four models have foreignkey relationship and one model has a one-to-one relationship to the main model. I am trying to execute a query on the main model and fetch related records from the sub-model sorted by 'id' and select the first record. I tried multiple ways to achieve this but still, the total operation takes around 20secs to fetch around 6000 records. I would really appreciate any help to efficiently fetch data from these models. Model M: id name status Model SA: m = Foreignkey(M) sa1 Model SB: m = Foreignkey(M) sb1 Model SC: m = Foreignkey(M) sc1 Model SD: m = Foreignkey(M) sd1 Model SE: m = OneToOne(M) se1 I tired select_related, prefetch_related, but still not able to reduce the turn-around-time. After trying different ways, currently, I am using the below, but from that, I get the only records which has data in the sub-models. But I would need to fetch all records from the main model irrespective of data in the sub-models. data = M.objects.exclude( SA=None, SB=None, SC=None, SD=None, SE=None, ) I am looking for output like: {'id': 1212, 'name':'asdasd', 'sa1':'asdasda, 'sb1':'asdasda, 'sc1':'asdasda, 'sd1':'asdasda, 'se1':'asdasda} -
Getting approval from Admin first before posting a blog in Django
I have made a blog as a project and I have set users to submit posts for the blog directly but i want to direct this post to the admin first for approval before showing on the website. here is the Post Create View Class. class PostCreateView(CreateView): model = Post fields = ['title', 'content'] template_name = "post_form.html" def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) Thank you in Advance -
Permanent Superuser Django Docker
So, I have a dockerfile that I run Django via CapRover to run the backend of my website. Amongst the components, I have an admin panel that I log into using a superuser that I've created by ssh-ing into the docker container. The problem is that whenever I change my backend by uploading it as a .tar via CapRover, I have to create my superuser again. My question is, is there any way to avoid this by creating some sort of persistance? Or is there any way of automating this via my dockerfile? Thanks! -
Django, get canvas data and using it in views.py
I'm new to web development. I research this question online but can not find a proper solution yet. I want to create a web site that allows the user to draw a number on a canvas and the website can predict the number after clicking the button. My idea is to get the canvas data by using getImageData and put the data into the views.py. Right now I can saw my ImageData in the console, but I don't know how to load the data to views.py where I will run python code for the classification. function hwdClick() { document.getElementById("hwdB").innerHTML = "YOU CLICKED ME!"; var canvas = document.getElementById("hwdcanvas"); var ctx = canvas.getContext("2d"); var canvasData = ctx.getImageData(0,0,350,350); console.log(canvasData); } Do I have to use database in this case? Please give me some hint on this problem. -
"Base classes have conflicting values for attribute" when using a Python mixin to overide a base class method
I have a django mixin: class PublicSchemaOnlyAdminAccessMixin: def has_view_or_change_permission(self, request, obj=None): return connection.schema_name == get_public_schema_name() def has_add_permission(self, request): return connection.schema_name == get_public_schema_name() def has_module_permission(self, request): return connection.schema_name == get_public_schema_name() That is used in many of my ModelAdmin classes, for example: class BlockAdmin(PublicSchemaOnlyAdminAccessMixin, admin.ModelAdmin): pass But I'm getting warning about this structure from LGTM: Base classes have conflicting values for attribute 'has_add_permission': Function has_add_permission and Function has_add_permission. However, none of their proposed solutions seem to be practical for this, since I am using this in about half of my Admin classes. Is there either A. A better way for me to resolve this bad code structure or B. Is this code structure fine (as long as I understand the classes are read from right to left and the mixin must go on the left for consistant behaviour) -
How to save a HTML Canvas content to Google Storage
I am trying to save an html canvas content to Google Storage. What I do is as following : Create a signed url for the image file. class ThumbnailUploadSignedURL(APIView): @method_decorator(login_required(login_url='/login/')) def post(self, request): filename = request.POST.get('filename') filetype = request.POST.get('type') filesize = request.POST.get('size', 0) path = '{0}-{1}/{2}/'.format(request.user, request.user.id, thumbnail.name) blob = default_storage.open(full_path, 'wb') signed_url = blob.blob.generate_signed_url(expiration=default_storage.expiration, method='PUT', content_type='image/png') return Response({"thumbnail_signed_url":signed_url}) Get the content of canvas and send it to Google Storage. var image = canvas.toDataURL("image/png"); const xhr = new XMLHttpRequest(); xhr.open("PUT", data.thumbnail_signed_url, true); xhr.setRequestHeader('Content-Type', 'image/png'); xhr.send(image); The file is successfully being created on Google Storage, however the content is stated as corrupt, it is indeed basically base64. I also tried ways to convert base64 to png, yet unsuccesfully, as it was suggested here php-js-canvas example. How can I achieve this with js and google storage ? -
Django - recycle form field variable twice
I have a page where the user can create a new team, the html page is divided as such: user inputs a team name (if they want to, the page can return an animation with JS) First form by clicking next, it brings to the 2nd part: where the user inputs the team key others can use to join the team Second form Once the user clicks submits, it needs to be submitted as one form (team name + team key) to process. My problem is that I wish to reuse the {{form.team_name}} value for the 2nd part that I will use for a team creation. The form.py values look like this: class TeamCreationForm(forms.Form): team_name= forms.CharField(max_length=100, widget= forms.TextInput (attrs={ 'placeholder': 'MY TEAM', 'id':'inputText'})) team_k = forms.CharField(max_length=100, widget= forms.TextInput (attrs={ 'placeholder': 'ENTER KEY', 'id':'inputText'})) my team creation page looks like this: [...] <button style="float:left;">Go Back</button> <div> <canvas id="text" width="500" height="100"></canvas> <canvas id="stage" width="500" height="100"></canvas> </div> <div> <div id="Div1"> <form id="form"> {{form.team_name}} <input type="submit" value="TRY IT"> </input> <button type="button" id="nextBtn" onclick="switchVisible();">Next</button> </form> </div> <div id="Div2"> <form id="form" method="POST" style="top:342px; left:340px;">{% csrf_token %} {{form.team_k}} <input type="submit" value="CREATE"> </input> <button type="button" id="nextBtn" onclick="switchVisible();">Previous</button> </form> </div> </div> [...] For it to work, I would need … -
Heroku app crashes after pushing change with new dependencies
So I have a Django web app running on Heroku. I recently pushed an update where I added some API functionality via the Django Rest Framework. I installed this via pip. Now my Heroku app crashes. I assume I somehow need to install this dependency on Heroku? Here is the error message: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail I tried entering the Heroku CLI and typing pip install djangorestframework but and running Heroku restart but it still crashes. -
Integrate twilio into webapp using postgres
I have a django app which stores phone numbers into a postgres database, I am looking to send sms to each of the numbers in the database as they are added via the webapp. I'm using pgadmin to monitor the database and it's all running on my localhost as of now, do I need to deploy it to get twilio working with the database? I can't seem to find any clear explanation as to how I can send the messages to the numbers stored as records in postgres, any help would be awesome! -
Issue with accessing Django Admin with the User table on the remote database and Django Native Admin related tables on the local databases
I'm trying to access the Django Admin using two databases. One is a local, while the other remote readonly legacy database has the User table. After logging in I get an error because the django_admin_log table is on the local database can't access the user table on the remote database. I'm using Django version 3.0.5. How could I fix this issue?