Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error while extending on 500 error django custom view
I'm triying to define a custom 500 error for my django app by just placing my 500.html file in the templates folder. {% extends "base.html" %} {% load static %} {% block body %} <div class="container"> <div class="row"> UPS, algo fue mal. </div> </div> {% endblock %} Whitout the first line( extending the skeleton of the web) it works, but with it i got this meesage: A server error occurred. Please contact the administrator. I'm dooing the exact same thing for the 404 errors, and I works perfectly. I'm completly lost here. -
SQL Query to Django Query
I'm trying to figure out how can I convert below SQL query into Django query select main_project.name, (main_contacts.first_name) as Name, group_concat(main_property.property_id) as Properties, sum(main_property.area), (main_contacts.first_name||main_project.name) as CONPROP from main_project INNER join main_property on main_property.project_id = main_project.id INNER join main_property_owner ON main_property_owner.property_id = main_property.id INNER JOIN main_contacts ON main_contacts.id = main_property_owner.contacts_id group by CONPROP models.py class Contacts(models.Model): first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=15, null=True, blank=True) mobile = models.CharField(max_length=10, unique=True) email = models.EmailField(unique=True, null=True, blank=True) def __str__(self): return f'{self.first_name} - {self.mobile}' class Project(models.Model): name = models.CharField(max_length=100) address = models.ForeignKey(Address, on_delete=models.CASCADE) def __str__(self): return self.name class Property(models.Model): added_on = models.DateTimeField(auto_now_add=True) creator = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='creator', limit_choices_to={'is_staff': True}) property_id = models.CharField(max_length=10, unique=True) project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='properties') owner = models.ManyToManyField(Contacts, blank=True) area = models.DecimalField(max_digits=20, decimal_places=2) internal = models.TextField(null=True, blank=True) external = models.TextField(null=True, blank=True) def __str__(self): return self.property_id I've learned that it will be done using 'annotate' but somehow I'm unable to do it. -
Django / Ubuntu 20 - How change to a previous version of GDAL
first of all, thanks for your help. I'm new to django, and I'm developing a site where you have to enter coordinates in some forms and then they should be editable. So far, so good, I haven't had any problem creating that, however, as I read, in some of the more recent versions, the order in which GDAL reads the coordinates was changed, so the positions appear inverted when reading data from geospatial databases. In other words, the coordinates are entered right (from PgAdmin they look right) but are read wrong when you load them into a leaflet map with Django. I asked about how to correct this (Link to my previous question) but got no answer and haven't been able to solve it myself. Therefore, the only thing I can think of is to try with previous versions of GDAL, however, I'm not quite sure how to do it. I followed the next steps to install it: pip3 install gdal sudo apt-get install gdal-bin libgdal-dev sudo apt-get install python3-gdal Thanks in advance -
Unable to import modules from aws lambda layer
I have a requirements file for my pip packages. I installed it in a target folder and zipped the contents and uploaded it on AWS lambda layer. Requirements.txt asgiref==3.2.3 certifi==2019.11.28 chardet==3.0.4 cloudevents==0.2.4 decorator==4.4.1 Django==3.0 idna==2.8 jaeger-client==4.2.0 jsonpath-ng==1.4.3 pbr==5.4.4 ply==3.11 pytz==2019.3 requests==2.22.0 six==1.13.0 sqlparse==0.3.0 urllib3==1.25.7 aws-xray-sdk mysql-connector-python gunicorn After this I made a dummy lambda function to check if the layer is working or not. import json import django def lambda_handler(event, context): # TODO implement return { 'statusCode': 200, 'body': json.dumps('Hello from Lambda!') } I get the error: Unable to import module 'lambda_function': No module named 'django' -
Django manager annotate first element of m2m as fk
Let's say I have these models. class AdventureWaypoint(models.Model): adventure = models.ForeignKey("Adventure", on_delete=models.CASCADE) waypoint = models.ForeignKey("Waypoint", on_delete=models.CASCADE) created_timestamp = models.DateTimeField(auto_now_add=True) class Waypoint(models.Model): name = models.CharField(max_length=255) class Adventure(models.Model): waypoints = models.ManyToManyField("Waypoint", through='AdventureWaypoint', related_name='waypoints') objects = AdventureManager() How could I write a manager that annotates first_waypoint to every queryset? I tried the following, but unfortunately Subquery doesn't work as expected. Couldn't use F as well. class AdventureManager(models.Manager): def get_queryset(self): qs = super(AdventureManager).get_queryset() first_waypoint = AdventureWaypoint.objects.filter(adventure_id=OuterRef("id")).order_by('created_timestamp').first().waypoint return qs.annotate(first_waypoint=Subquery(first_waypoint, output_field=models.ForeignKey("Waypoint", on_delete=models.CASCADE, null=True, blank=True))) Do I have to resort to raw SQL or how can this be done via Django ORM? -
I will not let anyone enter my backend URL - Django rest framework
This problem I want to know how to secure my back and request a URL. At first, I didn’t put any authcation on my project. Now what I want to do is aunt - if anyone visits my URL, I will not let them see that page. Can anyone help with this? -
Django forms render error messages below input field?
How do I render error messages in django forms as "This field is required" if form is submitted blank. This is my forms.py class StudentForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password'] def __init__(self, *args, **kwargs): super(StudentForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' class StudentExtraForm(forms.ModelForm): class Meta: model = models.Student fields = ['classes', 'roll', 'blood_group', 'phone', 'dob', 'gender', 'address', 'status', 'image'] def __init__(self, *args, **kwargs): super(StudentExtraForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' This is form.html <form class="forms-sample" action="{% url 'student:add_student' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form1.non_field_errors }} {{ form2.non_field_errors }} <div class="form-group"> {{ form1.first_name.errors }} <label for="{{ form1.first_name.id_for_label }}">First Name:</label> {{ form1.first_name }} </div> <div class="form-group"> {{ form1.last_name.errors }} <label for="{{ form1.last_name.id_for_label }}">Last Name:</label> {{ form1.last_name }} </div> <div class="form-group"> {{ form1.username.errors }} <label for="{{ form1.username.id_for_label }}">Username:</label> {{ form1.username }} </div> <div class="form-group"> {{ form1.email.errors }} <label for="{{ form1.email.id_for_label }}">Email:</label> {{ form1.email }} </div> <div class="form-group"> {{ form1.password.errors }} <label for="{{ form1.password.id_for_label }}">Password:</label> {{ form1.password }} </div> <div class="form-group"> {{ form2.classes.errors }} <label for="{{ form2.classes.id_for_label }}">Select Class:</label> {{ form2.classes }} </div> <div class="form-group"> {{ form2.roll.errors }} <label for="{{ form2.roll.id_for_label }}">Roll No:</label> {{ form2.roll }} </div> <div class="form-group"> … -
Why does PyCharm show an empty Django Model Dependency Diagram
The PyCharm Pro IDE has a convenient feature called a Django Model Dependency Diagram, which visualizes the relations between your Django models. However, every so often, this diagram turns up blank, or does not work at all, without any error messages (except in the logs). There's a related issue here: https://youtrack.jetbrains.com/issue/PY-39831 What could possibly cause the Django Model Dependency Diagram to turn up empty? -
Delete firebase token not accepting token in parameters
I created an endpoint on my API to DELETE a firebase token. The token is given in parameters. This is my test unit, that works fine: @patch("pyfcm.FCMNotification.clean_registration_ids") def test_delete_firebase_token(self, fcm_mock): fcm_mock.return_value = "thetokengeneratedbyfirebase" token = "dummytoken" # create token FirebaseConnectionFactory(user=self.author, token=token) # delete token url = reverse("user-firebase", kwargs={"user_pk": self.author.pk}) response = self.client.delete(url, data={"token": token,}, format="json",) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertIsNone( FirebaseConnection.objects.filter( token=token, user_id=self.author.pk ).first() ) This is my view: def delete(self, request, user_pk): """ Delete Firebase token. """ user = request.user if int(user.pk) != int(user_pk): raise PermissionDenied serializer_class = self.get_serializer_class() serializer = serializer_class(data=request.data, context={"user_pk": user_pk}) serializer.is_valid(raise_exception=True) token = serializer.validated_data.get("token") FirebaseConnection.objects.filter(token=token, user_id=user_pk).delete() return Response({}, status=status.HTTP_200_OK) serializer: class FirebaseDeleteSerializer(serializers.ModelSerializer): class Meta: model = FirebaseConnection fields = ("token",) # noinspection PyMethodMayBeStatic def validate_token(self, token): user_pk = self.context["user_pk"] validate_token_helper(token) if not FirebaseConnection.objects.filter(token=token, user_id=user_pk).exists(): raise serializers.ValidationError( "You don't have permission to perform this action." ) return token So when I try this endpoint, I can't give the token in parameters. It gives an error that it's not valid. I guess that's because the ':' symbol in string? But I'm not sure how to solve it properly. Validation says I'm not sending token at all. -
Wagtail: How to remove summary items on the admin homepgae
I am trying to remove/customize the summary items on the admin homepage with the recommended hook construct_homepage_summary_items. Add or remove items from the ‘site summary’ bar on the admin homepage (which shows the number of pages and other object that exist on the site). I manage to add my own items but struggle to remove all of the default items. @hooks.register("construct_homepage_summary_items") def add_my_summary_items(request, items): items.append(MySummaryItem(request)) items.pop(0) items only includes my custom items and wagtail.admin.site_summary.PagesSummaryItem but not those for images and documents. Removing items with pop doesn't seem to be as elegant as it could be either. I hoped for some way along the lines of the construct_main_menu hook: menu_items[:] = [item for item in menu_items if item.name != 'explorer'] But I could not find a name identifier or an equivalent. How would I go on about it? -
Multiple objects returned in Django
So I have my code below, whenever I run it in admin and try to view that object returns and error: Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one c2 -- it returned 2! How do I resolve this error? models.py: from django.db import models import datetime import pytz from django.utils import timezone class c1(models.Model): name = models.CharField(max_length=30, default="Other") def __str__(self): return self.name class c2(models.Model): c1 = models.ForeignKey(c1, on_delete=models.CASCADE) name = models.CharField(max_length=30, default="Other") def __str__(self): return self.name class c3(models.Model): c2 = models.ForeignKey(c2, on_delete=models.CASCADE) name = models.CharField(max_length=30, default="Other") def __str__(self): return self.name class Task_manager(models.Manager): def create_Task(self, title): Task1 = self.create(title=title) return Task1 class Task(models.Model): STATUS = ( ('ONGOING', 'ONGOING'), ('COMPLETED','COMPLETED'), ) search=models.CharField(max_length=300, choices=search_title, default="OTHER") c1=models.ForeignKey(c1, on_delete=models.SET_NULL, null=True) c2=models.ForeignKey(c2, on_delete=models.SET_NULL, null=True) c3=models.ForeignKey(c3, on_delete=models.SET_NULL, null=True) title=models.CharField(max_length=30,default="Other") created=models.DateTimeField(default=timezone.now()) objects=Task_manager() class Meta: ordering = [ '-created'] def __str__(self): return self.title -
Like button without refreshing a Page using jQuery in Django
I have a view that controls my like and dislike functions perfectly. But I want a scenario were authenciated users can like a page without refreshing the whole Page. Here's my code for better understanding... Thanks in advance My View: def like_post(request): user = request.user if request.method == "POST": post_id = request.POST.get('post_id') post_obj = Blog.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like,created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value=='Like': like.value='Dislike' else: like.value = 'Like' like.save() return redirect('blog') Models: LIKE_CHOICES = { ('Like', 'Like'), ('Dislike','Dislike') } class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,blank=True) post = models.ForeignKey(Blog, on_delete=models.CASCADE,blank=True) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=15) def __str__(self): return self.user My HTML Html <div class="like-section"> {% if request.user.is_authenticated %} <form action="{% url 'like_post' %}" method="POST"> {% csrf_token %} <input type="hidden" name="post_id" value="{{blog.id}}"> {% if user not in blog.liked.all %} <button class="btn btn-sm btn-info" id="like" type="submit"><i class="fas fa-thumbs-up"></i></button> {% else %} <button class="btn btn-sm btn-info" id="like" type="submit"><i class="fas fa-thumbs-down"></i> </button> {% endif %} </form> {% endif %} </div> <small class="like-count{{blog.id}}">{{blog.liked.all.count}} Likes</small> And lastly my jQuery: <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click', '#like', function(event){ event.preventDefault(); var post_id = $(this).attr('value'); $.ajax({ type:'POST', url: '{% url "like_post" %}', data:{'id':post_id, 'csrfmiddlewaretoken':'{{csrf_token}}'}, success: function(data){ $('#like-section').html(data) } }); }); }); </script> I still … -
KeyError in BaseInlineFormset django
i'm trying to show error message in my formset , and i override clean method in baseinlineformset but it raise this error KeyError at /template/template-name/ 'quantity' class MyBaseInlineFormSet(BaseInlineFormSet): def clean(self): super(MyBaseInlineFormSet, self).clean() for form in self.forms: product = form.cleaned_data['product'] qnt = product.quantity_storage quantity = form.cleaned_data['quantity'] if quantity > qnt: print(f'quantity : {quantity} qnt : {qnt} test') #this show: (quantity : none 3 : test why quantity will bo none !? raise forms.ValidationError('you not have enough products') MyCustomInlineFormSet = inlineformset_factory( Parent,Child,form=ChildForm,formset=MyBaseInlineFormSet,extra=1) i also tried to display the massage from my form class def clean_quantity(self): product= self.cleaned_data.get('product') qnt = product.quantity_storage quantity = self.cleaned_data.get('quantity') if quantity > qnt: raise forms.ValidationError('you not have enough products') return quantity but the massage will show only if my parent class has an error ! and this is my views.py def get_context_data(self,*args,**kwargs): data = super().get_context_data(*args,**kwargs) if self.request.POST: data['formset'] = MyCustomInlineFormSet(self.request.POST) data['formset'].full_clean() else: data['formset'] = MyCustomInlineFormSet() return data def form_valid(self,form): context = self.get_context_data() formset= context['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid() and form.is_valid() and formset.cleaned_data!={}: formset.instance = self.object formset.save() return super().form_valid(form) i also called the error massage in my template in this format {% if formset.quantity.errors %} <div class="error mx-auto"> {{formset.quantity.non_field_errors}} {{formset.quantity.errors}} </div> {% endif %} is there … -
Django File update not saving to folder
I am trying to update a form in which there is a input type file. But while saving the changes, name of the file is updated to database (MySQL) but not storing in folder. While uploading for the first time it works perfectly. upload_to option of FileField in modals is working fine and file is uploading to that upload_to path. But When I am trying to update the file, only file name name is updating to database. I can't share complete code due to non disclosure agreement with client. Few other fields are also there in form and everything is updating in database correctly. Only file is not uploading to specified path. Any help is appreciated. I tried many solutions available but none of them are working. Models.py Class Task(models.Model): attached_resources = models.FileField(upload_to='project/images/task/',default='') edit-task.html <form method="post" action="/app/task-detail/" enctype="multipart/form-data"> {% csrf_token %} <input name="task_file" type="file"> </form> views.py def task_detail(request): if request.method == 'POST': task_id = request.POST['task_id'] task_file = request.FILES['task_file'] task_to_edit = Task.objects.filter(id=task_id).update(attached_resources=task_file) -
Implementing a PostgreSql query with Django
Imagine a model in Django like: class MyModel(models.Model): data = JSONField() . . . The data is stored like this: {'1':'value1', '2':'value2', '3':'value3', ...}. The data keys are ['1', '2', '3', ...]. The query aim is to count the number of MyModels which have ids like '1' or '2' in data keys. The PostgreSql query is like: SELECT jsonb_object_keys(data) AS keys, COUNT(*) AS number FROM MyModel WHERE data ?| array['1','2'] GROUP BY keys The result is: keys | number -----+------- '1' | 150 '2' | 300 This means there are 150 MyModels that have '1' in their data keys and 300 MyModels with '2' in data keys. Now the question is how to implement the query with Django? -
DIfference Between two dates in django queryset
models.py class Operations(models.Model): model = models.CharField(max_length=100) process_status = models.CharField(max_length=100) created_date = models.DateField(null=True) views.py from django.db.models import DurationField, ExpressionWrapper, F from datetime import date today = date.today() created_queryset=Operations.objects.filter(process_status__startswith='Created').values('model').aggregate(days_awaiting=ExpressionWrapper(F('created_date')-F(today.strftime("%Y-%m-%d")),output_field=DurationField())).order_by('-created_date') I need output in no of days from today to the 'created_date' (Date format from Mysql database is in 2016-08-20) -
After i have installed allauth for django ModuleNotFoundError while migrating
I have installed django-allauth by pip install django-allauth. movies is the name of my app error image -
How to redirect to an explicitly named url in Django?
I am trying to have a redirect to a specific page base on a variable in my views.py: redirect(f'feed/user/{first_user}') But by having it like this it redirects me to the url: feed/search/feed/user/first_user instead I would like to redirect to the url feed/user/first_user I know that the feed/search/ part is appended because the search url in my urls.py calls the function that should redirect but I would like to keep it that way and only change the redirect. -
when click the send button showing full html source code in django
i just created a django form, once click the send button showing full html codes under the form. but message sent successfully. can you tell me how to resolve the issueenter image description here -
Refactoring multiple if conditions with Q() chaining in querystring evaluation Python/Django
I am working on cloning airbnb room registration system in Django. I have a class based view (HTTP get method) that filters rooms stored in the database according to various query string key value options and returns those rooms. Filter options provided through query string are: location = request.GET.get('location') adults = int(request.GET.get('adults', 0)) children = int(request.GET.get('children', 0)) infants = request.GET.get('infants', 0) min_cost = float(request.GET.get('min_cost', 0)) max_cost = float(request.GET.get('max_cost', sys.maxsize)) property_type = request.GET.get('property_type', None) place_type = request.GET.get('place_type', None) check_in = request.GET.get('checkin', None) check_in_date = datetime.datetime.strptime(check_in, '%Y-%m-%d') if check_in else None check_out = request.GET.get('checkout', None) check_out_date = datetime.datetime.strptime(check_out, '%Y-%m-%d') if check_out else None min_beds = request.GET.get('min_beds', None) min_bedrooms = request.GET.get('min_bedrooms', None) min_baths = request.GET.get('min_baths', None) amenities = request.GET.getlist('amenities', None) languages = request.GET.getlist('languages', None) I decided to store all filter expressions as Q() objects using &= operation. Rooms with already booked dates and host-chosen unavailable dates ('blockeddate') that are in conflict with provided check_in_date and check_out_date will be filtered out. After storing all Q() expression in a variable called 'queries', I passed 'queries' as an argument to Room.objects.filter() function. 'min_beds', 'min_bedrooms', and 'min_baths' options were evaluated after initial filtering so that I could perform annotate() function on the filtered queryset. Following code works, … -
Trying to filter data based on start and end date
I am using django filter package to filter data based on start, end date and class of dues fields defined in my models. The problem is If I select only class_of_fields data is filtered but when I select start and end_date along with class_of_dues no data is filtered below are my codes models.py class DuesLevy(models.Model): class_of_dues = models.CharField(max_length=30, default=options.CHOOSE, choices=options.CLASS_OF_DUES, blank=True) payment_circle = models.CharField(max_length=30, default=options.CHOOSE, choices=options.PAYMENT_CIRCLE) payment_option = models.CharField(max_length=30, default=options.CHOOSE, choices=options.PAYMENT_OPTION) amount = models.DecimalField(max_digits=8, decimal_places=2) transaction_id = models.CharField(max_length=30, null=True, blank=True, editable=False, default=my_rand) payment_channel = models.CharField(max_length=30, default=options.CHOOSE, choices=options.PAYMENT_CHANNEL_TYPE) payment_date = models.DateField() start_date = models.DateField() end_date = models.DateField() date_recorded = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) description = models.TextField(blank=True, null=True) def __str__(self): return self.amount filter.py from .models import DuesLevy, User from django_filters import widgets import django_filters from django import forms from django_select2 import forms as s2forms from backend import options class DuesFilter(django_filters.FilterSet): class_of_dues = django_filters.CharFilter( widget=s2forms.Select2Widget(choices=options.CLASS_OF_DUES, attrs={'class':'form-control'})) start_date = django_filters.DateFilter(field_name='payment_date', widget=forms.DateInput(attrs={'class':'form-control', 'type':'date'}), lookup_expr='lt',label='Start Date') end_date = django_filters.DateFilter(field_name='payment_date', widget=forms.DateInput(attrs={'class':'form-control', 'type':'date'}), lookup_expr='gt',label='End Date') user = django_filters.ModelChoiceFilter(queryset=User.objects.all(), widget=s2forms.ModelSelect2Widget( attrs={'class': 'form-control'}, model=User, search_fields=['member_id__icontains'], )) class Meta(): model = DuesLevy fields = ('class_of_dues', 'start_date', 'end_date') views.py class ListMemberDues(LoginRequiredMixin, View): login_url = '/backoffice/' def get(self, request): queryset = DuesLevy.objects.filter(user=request.user) query_filter = DuesFilter(request.GET, queryset) context = { 'form':query_filter.form, 'query':query_filter, } … -
How would I customize my form for uploading images?
I was wondering if someone know why my field for uploading pictures is like this? I can't select new pictures from my computer to upload, only ones already uploaded in the model instances through my Admin panel. It looks this way on my all of my routes. Here is link for my github repository - https://github.com/eonbre/DogApi1/tree/master/DrWebTestProject I would also love if someone would help me to return a random image on my /breeds//random route. enter image description here -
Python app returns MySQL data 3 times instead of 1
I have a simple MySQL table with the following meta and content +--------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | Name | varchar(100) | YES | | NULL | | | School | varchar(45) | YES | | NULL | | +--------+--------------+------+-----+---------+----------------+ +----+---------+--------+ | id | Name | School | +----+---------+--------+ | 1 | Artem | AU | | 2 | Simon | AAU | | 3 | Steffen | AU | +----+---------+--------+ from which I'm trying to fetch all data using a simple python app, however my output is returned like this when I run the app(click to enlarge photo): but what I expect it to return is (1, 'Artem', 'AU'), (2, 'Simon', 'AAU'), (3, 'Steffen', 'AU') only. The Python code is import MySQLdb from django.shortcuts import render from django.http import HttpResponse def getFromDB(): data = [] db = MySQLdb.connect(host="ip", user="user", passwd="pw", db="db") cur = db.cursor() cur.execute("SELECT * FROM students") students = cur.fetchall() for student in students: data.append(students) return data def index(request): return HttpResponse(getFromDB()) What am I missing? -
Django Pedigree Table
I am in the process of creating a site with Django for my wife and her dog club. I've seen many projects in php but none in python. I'm up for tackling this in any direction! I am wanting to dynamically create a table like this: My model looks like such (simplified for the question): class Dogs(models.Model): did = models.IntegerField(blank=true, null=true) name = models.TextField(db_column='name', blank=true, null=true) sire = models.TextField(db_column='Sire', blank=true, null=true) dam = models.TextField(db_column='Dam', blank=true, null=true) I've created a few different recursive functions that do correctly determine the ancestors of a child, but I am having difficulty outputting in a meaningful manner. Example: dog = [] def pedigree(did, max): con = sqlite3.connect('dog.sqlite3') con.row_factory cursor = con.execute('SELECT "Call Name", ROUND(((JulianDay("now") - JulianDay("Date of Birth"))/365.25),1), "Sex" FROM dogs where did IS %s ' % did).fetchall() for row in cursor: name, age, gender = row[0], row[1], row[2] sql = "SELECT a.Sire, a.Dam, s.'Registered Name', d.'Registered Name' FROM dogs a INNER JOIN dogs s ON a.Sire = s.did INNER JOIN dogs d ON a.Dam = d.did WHERE a.did = " printTree(sql, did, name, 0, max) return dog def printTree(stmt, did, name, N, max): rspan = 2**(max-N) if (rspan > 1): #print('rowspan= ', rspan, name) … -
django login form returns 'AnonymousUser' object has no attribute '_meta'
I am working on a django web app. In this web app, I have a login page. But when I use the click the login button, I get the following error message 'AnonymousUser' object has no attribute '_meta' I tried looking for this online and found these links in StackOverflow. link1 and link2. But the answers provided in these links do not seem to be working for me. This is my code so far views.py def login_page(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) user = form.get_user() login(request, user) if form.is_valid(): return redirect('global:homepage') else: form = AuthenticationForm() return render(request, 'accounts/login.html', {'form': form}) login.html <form class="" action="{% url 'accounts:login' %}" method="post"> {% csrf_token %} {% for field in form %} <p> <div class="form-group"> {% render_field field class="form-control" placeholder=field.label %} {% if field.help_text %} <p class="help-block"><small>{{ field.help_text }}</small></p> {% endif %} </div> {% for error in field.errors %} <p style="color: red">{{ error|add_class:'text-danger' }}</p> {% endfor %} </p> {% endfor %} <button type="submit" class="btn btn-primary btn-block btn-lg mt-5">Log in</button> </form> Not sure what I am doing wrong or what the error message means