Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass a string with slashes from view to template?
Why does the below code gives me SyntaxError: unexpected token: ':' in the browser's console whenever test view is called? Is it because the JavaScripts sees the text after slashes in the URL as commented lines? How do I fix that? The view: def test(request): context = { 'url': 'https://www.google.com', } return render(request, 'explorer/test.html', context) The template test.html: <script> var url = {{ url }} console.log(url) </script> -
Getting seconds from a timer function to my view
I want to get the minutes and seconds from the timer in my template to my view. I already tried different approaches with an ajax.post request but it didnt really work how I wanted it to be. Here is my template: {% block content %} <!-- Timer function --> <script type="text/javascript"> var sec = 0; function pad ( val ) { return val > 9 ? val : "0" + val; } setInterval( function(){ $("#seconds").html(pad(++sec%60)); $("#minutes").html(pad(parseInt(sec/60,10))); }, 1000); </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span id="minutes"></span>:<span id="seconds"></span> <form action="results" id=results method="POST"> <!-- after clicking on this button the minutes and seconds should also be sent as a POST request --> <div class="command"> <button type="submit" name="ctest_submit">Submit solution</button> </div> </form> {% endblock %} Now I want to get the minutes and seconds to my view as a POST request after clicking on the submit button. My idea was it to hide the time in a input like this: <input type="hidden" name="seconds" value="what should be in here???"> but I dont know what should be in value? -
Django inline has no ForeignKey
I have on error now. It's inline error, I trying to find the solution, and I'd tried for all day long but failed. I'm sorry about if this question is very easy and repeated. This is error, when I try to use inline it shows <class 'brick.admin.AdminRoomStateInline'>: (admin.E202) 'brick.RoomInfomation' has no ForeignKey to 'brick.RoomInfomation' models.py class RoomInfomation(models.Model): roomNum = models.PositiveSmallIntegerField(default=0, primary_key=True) roomFloor = models.PositiveSmallIntegerField(default=0) startPointX = models.PositiveSmallIntegerField(default=0) startPointY = models.PositiveSmallIntegerField(default=0) #referencing userInfo_RoomReservationFK = models.ForeignKey('UserInfo', null=True, blank=True) compInfo_RoomInfoFK = models.ForeignKey('CompanyInfomations', on_delete=models.CASCADE) companyRoomTypeInfo_RoomInfoFK = models.ForeignKey('CompanyRoomTypeInfomations', on_delete=models.CASCADE) def __unicode__(self): return '%s' % str(self.PositiveSmallIntegerField) class RoomState(models.Model): roomReservation_roomStateFK = models.ForeignKey('RoomInfomation') reservationBlock = models.BooleanField(default=False) reservated = models.BooleanField(default=False) reservatedDate = models.DateField(blank=True, null=True) reservationFirstDate = models.DateField(blank=True, null=True) reservationEndDate = models.DateField(blank=True, null=True) checkoutTime = models.DateField(blank=True, null=True) checkinTime = models.DateField(blank=True, null=True) admin.py class AdminRoomStateInline(admin.TabularInline): model = RoomInfomation extra = 8 # list_display = [ # 'roomReservation_roomStateFK', # 'reservationBlock', # 'reservated', # 'reservatedDate',#예약을 진행했던 날짜 # 'reservationFirstDate', # 'reservationEndDate', # 'checkoutTime', # 'checkinTime', # ] # inlines = [AdminRoomInfomationInline,] class AdminRoomInfomation(admin.ModelAdmin): fields = [ 'compInfo_RoomInfoFK', 'companyRoomTypeInfo_RoomInfoFK', 'userInfo_RoomReservationFK', 'startPointX', 'startPointY', 'roomNum', 'roomFloor' ] inlines = [AdminRoomStateInline,] #class RoomState(admin,ModelAdmin): #admin.site.register(RoomInfomation) #admin.site.register(RoomState, AdminRoomState) admin.site.register(UserInfo, AdminUserInfo) admin.site.register(RoomInfomation, AdminRoomInfomation) admin.site.register(RoomState) I double check that may not tried, for example, when I'd changed inline class AdminRoomState to … -
Reserved namespace issue with Django HttpResponseRedirect when calling from a defined view
Whenever I have set a redirect to another defined view, I am getting a namespace error. I have an app_name defined in urls.py, but I'm pretty sure that I am missing something obvious. Error: enter code here`Traceback (most recent call last): File "/root/areports/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/root/areports/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/root/areports/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/root/areports/reports/views.py", line 15, in entry_create_view return HttpResponseRedirect(reverse('reports:new_district_view')) File "/root/areports/venv/lib/python3.6/site-packages/django/urls/base.py", line 86, in reverse raise NoReverseMatch("%s is not a registered namespace" % key) django.urls.exceptions.NoReverseMatch: 'reports' is not a registered namespace views.py from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import New_Event_Form, New_District_Form def entry_create_view(request): form = New_Event_Form(request.POST or None) if form.is_valid(): form.save() #form = New_Event_Form() context = { "form": form } return HttpResponseRedirect(reverse('reports:new_district_view')) else: print('Invalid') context = { 'form': form, } return render(request, "entry_create.html", context) def new_district_view(request): new_district = New_District_Form(request.POST) if new_district.is_valid(): new_district.save() new_district = New_District_Form() context = { "new_district": new_district } return render(request, "new_district.html", context) else: print('Invalid') context = { "new_district": new_district } return render(request, "new_district.html", context) def home_view(request): return render(request, "home.html", {}) urls.py from django.contrib import admin from django.urls import path … -
Django: Authentication credentials were not provided
I've pulled up a dozen similar SO posts on this topic, and have implemented their solutions to the best that I have understood them, yet they haven't worked for me. Why am I getting this error detail: "Authentication credentials were not provided." after using an AJAX Patch request to hit my Django Rest Framework endpoint? I appreciate your help! Some Details The header tells me "Status Code: 401 Unauthorized" I'm on my localHost development server (Postgres) I don't get this error with any other django forms or ajax (Get and Posts) requests running on other apps within this application. This is the first time I'm attempting a PATCH request Ultimately, Once this Ajax Patch request works I, simply want to add bookid to the ManyToManyField books field in the api.BookGroup model I've tried to follow the suggestions in similar posts which recommend adjusting the settings.py to allow the right authentication and permission methods. referring to the DRF documentation, I've also changed the permission classes to permission_classes = (IsAuthenticated,) which should allow a patch request if I'm logged in when making the request (and yes, I am definitely logged in) The form data in the ajax header shows that I am … -
Issue linking Jquery library to Django extended template
I am making a web app using Django (v2.1.4). In one of my models I have a "date" field to which I would like to add the "date picker" calander using jquery. I am having trouble properly linking the jQuery code to Django. Here are the relevant pieces of code (let me know if you need more) models.py class Detail(models.Model): study = models.ForeignKey(Study, on_delete=models.CASCADE, related_name='details') Location = models.CharField('Detail', max_length=255) date = models.DateField('event date', default=datetime.date.today) time = models.TimeField('event start time', default=now) compensation = models.DecimalField(max_digits=6, decimal_places=2, default=0) description = models.TextField(blank=True) def __str__(self): return self.text forms.py class DetailForm(forms.ModelForm): class Meta: model = Detail fields = ('Location', 'date', 'time', 'compensation', 'description', ) widgets = { 'date': forms.DateInput(attrs={'class': 'datepicker'}) } views.py @login_required @educator_required def detail_add(request, pk): study = get_object_or_404(Study, pk=pk, owner=request.user) if request.method == 'POST': form = DetailForm(request.POST) if form.is_valid(): detail = form.save(commit=False) detail.study = study detail.save() messages.success(request, 'You may now add answers/options to the question.') return redirect('educators:detail_change', study.pk, detail.pk) else: form = DetailForm() return render(request, 'classroom/educators/detail_add_form.html', {'study': study, 'form': form}) template base.html {% load static %}<!doctype html> <html lang="en"> <head> ... <link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css”> <link rel=”stylesheet” href=”/resources/demos/style.css”> <script src=”https://code.jquery.com/jquery-1.12.4.js”></script> <script src=”https://code.jquery.com/ui/1.12.1/jquery-ui.js”> </script> </head> ... {% block scripts %} {% endblock %} {% block scripts … -
Saving data on Django from a Vue Template
I managed to get vue to work inside a Django template and I wondering what would be the best way to save a variable with the result of the calculation (this is a simple web calculator made in view) in this.result.toString() to a database using Django. I Would like to save the results and the current date/time. Thank you! new Vue({ el: '#app', data: { // calculation:'15*98', // tempResult:'1470', calculation:'', tempResult:'', }, mounted() { let btns = document.querySelectorAll('.btn') for (btn of btns) { btn.addEventListener('click',function() { this.classList.add('animate') this.classList.add('resetappearanim') }) btn.addEventListener('animationend',function() { this.classList.remove('animate') }) } }, methods: { append(value) { this.calculation += value.toString() }, clear() { this.calculation = '' this.tempResult = '' }, getResult() { if(this.tempResult != ''){ this.calculation = this.tempResult //this.tempResult = '' } }, backspace() { this.calculation = this.calculation.slice(0,-1) } }, watch: { calculation() { if(this.calculation !== '' && !isNaN(this.calculation.slice(-1)) && this.calculation != this.result ){ this.tempResult = this.result.toString() } } }, computed: { result() { if(!isNaN(this.calculation.slice(-1))) return eval(this.calculation) else return eval(this.calculation.slice(0, -1)) }, fontSize() { // save result here ?? return this.fontSize = 50-(this.tempResult.length*1.25) } }, filters: { hugeNumber: (value) => { let parts = value.toString().split("."); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " "); return parts.join("."); }, number: (value) => { return value.replaceAll('*','x') … -
geodjango - fit bounds of leaflet map for a single point
I've been trying to set a leaflet map center with a point coordinates passed as the context.geom variable in the template, I previously tried with the leaflet-django library, but I couldnt find a way to reset the settings configuration to recognize the .geom value I set up map with leaflet from scratch, no library, so far I got this views.py: def buscar_rol(request): if request.method == 'POST': srch = request.POST['srh'] if srch: match = D_Base_Roles.objects.filter(Q(rol__iexact=srch) | Q(dir__icontains=srch)) pto = match[0] js in Template: var map = L.map('pto_gis').setView([-23.64, -70.387],17); L.tileLayer('http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',{ maxZoom: 20, subdomains:['mt0','mt1','mt2','mt3'] }).addTo(map); var pto_ubi = {{ pto.geom|geojsonfeature|safe }} var mrk = L.geoJson(pto_ubi).addTo(map); var loc_pto = pto_ubi.geometry.coordinates; mrkbounds = L.latLngBounds(loc_pto); but in the console it mrkbounds has only two points, and of the same coordinates, I tried also to pass the pto_ubi and loc_pro variables before setting the map to pass loc_pto as coordinate for the setView, : var pto_ubi = {{ pto.geom|geojsonfeature|safe }} var loc_pto = pto_ubi.geometry.coordinates; var map = L.map('pto_gis').setView(loc_pto,17); but i got a "TypeError: t is null" error is there a way to set up django-leaflet to override the zoom and center settings based on a context values from a search function?, or how could I make this … -
Django MPTT: Rebuild tree in migrations file
I already have a model in my project that I now want to use with django-mptt. This model already has some data in it. During migrations, you are asked to set default values for some of the fields django-mptt creates. As directed in the documentation, I set 0 as the one off default value. The documentation goes ahead and recommends running Model.objects.rebuild() after this is done to set the correct values in the fields. I would like to perform this operation via my migrations files. I do NOT want to run this via my django-shell as this is not a one off operation. My migration files is so: # -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-12-27 17:33 from __future__ import unicode_literals from django.db import migrations, models def migrate_mptt(apps, schema_editor): ProductCategory = apps.get_model("product", "ProductCategory") ProductCategory.objects.rebuild() class Migration(migrations.Migration): dependencies = [ ('product', '0016_auto_20181227_2303'), ] operations = [ migrations.RunPython(migrate_mptt), ] On migration, I receive the error AttributeError: 'Manager' object has no attribute 'rebuild'. The same command works perfectly in the shell, of course. I need to do this via migrations since I want this operation to be run automatically every time my project is deployed. -
get_or_create object created or found?
I want to use get_or_create in some view and I want to know if it is made or found? One of the lines looks like this: source,p = Source.objects.get_or_create(name="Website") -
collectstatic refers to wrong directory
I got a problem that I can't seem to to find the root cause for. When I run the 'collectstatic' command I get error file not found. I can see it tries to put files in wrong directory. First after running the command I get this question You have requested to collect static files at the destination location as specified in your settings: /var/www/projects/foobar/foobar/static Which is right. But I get this error: FileNotFoundError: [Errno 2] No such file or directory: '/var/www/projects/foobar/foobar/foobar/static' Thats one dir of 'foobar' to much. This is my settings for the production: STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_ROOT = '/var/www/projects/foobar/foobar/media' MEDIA_URL = '/media/' STATIC_ROOT = '/var/www/projects/foobar/foobar/static' STATIC_URL = '/static/' How come it adds an extra dir of 'foobar'? -
Using attribute values as choices in Django model
I want the user to be able to add values to an attribute 'county' in model CountyChoices. I then want those values to surface as choices in a form for address for the attribute 'county' in model Address. I couldn't think of another way to explain this and so I had a hard time finding this in the documentation. What would this be called in the Django docs so that I can look this up? A link would be even better - Thanks in advanced. -
Django - PUT request in RetrieveUpdateDestroyAPIView
I am trying to make a PUT request to and RetrieveUpdateDestroyAPIView to my Student model. Model class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) college = models.CharField(max_length=100) branch = models.CharField(max_length=10) section = models.CharField(max_length=10) optedCourses = models.ManyToManyField(Course, blank=True, related_name='students') registrations = models.ManyToManyField(Course, blank=True, related_name='studentRequests') Serializer class StudentSignupSerializer(ModelSerializer): user = UserSignupSerializer() class Meta: model = Student fields = '__all__' def create(self, validated_data): user = User.objects.create(**validated_data.pop('user'), is_student=True) validated_data.pop('optedCourses') validated_data.pop('registrations') return Student.objects.create(user=user, **validated_data) VIEW class DetailStudent(RetrieveUpdateDestroyAPIView): queryset = Student.objects.all() lookup_field = 'id' lookup_url_kwarg = 's_id' def get_serializer_class(self): if self.request.method == 'GET': return StudentSerializer else: return StudentSignupSerializer I am trying to add more elements to the ManyToManyFields (optedCourses, registrations) by making PUT requests, but I am getting an error. { "user": { "username": [ "A user with that username already exists." ] } } Shouldn't PUT request update the existing elements? How do I approach on solving this problem? -
How to know the url path from a view function of another url in django?
I have a set of URLs: /home/ /register/ /login/ /puzzle/<pk> All of the first 3 urls can make a request to the last url. Is it possible to know which urls are calling the /puzzle/<pk>, from the view function attached to it? -
Django queryset iterator() doesn't work as expected
I have tested queryset.iterator() based on Django document. Oracle and PostgreSQL use server-side cursors to stream results from the database without loading the entire result set into memory. With server-side cursors, the chunk_size parameter specifies the number of results to cache at the database driver level. Fetching bigger chunks diminishes the number of round trips between the database driver and the database, at the expense of memory. On PostgreSQL, server-side cursors will only be used when the DISABLE_SERVER_SIDE_CURSORS setting is False. print(settings.DATABASES['default']['ENGINE']) # postgresql class TestModel(Model): age = IntegerField(default=1) # Insert 10 rows for i in range(10): TestModel().save() settings.DEBUG = True l = logging.getLogger('django.db.backends') l.setLevel(logging.DEBUG) l.addHandler(logging.StreamHandler()) # From now, every queries emitted by Django will be printed. print(settings.DISABLE_SERVER_SIDE_CURSORS) # False for i in TestModel.objects.all().iterator(chunk_size=2): print(i.age) (0.001) DECLARE "_django_curs_4369655232_3" NO SCROLL CURSOR WITH HOLD FOR SELECT "testmodel"."age" FROM "testmodel"; args=() I expected the above code will hit database 5 times for every 2 rows because of chunk_size=2(and the total number of rows are 10). However, it seems to emit just one query(above printed query). Do I misunderstand on queryset.iterator()? -
Trying to web scrape with Python from Heroku gives 'Connection aborted' error
I have a Django API application that web scrapes a website with the pythonic library RoboBrowser, which allows for easy log in and scraping from the page you get redirected to. The code that scrapes sits in the views.py file and the data is showed in an API view, using the Django REST framework. My application worked on my local network, but when I put the project up on heroku and tried to view the API view with the JSON data I got this error. 'Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)) This is the traceback: Environment: Request Method: GET Request URL: https://restschool.herokuapp.com/results/ Django Version: 2.1.4 Python Version: 3.6.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'webapp'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', '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') Traceback: File "/app/.heroku/python/lib/python3.6/site-packages/urllib3/connectionpool.py" in _make_request 377. httplib_response = conn.getresponse(buffering=True) During handling of the above exception (getresponse() got an unexpected keyword argument 'buffering'), another exception occurred: File "/app/.heroku/python/lib/python3.6/site-packages/urllib3/connectionpool.py" in urlopen 600. chunked=chunked) File "/app/.heroku/python/lib/python3.6/site-packages/urllib3/connectionpool.py" in _make_request 384. six.raise_from(e, None) File "<string>" in raise_from File "/app/.heroku/python/lib/python3.6/site-packages/urllib3/connectionpool.py" in _make_request 380. httplib_response = conn.getresponse() File "/app/.heroku/python/lib/python3.6/http/client.py" in getresponse 1331. response.begin() File "/app/.heroku/python/lib/python3.6/http/client.py" in begin 297. version, status, reason = self._read_status() File "/app/.heroku/python/lib/python3.6/http/client.py" in _read_status … -
Django returns Page Not Found for mapped URL
I'm trying to render a basic html/css page in Django and I can't get it to work. It's set up seemingly the same as my index page which does work correctly and the debug explanation from the 404 response seems to show that it's pointing to the right url. Any thoughts on why this isn't working? *I'm using django 2.1 so I'm using path instead of the old regex url mapping *The html file exists and is located in templates\base_app\our-story.html From views.py: def OurStory(request): return render(request, 'base_app/our-story.html') From urls.py: from base_app import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('our-story', views.OurStory, name='our-story') ] From settings.py: TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') INSTALLED_APPS = [ (standard django apps) 'base_app' ] From debug message: Request Method: GET Request URL: http://127.0.0.1:8000/our-story.html Using the URLconf defined in base_app.urls, Django tried these URL patterns, in this order: admin/ [name='index'] our-story [name='our-story'] The current path, our-story.html, didn't match any of these. -
SelectDateWidget choices
I would manually like to set the date choices in my form according to my DB data. Here is a code snippet of the code I am using DATA_YEARS = ('2017', '2018') DATA_MONTHS = ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12') class DateForm(forms.Form): year = forms.DateField(widget=forms.SelectDateWidget(years=DATA_YEARS)) month = forms.DateField(widget=forms.SelectDateWidget(months=DATA_MONTHS)) However, I reckon SelectDateWidget does not expect to receive these arguments. If not, how can I implement this properly? -
Refactor Django FormView Context
I currently email myself submitted form information as an admin so I can contact a customer. I could not figure out how to simply pass all of the form variables to the Django Email Template. I instead had to define the individually. Is there a way to pass all of the context variables so I don't have define each and every one of them? form_class = CustomProjectBuildRequestForm success_url = reverse_lazy('home') success_message = "Form successfully submitted!" def form_valid(self, form): form.save() context = { 'first_name': form.cleaned_data.get('first_name'), 'last_name': form.cleaned_data.get('last_name'), 'email': form.cleaned_data.get('email'), 'phone': form.cleaned_data.get('phone_number'), 'zip_code': form.cleaned_data.get('zip_code'), 'project_title': form.cleaned_data.get('project_name'), 'project_description': form.cleaned_data.get('project_description'), 'contact_method': form.cleaned_data.get('preferred_contact_method'), } template = get_template('request-custom-project/email_template.html') content = template.render(context) send_mail( 'New Custom Project Request', html_message=content, message=content, from_email=context['email'], recipient_list=['test@gmail.com'], fail_silently=False, ) return super(PMPIndex, self).form_valid(form) -
How to save data of the updated table to another table in Django
I just started in Django, I'm developing a web-application that want to create a Purchase Order and Masterlist. I started using the generic views and now I can create and update a Purchase Order. It has a status field of Pending and Received. If I created a new Purchase Order the default status is Pending and If I updated it to Received it should also save the data to Masterlist table. The thing is, it doesn't work. By the way, the received item should stay in Purchase Order table for history. Since I'm using the generic views in Django.. I tried to put the masterlist table in the update view of the purchaseorder but It has error saying No masterlist found matching the query Here is my class for the UpdateView class PurchaseOrderUpdateView(LoginRequiredMixin, UpdateView): model = PurchaseOrder model = Masterlist fields = ['item_no', 'description', 'dimension', 'unit', 'quantity', 'cost', 'project_site', 'po_date', 'supplier', 'status'] def form_valid(self, form): form.instance.prepared_by = self.request.user return super().form_valid(form) What I expect is, when I update the status field of my Purchase Order to received, it should also saved the data of it to Masterlist. Or If the item in Purchase Order exists in Masterlist it will update the … -
How to create model objects that belong to unique user
I am setting up a delivery app .I want to be able to create a Reciever that belongs to the user logged in when created. class CustomUser(AbstractUser): first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) email = models.EmailField(blank=False) class Reciever (models.Model): name = models.CharField(max_length=256,blank=False) I want to create a Reciever object that belongs to a particular user. When i create a Reciever now , it is available to all users. -
How do I stay on the same tab in a webpage after submitting a form using Django?
When I refresh the page/submit a form for my django app, it always goes to the first tab instead of redirecting to the tab the user was currently on. Is there any simple fix for this because I haven't found any answers online -
UnboundLocalError at / local variable 'Profile' referenced before assignment
i am writing a django views as shown:- def feed(request): if request.user.is_authenticated: user=request.user profile=Profile.objects.filter(user=user) userfollowing=FollowingProfiles.objects.filter(Profile=profile) for following in userfollowing: username=following.ProfileName useraccount=User.objects.filter(username=username) Profile=Profile.objects.filter(user=useraccount) Post=post.objects.filter(Profile=Profile) comment=comment.objects.filter(post=Post) final_post_queryset=final_post_queryset+Post final_comment_queryset=final_comment_queryset+comment return render(request,'feed/feed.html',{'final_comment_queryset':final_comment_queryset,'final_post_queryset':final_post_queryset}) else: redirect('signup') while template feed.html is:- {% extends 'base.html' %} {% block content %} {% load static %} {% for p in final_post_queryset %} {{ p.DatePosted }} <img src="{{ p.Picture.url }}"/> {% endblock %} while the error is:- so the error is in the 3rd line of view profile=Profile.objects.filter(user=user) -
Method GoogleOAuth2 uses to login user
I have GoogleOAuth2 login in my application (social_core.backends.google.GoogleOAuth2). I want to write a custom class that inherits GoogleOAuth2 class. I want it to check Users.is_active is True or False and sent custom error message if Users.ia_active=False. What method does GoogleOAuth2 use to login a user? -
Django User with is_active=False login via GoogleOAuth2
I have a Django app with login via GoogleOAuth2. In general, GoogleOAuth2 works fine. When I try to login as a user with User.is_active=True, it's all OK. But when I try to login as a user with User.is_active=False, I got nothing. No error, just login page again. What can be an issue? How I should handle this error?