Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to setup login page using django-microsoft-auth in a django project
I am using django-microsoft-auth in my Django project. I followed this guide. Now, I'm able to log in through Microsoft account(address: http://localhost:8000/admin ) but I don't know how to add a view that will say "Login using Microsoft" and how to link that view with Microsoft authentication page. It will be great if someone can tell me how to do this. -
What is the right way of including and extending templates in django
I have a page template, as shown. <!DOCTYPE html> <html> <head> <base href=''> <meta charset='utf-8'></meta> <meta name='description' content=''></meta> <meta name='author' content=''></meta> <meta name='keywords' content=''></meta> <meta name='viewport' content='width=device-width, initial-scale=1'></meta> <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/> <title></title> </head> <body> {% include "waffle.html" %} </body> </html> And a waffle template as shown {% block content%} {% endblock %} And an index thats supposed to extend the waffle, as shown: {% extends "waffle.html" %} {% block content%} The home page look and feel starts here. {% endblock %} And a view thats supposed to display my templates, as shown from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request, "index.html") My problem is that this is not working, and I have absolutely no idea. I am coming from php and trying to learn django, but this templating thing is frustrating me. Any ideas of what I might be doing wrong here -
How to add a user in the admin page?(getting error)
Django version: 2.1.5 When I tried to add a user in the admin page it gave me this error: OperationalError at /admin/auth/user/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://localhost:8000/admin/auth/user/add/ Django Version: 2.1.5 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Users\themi\Envs\project\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 298 Python Executable: C:\Users\themi\Envs\project\Scripts\python.exe Python Version: 3.8.2 Python Path: ['C:\\Users\\themi\\OneDrive\\Desktop\\myfirstdjango', 'C:\\Users\\themi\\Envs\\project\\Scripts\\python38.zip', 'c:\\users\\themi\\appdata\\local\\programs\\python\\python38-32\\DLLs', 'c:\\users\\themi\\appdata\\local\\programs\\python\\python38-32\\lib', 'c:\\users\\themi\\appdata\\local\\programs\\python\\python38-32', 'C:\\Users\\themi\\Envs\\project', 'C:\\Users\\themi\\Envs\\project\\lib\\site-packages'] Server time: Sun, 22 Mar 2020 07:47:59 +0000 I know this question has been answered before but the solutions didn't work for me. -
django annotate unexpected limit 21
I want use django ORM to finish count group by, but select sql unexpected limit 21 every time. I don't want the limit, why limit 21 appear, and how can I get all data? model: class Company(models.Model): company_no = models.CharField(primary_key=True, max_length=128) name = models.CharField(max_length=128) is_test = models.BooleanField(default=False) class Meta: db_table = 'company' class User(models.Model): symbol = models.BigIntegerField(primary_key=True) is_test = models.BooleanField(default=False) class Meta: db_table = 'user' class UserEmploy(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, db_column='symbol', to_field='symbol', related_name='employ') company = models.ForeignKey(Company, on_delete=models.CASCADE, to_field='company_no', db_column='company_no', related_name='user_employ') class Meta: db_table = 'user_employ' django code in my views: employ_qs_exclude_test = UserEmploy.objects\ .exclude(user__is_test__in=utils.IS_TEST_MODE)\ .values("company__name") \ .annotate(employ_count=Count('user', distinct=True))\ .order_by('company') sql log: SELECT `company`.`name`, COUNT(DISTINCT `user_employ`.`symbol`) AS `employ_count` FROM `user_employ` INNER JOIN `user` ON (`user_employ`.`symbol` = `user`.`symbol`) INNER JOIN `company` ON (`user_employ`.`company_no` = `company`.`company_no`) WHERE NOT (`user`.`is_test` IN (1)) GROUP BY `company`.`name`, `company`.`created_at` ORDER BY `company`.`created_at` DESC LIMIT 21; -
How to query mutations in react and fetch results in a div
All the examples I have been coming across they are fetching Inside a list box which is not understandable . Please help its really urgent. Thank you so much in advance -
Programming Error: relation "first_app_people" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "first_app_people"
I am trying to deploy my django app on heroku. But there is error which I don't understand what type of error is this.Please help to solve this error: Programming Error: relation "first_app_people" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "first_app_people" models.py class People(models.Model): name = models.CharField(max_length=220) slug = models.SlugField(unique=True) money = models.IntegerField() status = models.CharField(max_length=120, null=True, choices=Status) date = models.DateTimeField(default=datetime.datetime.now) def __str__(self): return self.name def get_absolute_url(self, *args, **kwargs): return reverse("first_app:detail", kwargs={"slug": self.slug}) views.py from django.shortcuts import render, get_object_or_404, redirect from .models import People from .forms import PeoplesForm def home_page(request): form = People.objects.all() stock = form.count() sell = form.filter(status='Fowara_Chowk').count() sold = form.filter(status='Station').count() context = { 'form': form, 'stock': stock, 'sold': sold, 'sell': sell, } return render(request, 'index.html', context) def create_view(request): form = PeoplesForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() return redirect('/') context = { 'form': form } return render(request, 'create.html', context) def detail_view(request, slug): form = get_object_or_404(People, slug=slug) context = { 'form': form } return render(request, 'detail.html', context) def update_view(request, slug): form = People.objects.get(slug=slug) update_form = PeoplesForm(instance=form) if request.method == "POST": update_form = PeoplesForm(request.POST or None, instance=form) if update_form.is_valid(): update_form.save() return redirect('/') context = { 'form': update_form, } return render(request, 'update.html', context) def delete_view(request, … -
Folium map not getting rendered within iFrame in django
I am trying to use folium maps within django. From views.py, map_html is passed onto sample_map.html as context variable. Inside sample_map.html, I am trying to render the map_html within an iFrame. (I have to use iFrame as folium returns complete html) Issue: The map is getting rendered, but outside of iFrame. I am able to render some plain html like <html><body>It works</body></html> onto the iframe without any issues. views.py import folium def show_map(request): m = folium.Map([17.3850, 78.4867], zoom_start=10) map_html = m.get_root().render() context = {'map_html': map_html} return render(request, 'sample_map.html', context) sample_map.html <!DOCTYPE html> <html lang="en"> <body> <iframe id="foo"></iframe> <script src="https://code.jquery.com/jquery-3.4.1.min.js" .. ></script> <script> $(document).ready(function() { var iframe = document.getElementById('foo'), iframedoc = iframe.contentDocument || iframe.contentWindow.document; // iframedoc.body.innerHTML = "<html><body>Content gets rendered within iframe as expected</body></html>" iframedoc.body.innerHTML = "{{map_html|safe}}" // content gets rendered outside the iframe }); </script> </body> </html> sdfas -
Jquery autocomplete not filtering JSON data from django
I tried the Jquery autocomplete for entering country name in a input field. Instead it is binding all the JSON data and the search does not filter from the JSON data. JQUERY Autocomplete function for country $("#ddlCountry").autocomplete({ source: function(request, response) { $.ajax({ type: 'GET', url: 'country', dataType: "json", data: { term: request.term }, success: function(data) { console.log(request.term) response($.map(data, function(item, key) { return { label: item.country_name, value: item.id } })); }, error: function(xhr) { console.log('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText); } }); }, minLength: 2, select: function(event, ui) { e.preventDefault() }, focus: function(event, ui) { e.preventDefault() }, }); Views.py def country_list(request): if request.method == "GET": if request.is_ajax(): obj_country_list = Country.objects.values("id", "country_name") return HttpResponse(json.dumps(list(obj_country_list))) JSON DATA {"id": 1, "country_name": "Afghanistan"}, {"id": 2, "country_name": "Albania"}, {"id": 3, "country_name": "Algeria"}, {"id": 4, "country_name": "Andorra"}, {"id": 5, "country_name": "Angola"}, {"id": 6, "country_name": "Antigua and Barbuda"}, {"id": 7, "country_name": "Argentina"}, {"id": 8, "country_name": "Armenia"}, {"id": 9, "country_name": "Australia"}, {"id": 10, "country_name": "Austria"}, {"id": 11, "country_name": "Azerbaijan"}, {"id": 12, "country_name": "Bahamas"}, {"id": 13, "country_name": "Bahrain"}, {"id": 14, "country_name": "Bangladesh"}, {"id": 15, "country_name": "Barbados"}, {"id": 16, "country_name": "Belarus"}, {"id": 17, "country_name": "Belgium"}, {"id": 18, "country_name": "Belize"}, {"id": … -
Is it safe to send form's data (POST) asynchronously to the server?
I would like to know (I know almost nothing about this) if it's dangerous to send a form using the post method and a function like the following one. I started to questioning this method because the html code can be modified. If not, what should I change? As example, the following function is provided: script.js function fname(){ var https = new XMLHttpRequest(); https.open("POST", "url", true); https.setRequestHeader('X-CSRFToken', getCookie('csrftoken')); var varname = "data_from_input"; https.send(varname); } -
Define two fields on serializer in DRF in which one of them is required
I want to create a serializer that let users to login with their username or phone number, Now if they use a phone number or username I need different validations. I know that I can achieve this in the view, however, I'm looking for a solution to handle this situation in the serializer. -
How to handle media file errors in django templates?
Here I successfully uploaded files in database(working fine). The issue here is file is stored in the database and if in case the media folder gets deleted it will raise an error [WinError 2] The system cannot find the file specified: ... So my question is how can I handle this error. If the file is in database but not in the media folder then I want to handle this error and display the template without error. How can I do this ? template {% for document in documents %} <tr> <td>{{forloop.counter}}</td> <td>{{document.filename|truncatechars:15}}</td> <td>{{document.file.size|filesizeformat}}</td> <td>{{document.category}}</td> <td>{{document.file.url}}</td> <tr> {% endfor %} -
django pagination category wise
How Can use pagination in my Category page in django def englishStatus(request): allpost=[] catpost=Content.objects.values('category','id') cats={item['category'] for item in catpost} for cat in cats: if cat=="englishStatus": post=Content.objects.filter(category=cat) n=len(post) allpost.append([post,range(1,n),n]) paginator=Paginator(allpost,4) page=request.GET.get('page') try: allpost=paginator.page(page) except PageNotAnInteger: allpost=paginator.page(1) except EmptyPage: allpost=paginator.page(paginator.num_pages) params={'allpost':allpost} return render(request,'status/englishStatus.html',params) I cant able to do pagination -
how to use ajax in postlistview as well as in postdetailview
I have a post detail where i successfully use ajax to like the post section so if anyone like the post it is asynchronously referesh the section. however i can't do it in the post list view. its not working asynchronously. Anyone who can help me to solve it. here is my views.py: @login_required def like_post(request): # posts = get_object_or_404(Post, id=request.POST.get('post_id')) posts = get_object_or_404(post, id=request.POST.get('id')) is_liked = False if posts.likes.filter(id=request.user.id).exists(): posts.likes.remove(request.user) is_liked = False else: posts.likes.add(request.user) is_liked = True notify.send(request.user, recipient=posts.author, actor=request.user, verb='liked your post.', target=posts, nf_type='liked_by_one_user') context = {'posts':posts, 'is_liked': is_liked, 'total_likes': posts.total_likes(),} if request.is_ajax(): html = render_to_string('blog/like_section.html', context, request=request) return JsonResponse({'form': html}) if request.is_ajax(): html = render_to_string('blog/likes_home.html', context, request=request) return JsonResponse({'form': html}) the likes_home section is for postlistview my likes_home.html: <script> $(document).on('click', '#like', function(event){ event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: '{% url "like_post" %}', data: {'id':pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: 'json', success: function(response){ $('#like-home').html(response['form']) console.log($('#like-home').html(response['form'])); }, error: function(rs, e){ console.log(rs.responseText); }, }); }); </script> <form action="{% url 'like_post' %}" method="POST"> {% csrf_token %} {% if post.is_liked %} <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-danger">dislike</button> {% else %} <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-primary">like</button> {% endif %} </form> and my … -
set_password() method is saving plain text
When I'm saving the user from the view and writing the codes it is saving the password as plain text but when I'm using the same set_password() method in the shell, it's saving the hashed password perfectly. Kindly point out where I'm making the mistake. Actually I'm saving the data directly from an excel sheet. username="username" password="password" firstName="first" lastName="lastname" user=User.objects.create( firstName = firstName, lastName = lastName, username = username, ) user.set_password(password)) user.is_student = True user.save() user.school = request.user.school user_inst.save() user_ins = User.objects.get(username=username) -
AttributeError: module 'django.contrib.auth.admin' has no attribute 'site'
I encountered the error AttributeError: module 'django.contrib.auth.admin' has no attribute 'site' .I cant figure out where i went wrong.Can anyone help? here is the code in urls.py. from django.contrib.auth import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('adoption.urls')), path('accounts/', include('accounts.urls')), path('admin/', admin.site.urls) ] urlpatterns= urlpatterns+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to use specifice blocks from another html file in Django template?
Suppose I have 2 files base.html and home.html. home.html: {% block block1 %} b1 {% endblock %} {% block block2 %} b2 {% endblock %} {% block block3 %} b3 {% endblock %} ... and many more base.html: <!-- need extending other files so it is not an option. --> {% extends 'othertemplate.html' %} {% include 'home.html' %} <-- I only want block2 from this file here. How do I do this when displaying 'base.html'? -
Django ModelForm's DateTime value being localized/translated with localization turned off
So I'm working on this Activity management platform, we are using Django 3.0.4. Before I expose my problem, I must say that I'm somewhat new to Django and python itself. My current objetive is to allow the administrator to set specific dates for specific events. Initially the page must show the current dates and details. That I can already the do with the code shown below This is an example of the model used to store the dates class Dates(models.Model): id = models.AutoField(db_column='ID', primary_key=True) datestart = models.DateTimeField(db_column='DateStart') dateend = models.DateTimeField(db_column='DateEnd') class Meta: db_table = 'Dates' This is my form class dateForm(forms.ModelForm): class Meta: model = Dates exclude = ['id'] And this is my current view function def editdates(request): dates_current = Dates.objects.get(id=1) dates_form = dateForm(instance=dates_current) if request.method == 'POST': submitted_data = request.POST.copy() #Might need to change incoming data before saving to db dates_form = diaAbertoSettingsForm(submitted_data, instance=dates_current) #Generate form with existing data if dates_form.is_valid(): dates_form.save() return render(request=request, template_name = 'dates/edit.html', context = {'form': dates_form}) The same page that shows the data (dates) must also allow you to submit a change, this would be relatively easy to do. The real problem starts when I want to submit the form. Currently, I do the … -
How to make notifications from one app to another app in django?
I am making one e-commerce website and i am just trying to make notifications from admin side to user side both are diffrent app in django... My problems is how to make notifications in admin side (one app)when i click the button send the messages and display the notifications or message in userside(other app) -
Django range filter datetimeshortcuts
Using Django-admin-rangefilter 0.5.4 with djanog 3.0.4 and Grappelli 2.14. Getting error: can't find variable: DateTimeShortsCuts in production when using rangefilter. which results in no date picker. While in development it's working fine. The date time picker working in Django Admin. Can someone suggest how to debug/correct this. -
how to display model questions and options and get the choice choosen by user in django
i'm creating quiz website in django...i'm confused in how can i get the quetions and options of model and display it into the page.and how i campare the choosen options with the result model answer and increament the score. here is my MODELS.PY class question(models.Model): question=models.CharField(max_length=100) def __str__(self): return self.question class options(models.Model): question=models.ForeignKey(question,default=1,on_delete=models.SET_DEFAULT) op1=models.CharField(max_length=20) op2=models.CharField(max_length=20) op3=models.CharField(max_length=20) op4=models.CharField(max_length=20) # def __str__(self): # return self.question class answer(models.Model): question=models.ForeignKey(question,default=1,on_delete=models.SET_DEFAULT) result=models.CharField(max_length=50) template(quizpage.html) <body> <h2>Hello, {{username}}</h2> <div id="nav"> <a href="/logout">Logout</a> </div> <br> {% for i in ques %} <h2>{{i.optionsid}}{{i.question}}</h2> <br> <form action="/next" method="POST"> <input type="radio" name="answer" value="a"><span>{{i.op1}}</span> <input type="radio" name="answer" value="a"><span>{{i.op2}}</span> <input type="radio" name="answer" value="a"><span>{{i.op3}}</span> <input type="radio" name="answer" value="a"><span>{{i.op4}}</span> <input type="submit" value="next"> </form> {% endfor %} </body> Views.py def addscore(request): score=0 if request.method=='POST': ans=request.POST.get('answer') ?????? return render(request,'nextpage') else: return render(request,'quizapp/quizpage.html') def nextquestion(request): pass def showtest(request): ops=models.options.objects.filter(id='id') return render(request,'quizapp/quizpage.html',{'ops':ops}) -
I made django application but can't orchestration in GKE
I made django appilcation in reference to official manual. https://cloud.google.com/python/django/kubernetes-engine?hl=ja After pushing the Docker image, I got bellow message in EXTERNAL-IP page. Django Version: 2.2.5 Exception Type: OperationalError Exception Value: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0") When I develop in local, I can connect to Cloud SQL instance. But, it seems that GKE resource can't connect to Cloud SQL instance. I think I made secret for instance-level access and database access correctly according to manual. When I create secret for instance-level access, I type bellow command. kubectl create secret generic cloudsql-oauth-credentials --from-file=credentials.json=appname-0000-*******.json When I create secret for database access, I type bellow command. kubectl create secret generic cloudsql --from-literal=username=user --from-literal=password=*** I edited in polls.yaml. In polls.yaml, I edited like bellow. # [START proxy_container] - image: gcr.io/cloudsql-docker/gce-proxy:1.05 name: cloudsql-proxy command: ["/cloud_sql_proxy", "--dir=/cloudsql", "-instances=appname-0000:asia-northeast1:mysqlinstance=tcp:5432", "-credential_file=/secrets/cloudsql/credentials.json"] In settings.py, I coded about DATABASES like bellow. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'polls', 'USER': os.getenv('DATABASE_USER'), 'PASSWORD': os.getenv('DATABASE_PASSWORD'), 'HOST': '127.0.0.1', 'PORT': '5432', } } What can cause this error? Please let me know the solution! -
How to send static file link as variable in `include` tag in Django?
Suppose I have a base.html and home.html. The base.html file has: {% include 'home.html' with thelink='hard/coded/link' %} And home.html contains: The link of static file is : {{ thelink }} This works well so far. But now, I want to do this: base.html: {% load static %} {% include 'home.html' with thelink={% static 'link' %} %} I know this will not work. So how do I send a variable with static files references in the include tag? -
UnicodeDecodeError: 'gbk' codec can't decode byte 0x82 in position 402: illegal multibyte sequence
when I use pipenv install django-mdeditor,then happend this question as follows: pipenv install -e git+https://github.com/pylixm/django-mdeditor.git@master#egg=django-mdeditor Installing -e git+https://github.com/pylixm/django-mdeditor.git@master#egg=django-mdeditor… Adding django-mdeditor to Pipfile's [packages]… Installation Succeeded Pipfile.lock (0c05dd) out of date, updating to (5c4038)… Locking [dev-packages] dependencies… Locking [packages] dependencies… Locking Failed! ... Traceback (most recent call last): UnicodeDecodeError: 'gbk' codec can't decode byte 0x82 in position 402: illegal multibyte sequence how can I solve it? -
Overwrite create method for a Django restframework nested serializer
I am trying to use nested writable serializer in django-rest-framework. When I send a POST request with following data: { "acc_name": "Salary Card", "acc_type_id": { "id": 2, "acc_type_name": "Debit Card" }, "credit_amt": null, "bill_dt": null, "due_dt": null, "balance": "0.00", "comments": null } I got an error: Cannot assign "OrderedDict([('acc_type_name', 'Debit Card')])": "Accounts.acc_type_id" must be a "AccountTypes" instance. I actually passed id for AccountTypes, but why restframework remove it automatically? How can I resolve this problem? How can I create a new account with existing account type? Views: class AccountTypesViewSet(ListAPIView): name = __name__ pagination_class = None queryset = AccountTypes.objects.filter(active='Y') serializer_class = AccountTypesSerializer class AccountsViewSet(viewsets.ModelViewSet): pagination_class = None queryset = Accounts.objects.all() serializer_class = AccountsSerializer Models: class AccountTypes(models.Model): id = models.AutoField(primary_key=True, editable=False) acc_type_name = models.CharField(max_length=50) active = models.CharField(max_length=1, default='Y') class Meta: db_table = f'"{schema}"."taccount_types"' managed = False class Accounts(models.Model): id = models.AutoField(primary_key=True, editable=False) acc_name = models.CharField(max_length=1024) acc_type_id = models.ForeignKey( to=AccountTypes, db_column='acc_type_id', related_name='accounts', on_delete=models.DO_NOTHING ) credit_amt = models.DecimalField(max_digits=11, decimal_places=2, null=True) bill_dt = models.DateField(null=True) due_dt = models.DateField(null=True) balance = models.DecimalField(max_digits=11, decimal_places=2, default=0) comments = models.CharField(max_length=1024, null=True) class Meta: db_table = f'"{schema}"."taccounts"' managed = False Serializers: class AccountTypesSerializer(serializers.ModelSerializer): class Meta: model = AccountTypes fields = ('id', 'acc_type_name') class AccountsSerializer(serializers.ModelSerializer): # acc_type = serializers.SlugRelatedField(slug_field='acc_type_name', source='acc_type_id', read_only=True) acc_type_id … -
Django Allauth Encrypt Email in account_emailaddress Table
I have successfully encrypted the user email via a custom user model with https://github.com/incuna/django-pgcrypto-fields. However, for some reason allauth does not encrypt the same email under the account_emailaddress table. This table is used to identify if a user has verified their email and if their email is their primary email. How would I be able to encrypt the email in that table? Code: Settings.py: PGCRYPTO_KEY = 'hello' INSTALLED_APPS = [ 'pgcrypto', ] Custom User Model models.py: from pgcrypto import fields class CustomUserManager(BaseUserManager): def _create_user(self, email, password,is_staff, is_superuser, **extra_fields): now = timezone.now() if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email,is_staff=is_staff, is_active=True,is_superuser=is_superuser, last_login=now,**extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): return self._create_user(email, password, False, False,**extra_fields) def create_superuser(self, email, password, **extra_fields): return self._create_user(email, password, True, True,**extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): objects = CustomUserManager() email = fields.EmailPGPSymmetricKeyField() identifier = models.CharField(unique=True, max_length=50, default=uuid.uuid1) username = models.CharField(_('username'), max_length=30, blank=True, default='', unique=True) USERNAME_FIELD = 'username' first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.')) is_mod = models.BooleanField(_('moderator status'), default=False, help_text=_('Designates whether the user can …