Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, sum of values in form, then submit to database
Say for example I have this. Take the input fields, and add via the calculate button. I tried using django-mathfilters inside of my html file, but then I realized that the fields would always be empty beforehand, so nothing would ever be calculated. What is the right approach to this? Do I need to split Final_Result from my book table? Book Price: $10 (input field) Delivery charge: $3 (input field) Delivery type: $5 (input field) Final Result: (result of adding the fields above when user clicks the calculate button [calculate] [submit] submit button will finalize the results and sent the values to the database. This is my model for the table class book(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) book_price = models.IntegerField() delivery_charge = models.IntegerField() delivery_type = models.IntegerField() final_result = models.IntegerField() views.py for the form def final_price(request): if request.method == 'POST': form = RequestForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect('final_price') else: form = RequestForm() args = {'form': form} return render(request, 'final_price.html', args) Model for to allow me to edit the fields in my book module class RequestForm(forms.ModelForm): class Meta: model = book fields = ( 'book_price', 'delivery_charge', 'delivery_type', ) I tried adding them through the … -
TypeError: title() missing 1 required positional argument: 'request'
Traceback (most recent call last): File "C:\Users\danfi\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\danfi\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\danfi\AppData\Local\Programs\Python\Python38-32\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 975, in _find_and_load_unlocked File "", line 671, in _load_unlocked File "", line 783, in exec_module File "", line 219, in _call_with_frames_removed File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\WILLIAMSWEBSITE\TJWEXOTICS\urls.py", line 21, in path('', include('TJW.urls')) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\urls\conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "C:\Users\danfi\AppData\Local\Programs\Python\Python38-32\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) … -
I want to serve static files with permissions logic in my django project
So I've been working on a django project. Its a marketplace platform (two kinds of users - buyer & seller) and when a seller uploads files for a buyer, only those two users should have access to the uploaded files. I'm trying to figure how static files can be served with these permissions. I'm not sure if this is relevant but I'm using nginx to serve the static files, so is there a way to add permissions logic in django to serve these static files? -
Python(Django), PHP, Ruby frameworks: How do they handle browser side scripting?
I am quite familiar with javascript frameworks like Angular, React & Vue. Since browsers understand and knows how to run javascript, these frameworks are used for end-to-end web application development. But when we think of non-javascript frameworks like Python(Django/Flask), PHP, Ruby on Rails etc. few questions come to my mind: Do these framework supports only server side scripting in their respective languages (i.e. Python, PHP, Ruby)? When these frameworks send webpage/response to browser and lets say for example the page is having submission form which needs validations, which scripting do they use on browser side? Because browsers don't support Python, PHP, Ruby languages. OR Django/Flask, PHP, RoR programmers also need to know javascript and they got to embed it in pages/responses they send? -
Profile model Data is not saving when I try to create user and Profile simultaneously
When I try to create a new user, I also want to create their profile at the same time. But there is no data coming from the Profile form. User is created but in Profile creation form I am getting an error. Here is my models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) StudentID = models.IntegerField(primary_key=True, verbose_name='SID') image = models.ImageField(default='default.jpeg', upload_to='profile_pics', blank=True) def __str__(self): return self.Branch def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() class Meta: model = User fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2'] class ProfileCreationForm(forms.ModelForm): class Meta: model = Profile fields = ['StudentID', 'Branch', 'YearOfStudy', 'ContactNumber'] views.py when I try to print StudentID, I get None value. I think there is data loss. def register(request): print("hello") if request.method == 'POST': form = UserRegisterForm(request.POST) form1 = ProfileCreationForm(request.POST) if form.is_valid() and form1.is_valid(): user = form.cleaned_data.get('username') StudentID = form.cleaned_data.get('StudentID') print(StudentID) profile = form1.save(commit=False) profile.user = user form.save() profile.save() messages.success(request, f'Your account has been created! You are now able to log in') print("reached here") return redirect('login') else: form = UserRegisterForm() form1 = ProfileCreationForm() … -
How to export data into csv file from multiple django models?
from django.db import models Models.py class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) class Album(models.Model): artist = models.ForeignKey(Musician, on_delete=models.CASCADE) name = models.CharField(max_length=100) release_date = models.DateField() num_stars = models.IntegerField() class Runner(models.Model): MedalType = models.TextChoices('MedalType', 'GOLD SILVER BRONZE') name = models.CharField(max_length=60) medal = models.CharField(blank=True, choices=MedalType.choices, max_length=10) artist1 = models.ForeignKey(Album, on_delete=models.CASCADE) I want to export the data from multiple models to single csv files.Is there any way to do that ? I'm trying to applay the export features for user not on admin side. -
How to add Auto increment Field, Which isn't a Primary Key in Django Models
I want to add a field id in my Django Model. The primary key is the email id. I want the id field to be AUTO_INCERMENT. we can use models following AutoField(primary_key=True) but this makes id the primary key to the id, which isn't the desired case. it returns the following error. django.db.utils.Error: Incorrect table definition; there can be only one auto column and it must be defined as a key [SQLCode: 1075], [SQLState: 42000] below code for model class USER(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) email = models.EmailField(primary_key=True) when I am making primary_key=False it will return same error django.db.utils.Error: Incorrect table definition; there can be only one auto column and it must be defined as a key [SQLCode: 1075], [SQLState: 42000] -
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!